Programs & Examples On #Dataset

A dataset is a collection of data, generally represented in tabular form, with columns signifying different variables and rows signify different members of the set. If you are looking for a freely available dataset for any purpose, please consider asking your question on https://opendata.stackexchange.com.

How to fill Dataset with multiple tables?

Method Load of DataTable executes NextResult on the DataReader, so you shouldn't call NextResult explicitly when using Load, otherwise odd tables in the sequence would be omitted.

Here is a generic solution to load multiple tables using a DataReader.

// your command initialization code here
// ...
DataSet ds = new DataSet();
DataTable t;
using (DbDataReader reader = command.ExecuteReader())
{
  while (!reader.IsClosed)
  {
    t = new DataTable();
    t.Load(rs);
    ds.Tables.Add(t);
  }
}

Reading DataSet

If this is from a SQL Server datebase you could issue this kind of query...

Select Top 1 DepartureTime From TrainSchedule where DepartureTime > 
GetUTCDate()
Order By DepartureTime ASC

GetDate() could also be used, not sure how dates are being stored.

I am not sure how the data is being stored and/or read.

Should I Dispose() DataSet and DataTable?

I call dispose anytime an object implements IDisposeable. It's there for a reason.

DataSets can be huge memory hogs. The sooner they can be marked for clean up, the better.

update

It's been 5 years since I answered this question. I still agree with my answer. If there is a dispose method, it should be called when you are done with the object. The IDispose interface was implemented for a reason.

Datatable vs Dataset

One feature of the DataSet is that if you can call multiple select statements in your stored procedures, the DataSet will have one DataTable for each.

Direct method from SQL command text to DataSet

public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";

public static DataSet LoaderDataSet(string StrSql)      
{
    SqlConnection cnn;            
    SqlDataAdapter dad;
    DataSet dts = new DataSet();
    cnn = new SqlConnection(textDataSource);
    dad = new SqlDataAdapter(StrSql, cnn);
    try
    {
        cnn.Open();
        dad.Fill(dts);
        cnn.Close();

        return dts;
    }
    catch (Exception)
    {

        return dts;
    }
    finally
    {
        dad.Dispose();
        dts = null;
        cnn = null;
    }
}

How to add header to a dataset in R?

this should work out,

      kable(dt) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
  kable_styling(c("striped", "bordered")) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
  add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
  add_header_above(c(" ", "Group 6" = 6))

for more you can check the link

How to delete the first row of a dataframe in R?

While I agree with the most voted answer, here is another way to keep all rows except the first:

dat <- tail(dat, -1)

This can also be accomplished using Hadley Wickham's dplyr package.

dat <- dat %>% slice(-1)

A simple explanation of Naive Bayes Classification

I try to explain the Bayes rule with an example.

What is the chance that a random person selected from the society is a smoker?

You may reply 10%, and let's assume that's right.

Now, what if I say that the random person is a man and is 15 years old?

You may say 15 or 20%, but why?.

In fact, we try to update our initial guess with new pieces of evidence ( P(smoker) vs. P(smoker | evidence) ). The Bayes rule is a way to relate these two probabilities.

P(smoker | evidence) = P(smoker)* p(evidence | smoker)/P(evidence)

Each evidence may increase or decrease this chance. For example, this fact that he is a man may increase the chance provided that this percentage (being a man) among non-smokers is lower.

In the other words, being a man must be an indicator of being a smoker rather than a non-smoker. Therefore, if an evidence is an indicator of something, it increases the chance.

But how do we know that this is an indicator?

For each feature, you can compare the commonness (probability) of that feature under the given conditions with its commonness alone. (P(f | x) vs. P(f)).

P(smoker | evidence) / P(smoker) = P(evidence | smoker)/P(evidence)

For example, if we know that 90% of smokers are men, it's not still enough to say whether being a man is an indicator of being smoker or not. For example if the probability of being a man in the society is also 90%, then knowing that someone is a man doesn't help us ((90% / 90%) = 1. But if men contribute to 40% of the society, but 90% of the smokers, then knowing that someone is a man increases the chance of being a smoker (90% / 40%) = 2.25, so it increases the initial guess (10%) by 2.25 resulting 22.5%.

However, if the probability of being a man was 95% in the society, then regardless of the fact that the percentage of men among smokers is high (90%)! the evidence that someone is a man decreases the chance of him being a smoker! (90% / 95%) = 0.95).

So we have:

P(smoker | f1, f2, f3,... ) = P(smoker) * contribution of f1* contribution of f2 *... 
=
P(smoker)* 
(P(being a man | smoker)/P(being a man))*
(P(under 20 | smoker)/ P(under 20))

Note that in this formula we assumed that being a man and being under 20 are independent features so we multiplied them, it means that knowing that someone is under 20 has no effect on guessing that he is man or woman. But it may not be true, for example maybe most adolescence in a society are men...

To use this formula in a classifier

The classifier is given with some features (being a man and being under 20) and it must decide if he is an smoker or not (these are two classes). It uses the above formula to calculate the probability of each class under the evidence (features), and it assigns the class with the highest probability to the input. To provide the required probabilities (90%, 10%, 80%...) it uses the training set. For example, it counts the people in the training set that are smokers and find they contribute 10% of the sample. Then for smokers checks how many of them are men or women .... how many are above 20 or under 20....In the other words, it tries to build the probability distribution of the features for each class based on the training data.

How to convert a Scikit-learn dataset to a Pandas dataset?

One of the best ways:

data = pd.DataFrame(digits.data)

Digits is the sklearn dataframe and I converted it to a pandas DataFrame

Select method in List<t> Collection

you can also try

var query = from p in list
            where p.Age > 18
            select p;

Filtering DataSet

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));

How I can filter a Datatable?

You can use DataView.

DataView dv = new DataView(yourDatatable);
dv.RowFilter = "query"; // query example = "id = 10"


http://www.csharp-examples.net/dataview-rowfilter/

How to test if a DataSet is empty?

Fill is command always return how many records inserted into dataset.

DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(sqlString, sqlConn);
var count = da.Fill(ds);
if(count > 0)
{
   Console.Write("It is not Empty");
}

DataAdapter.Fill(Dataset)

You need to do this:

OleDbConnection connection = new OleDbConnection(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();

string query = 
    @"SELECT tbl_Computer.*,  tbl_Besitzer.*
    FROM tbl_Computer 
    INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
    WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection); 
DBAdapter.Fill(DS);

By the way, what is this DataSet1? This should be "DataSet".

Sort columns of a dataframe by column name

  test[,sort(names(test))]

sort on names of columns can work easily.

Convert DataSet to List

var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
    Name = r.Field<string>("Name"),
    Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable

Adding rows to dataset

 DataSet ds = new DataSet();

 DataTable dt = new DataTable("MyTable");
 dt.Columns.Add(new DataColumn("id",typeof(int)));
 dt.Columns.Add(new DataColumn("name", typeof(string)));

 DataRow dr = dt.NewRow();
 dr["id"] = 123;
 dr["name"] = "John";
 dt.Rows.Add(dr);
 ds.Tables.Add(dt);

C#, Looping through dataset and show each record from a dataset column

I believe you intended it more this way:

foreach (DataTable table in ds.Tables)
{
    foreach (DataRow dr in table.Rows)
    {
        DateTime TaskStart = DateTime.Parse(dr["TaskStart"].ToString());
        TaskStart.ToString("dd-MMMM-yyyy");
        rpt.SetParameterValue("TaskStartDate", TaskStart);
    }
}

You always accessed your first row in your dataset.

adding a datatable in a dataset

Just give any name to the DataTable Like:

DataTable dt = new DataTable();
dt = SecondDataTable.Copy();    
dt .TableName = "New Name";
DataSet.Tables.Add(dt );

Stored procedure return into DataSet in C# .Net

I should tell you the basic steps and rest depends upon your own effort. You need to perform following steps.

  • Create a connection string.
  • Create a SQL connection
  • Create SQL command
  • Create SQL data adapter
  • fill your dataset.

Do not forget to open and close connection. follow this link for more under standing.

Convert floats to ints in Pandas?

Use the pandas.DataFrame.astype(<type>) function to manipulate column dtypes.

>>> df = pd.DataFrame(np.random.rand(3,4), columns=list("ABCD"))
>>> df
          A         B         C         D
0  0.542447  0.949988  0.669239  0.879887
1  0.068542  0.757775  0.891903  0.384542
2  0.021274  0.587504  0.180426  0.574300
>>> df[list("ABCD")] = df[list("ABCD")].astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

EDIT:

To handle missing values:

>>> df
          A         B     C         D
0  0.475103  0.355453  0.66  0.869336
1  0.260395  0.200287   NaN  0.617024
2  0.517692  0.735613  0.18  0.657106
>>> df[list("ABCD")] = df[list("ABCD")].fillna(0.0).astype(int)
>>> df
   A  B  C  D
0  0  0  0  0
1  0  0  0  0
2  0  0  0  0

Iterate through DataSet

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (object item in row.ItemArray)
        {
            // read item
        }
    }
}

Or, if you need the column info:

foreach (DataTable table in dataSet.Tables)
{
    foreach (DataRow row in table.Rows)
    {
        foreach (DataColumn column in table.Columns)
        {
            object item = row[column];
            // read column and item
        }
    }
}

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

object[,] valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);

//Get the column names
for (int k = 0; k < valueArray.GetLength(1); )
{
    //add columns to the data table.
    dt.Columns.Add((string)valueArray[1,++k]);
}

//Load data into data table
object[] singleDValue = new object[valueArray.GetLength(1)];
//value array first row contains column names. so loop starts from 1 instead of 0
for (int i = 1; i < valueArray.GetLength(0); i++)
{
    Console.WriteLine(valueArray.GetLength(0) + ":" + valueArray.GetLength(1));
    for (int k = 0; k < valueArray.GetLength(1); )
    {
        singleDValue[k] = valueArray[i+1, ++k];
    }
    dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
}

How to loop through a dataset in powershell?

Here's a practical example (build a dataset from your current location):

$ds = new-object System.Data.DataSet
$ds.Tables.Add("tblTest")
[void]$ds.Tables["tblTest"].Columns.Add("Name",[string])
[void]$ds.Tables["tblTest"].Columns.Add("Path",[string])

dir | foreach {
    $dr = $ds.Tables["tblTest"].NewRow()
    $dr["Name"] = $_.name
    $dr["Path"] = $_.fullname
    $ds.Tables["tblTest"].Rows.Add($dr)
}


$ds.Tables["tblTest"]

$ds.Tables["tblTest"] is an object that you can manipulate just like any other Powershell object:

$ds.Tables["tblTest"] | foreach {
    write-host 'Name value is : $_.name
    write-host 'Path value is : $_.path
}

How to check for a Null value in VB.NET

If Not editTransactionRow.pay_id AndAlso String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then
    stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value
End If

Looping through a DataTable

     foreach (DataRow row in dt.Rows) 
     {
        foreach (DataColumn col in dt.Columns)
           Console.WriteLine(row[col]);
     }

Convert generic list to dataset in C#

One option would be to use a System.ComponenetModel.BindingList rather than a list.

This allows you to use it directly within a DataGridView. And unlike a normal System.Collections.Generic.List updates the DataGridView on changes.

.NET - How do I retrieve specific items out of a Dataset?

int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());

How do I find out if a column exists in a VB.Net DataRow

You can use DataSet.Tables(0).Columns.Contains(name) to check whether the DataTable contains a column with a particular name.

MySQL "between" clause not inclusive?

select * from person where DATE(dob) between '2011-01-01' and '2011-01-31'

Surprisingly such conversions are solutions to many problems in MySQL.

In Python, how do you convert seconds since epoch to a `datetime` object?

Note that datetime.datetime.fromtimestamp(timestamp) and .utcfromtimestamp(timestamp) fail on windows for dates before Jan. 1, 1970 while negative unix timestamps seem to work on unix-based platforms. The docs say this:

"This may raise ValueError, if the timestamp is out of the range of values supported by the platform C gmtime() function. It’s common for this to be restricted to years in 1970 through 2038"

See also Issue1646728

How can I put a database under git (version control)?

What you want, in spirit, is perhaps something like Post Facto, which stores versions of a database in a database. Check this presentation.

The project apparently never really went anywhere, so it probably won't help you immediately, but it's an interesting concept. I fear that doing this properly would be very difficult, because even version 1 would have to get all the details right in order to have people trust their work to it.

How to include jQuery in ASP.Net project?

There are actually a few ways this can be done:

1: Download

You can download the latest version of jQuery and then include it in your page with a standard HTML script tag. This can be done within the master or an individual page.

HTML5

<script src="/scripts/jquery-2.1.0.min.js"></script>

HTML4

<script src="/scripts/jquery-2.1.0.min.js" type="text/javascript"></script>

2: Content Delivery Network

You can include jQuery to your site using a CDN (Content Delivery Network) such as Google's. This should help reduce page load times if the user has already visited a site using the same version from the same CDN.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

3: NuGet Package Manager

Lastly, (my preferred) use NuGet which is shipped with Visual Studio and Visual Studio Express. This is accessed from right-clicking on your project and clicking Manage NuGet Packages.

NuGet is an open source Library Package Manager that comes as a Visual Studio extension and that makes it very easy to add, remove, and update external libraries in your Visual Studio projects and websites. Beginning ASP.NET 4.5 in C# and VB.NET, WROX, 2013

enter image description here

Once installed, a new Folder group will appear in your Solution Explorer called Scripts. Simply drag and drop the file you wish to include onto your page of choice.

This method is ideal for larger projects because if you choose to remove the files, or change versions later (though the package manager) if will automatically remove/update any reference to that file within your project.

The only downside to this approach is it does not use a CDN to host the file so page load time may be slightly slower the first time the user visits your site.

iterating quickly through list of tuples

The question is dead but still knowing one more way doesn't hurt:

my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)]

for first,*args in my_list:
    if first == Value:
        PAIR_FOUND = True
        MATCHING_VALUE = args
        break

Check if a Python list item contains a string inside another string

I am new to Python. I got the code below working and made it easy to understand:

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for str in my_list:
    if 'abc' in str:
       print(str)

Recursion or Iteration?

It may be fun to write it as recursion, or as a practice.

However, if the code is to be used in production, you need to consider the possibility of stack overflow.

Tail recursion optimization can eliminate stack overflow, but do you want to go through the trouble of making it so, and you need to know you can count on it having the optimization in your environment.

Every time the algorithm recurses, how much is the data size or n reduced by?

If you are reducing the size of data or n by half every time you recurse, then in general you don't need to worry about stack overflow. Say, if it needs to be 4,000 level deep or 10,000 level deep for the program to stack overflow, then your data size need to be roughly 24000 for your program to stack overflow. To put that into perspective, a biggest storage device recently can hold 261 bytes, and if you have 261 of such devices, you are only dealing with 2122 data size. If you are looking at all the atoms in the universe, it is estimated that it may be less than 284. If you need to deal with all the data in the universe and their states for every millisecond since the birth of the universe estimated to be 14 billion years ago, it may only be 2153. So if your program can handle 24000 units of data or n, you can handle all data in the universe and the program will not stack overflow. If you don't need to deal with numbers that are as big as 24000 (a 4000-bit integer), then in general you don't need to worry about stack overflow.

However, if you reduce the size of data or n by a constant amount every time you recurse, then you can run into stack overflow when n becomes merely 20000. That is, the program runs well when n is 1000, and you think the program is good, and then the program stack overflows when some time in the future, when n is 5000 or 20000.

So if you have a possibility of stack overflow, try to make it an iterative solution.

LaTeX package for syntax highlighting of code in various languages

I would use the minted package as mentioned from the developer Konrad Rudolph instead of the listing package. Here is why:

listing package

The listing package does not support colors by default. To use colors you would need to include the color package and define color-rules by yourself with the \lstset command as explained for matlab code here.

Also, the listing package doesn't work well with unicode, but you can fix those problems as explained here and here.

The following code

\documentclass{article}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[language=html]
<html>
    <head>
        <title>Hello</title>
    </head>
    <body>Hello</body>
</html>
\end{lstlisting}
\end{document}

produces the following image:

enter image description here

minted package

The minted package supports colors, unicode and looks awesome. However, in order to use it, you need to have python 2.6 and pygments. In Ubuntu, you can check your python version in the terminal with

python --version

and you can install pygments with

sudo apt-get install python-pygments

Then, since minted makes calls to pygments, you need to compile it with -shell-escape like this

pdflatex -shell-escape yourfile.tex

If you use a latex editor like TexMaker or something, I would recommend to add a user-command, so that you can still compile it in the editor.

The following code

\documentclass{article}
\usepackage{minted}
\begin{document}

\begin{minted}{html}
    <!DOCTYPE html>
    <html>
       <head>
           <title>Hello</title>
       </head>

       <body>Hello</body>
    </html>
\end{minted}
\end{document}

produces the following image:

enter image description here

SQL WHERE ID IN (id1, id2, ..., idn)

Try this

SELECT Position_ID , Position_Name
FROM 
position
WHERE Position_ID IN (6 ,7 ,8)
ORDER BY Position_Name

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

CSS Animation onClick

You can do that by using following code

$('#button_id').on('click', function(){
$('#element_want_to_target').addClass('.animation_class');});

Capturing URL parameters in request.GET

To do this, simply type this in javascript:

function getParams(url) {
    var params = {};
    var parser = document.createElement('a');
    parser.href = url;
    var query = parser.search.substring(1);
    var vars = query.split('&');
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split('=');
        params[pair[0]] = decodeURIComponent(pair[1]);
    }
    return params;
};
var url = window.location.href;
getParams(url);

Confused about stdin, stdout and stderr?

I'm afraid your understanding is completely backwards. :)

Think of "standard in", "standard out", and "standard error" from the program's perspective, not from the kernel's perspective.

When a program needs to print output, it normally prints to "standard out". A program typically prints output to standard out with printf, which prints ONLY to standard out.

When a program needs to print error information (not necessarily exceptions, those are a programming-language construct, imposed at a much higher level), it normally prints to "standard error". It normally does so with fprintf, which accepts a file stream to use when printing. The file stream could be any file opened for writing: standard out, standard error, or any other file that has been opened with fopen or fdopen.

"standard in" is used when the file needs to read input, using fread or fgets, or getchar.

Any of these files can be easily redirected from the shell, like this:

cat /etc/passwd > /tmp/out     # redirect cat's standard out to /tmp/foo
cat /nonexistant 2> /tmp/err   # redirect cat's standard error to /tmp/error
cat < /etc/passwd              # redirect cat's standard input to /etc/passwd

Or, the whole enchilada:

cat < /etc/passwd > /tmp/out 2> /tmp/err

There are two important caveats: First, "standard in", "standard out", and "standard error" are just a convention. They are a very strong convention, but it's all just an agreement that it is very nice to be able to run programs like this: grep echo /etc/services | awk '{print $2;}' | sort and have the standard outputs of each program hooked into the standard input of the next program in the pipeline.

Second, I've given the standard ISO C functions for working with file streams (FILE * objects) -- at the kernel level, it is all file descriptors (int references to the file table) and much lower-level operations like read and write, which do not do the happy buffering of the ISO C functions. I figured to keep it simple and use the easier functions, but I thought all the same you should know the alternatives. :)

wampserver doesn't go green - stays orange

Also in device manager, first click "show all processes", put a stop to HTTP

After this fix I got an IIS page issue on localhost which got solved when we did the step below:
Check your hosts file in the C:\Windows\System32\Drivers\etc\ folder, if entry 127.0.0.1 localhost is commented then uncomment it by removing the # in front of that line.

A regex for version number parsing

^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$

Perhaps a more concise one could be :

^(?:(\d+)\.){0,2}(\*|\d+)$

This can then be enhanced to 1.2.3.4.5.* or restricted exactly to X.Y.Z using * or {2} instead of {0,2}

Should I declare Jackson's ObjectMapper as a static field?

Yes, that is safe and recommended.

The only caveat from the page you referred is that you can't be modifying configuration of the mapper once it is shared; but you are not changing configuration so that is fine. If you did need to change configuration, you would do that from the static block and it would be fine as well.

EDIT: (2013/10)

With 2.0 and above, above can be augmented by noting that there is an even better way: use ObjectWriter and ObjectReader objects, which can be constructed by ObjectMapper. They are fully immutable, thread-safe, meaning that it is not even theoretically possible to cause thread-safety issues (which can occur with ObjectMapper if code tries to re-configure instance).

How to list files in an android directory?

In order to access the files, the permissions must be given in the manifest file.

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Try this:

String path = Environment.getExternalStorageDirectory().toString()+"/Pictures";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
    Log.d("Files", "FileName:" + files[i].getName());
}

How to execute a stored procedure inside a select query

Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.

So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:

DECLARE @myId int;
DECLARE @myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
    SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId, @myName;
WHILE @@FETCH_STATUS = 0 BEGIN
    EXECUTE dbo.myCustomProcedure @myId, @myName;
    FETCH NEXT FROM myCursor INTO @myId, @myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;

Note that @@FETCH_STATUS is a standard variable which gets updated for you. The rest of the object names here are custom.

How to add an extra source directory for maven to compile and include in the build jar?

NOTE: This solution will just move the java source files to the target/classes directory and will not compile the sources.

Update the pom.xml as -

<project>   
 ....
    <build>
      <resources>
        <resource>
          <directory>src/main/config</directory>
        </resource>
      </resources>
     ...
    </build>
...
</project>

Truncate (not round off) decimal numbers in javascript

Number.prototype.truncate = function(places) {
  var shift = Math.pow(10, places);

  return Math.trunc(this * shift) / shift;
};

SQL Server : error converting data type varchar to numeric

I think the problem is not in sub-query but in WHERE clause of outer query. When you use

WHERE account_code between 503100 and 503105

SQL server will try to convert every value in your Account_code field to integer to test it in provided condition. Obviously it will fail to do so if there will be non-integer characters in some rows.

How to open every file in a folder

You can actually just use os module to do both:

  1. list all files in a folder
  2. sort files by file type, file name etc.

Here's a simple example:

import os #os module imported here
location = os.getcwd() # get present working directory location here
counter = 0 #keep a count of all files found
csvfiles = [] #list to store all csv files found at location
filebeginwithhello = [] # list to keep all files that begin with 'hello'
otherfiles = [] #list to keep any other file that do not match the criteria

for file in os.listdir(location):
    try:
        if file.endswith(".csv"):
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello") and file.endswith(".csv"): #because some files may start with hello and also be a csv file
            print "csv file found:\t", file
            csvfiles.append(str(file))
            counter = counter+1

        elif file.startswith("hello"):
            print "hello files found: \t", file
            filebeginwithhello.append(file)
            counter = counter+1

        else:
            otherfiles.append(file)
            counter = counter+1
    except Exception as e:
        raise e
        print "No files found here!"

print "Total files found:\t", counter

Now you have not only listed all the files in a folder but also have them (optionally) sorted by starting name, file type and others. Just now iterate over each list and do your stuff.

How to use private Github repo as npm dependency

With git there is a https format

https://github.com/equivalent/we_demand_serverless_ruby.git

This format accepts User + password

https://bot-user:[email protected]/equivalent/we_demand_serverless_ruby.git

So what you can do is create a new user that will be used just as a bot, add only enough permissions that he can just read the repository you want to load in NPM modules and just have that directly in your packages.json

 Github > Click on Profile > Settings > Developer settings > Personal access tokens > Generate new token

In Select Scopes part, check the on repo: Full control of private repositories

This is so that token can access private repos that user can see

Now create new group in your organization, add this user to the group and add only repositories that you expect to be pulled this way (READ ONLY permission !)

You need to be sure to push this config only to private repo

Then you can add this to your / packages.json (bot-user is name of user, xxxxxxxxx is the generated personal token)

// packages.json


{
  // ....
    "name_of_my_lib": "https://bot-user:[email protected]/ghuser/name_of_my_lib.git"
  // ...
}

https://blog.eq8.eu/til/pull-git-private-repo-from-github-from-npm-modules-or-bundler.html

Java math function to convert positive int to negative and negative to positive?

The easiest thing to do is 0- the value

for instance if int i = 5;

0-i would give you -5

and if i was -6;

0- i would give you 6

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Replace given value in vector

Another simpler option is to do:

 > x = c(1, 1, 2, 4, 5, 2, 1, 3, 2)
 > x[x==1] <- 0
 > x
 [1] 0 0 2 4 5 2 0 3 2

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

In the line of what Christian suggests, you could also do:

$('head').append("<style>.span::after{ content:'bar' }</style>");

How to get back Lost phpMyAdmin Password, XAMPP

There is a batch file called resetroot.bat located in the xammp folders 'C:\xampp\mysql' run this and it will delete the phpmyadmin passwords. Then all you need to do is start the MySQL service in xamp and click the admin button.

filename and line number of Python script

Here's what works for me to get the line number in Python 3.7.3 in VSCode 1.39.2 (dmsg is my mnemonic for debug message):

import inspect

def dmsg(text_s):
    print (str(inspect.currentframe().f_back.f_lineno) + '| ' + text_s)

To call showing a variable name_s and its value:

name_s = put_code_here
dmsg('name_s: ' + name_s)

Output looks like this:

37| name_s: value_of_variable_at_line_37

What is a good alternative to using an image map generator?

Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.

This btw is Search Engine Optimised as well :)

Source code follows:

_x000D_
_x000D_
.image-map {
  background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
  width: 272px;
  height: 92px;
  display: block;
  position: relative;
  margin-top:10px;
  float: left;
}

.image-map > a.map {
  position: absolute;
  display: block;
  border: 1px solid green;
}
_x000D_
<div class="image-map">
    <a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
    <a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
    <a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
    <a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
_x000D_
_x000D_

EDIT:

After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.

Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)

However I guess the target audience for this question does not agree with me.

You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.

Read response headers from API response - Angular 5 + TypeScript

In my case in the POST response I want to have the authorization header because I was having the JWT Token in it. So what I read from this post is the header I we want should be added as an Expose Header from the back-end. So what I did was added the Authorization header to my Exposed Header like this in my filter class.

response.addHeader("Access-Control-Expose-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Authorization, X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept, X-Custom-header");
response.addHeader(HEADER_STRING, TOKEN_PREFIX + token); // HEADER_STRING == Authorization

And at my Angular Side

In the Component.

this.authenticationService.login(this.f.email.value, this.f.password.value)
  .pipe(first())
  .subscribe(
    (data: HttpResponse<any>) => {
      console.log(data.headers.get('authorization'));
    },
    error => {
      this.loading = false;
    });

At my Service Side.

return this.http.post<any>(Constants.BASE_URL + 'login', {username: username, password: password},
  {observe: 'response' as 'body'})
  .pipe(map(user => {
       return user;
  }));

How to gzip all files in all sub-directories into one compressed file in bash

tar -zcvf compressFileName.tar.gz folderToCompress

everything in folderToCompress will go to compressFileName

Edit: After review and comments I realized that people may get confused with compressFileName without an extension. If you want you can use .tar.gz extension(as suggested) with the compressFileName

How to sort a data frame by alphabetic order of a character variable in R?

Well, I've got no problem here :

df <- data.frame(v=1:5, x=sample(LETTERS[1:5],5))
df

#   v x
# 1 1 D
# 2 2 A
# 3 3 B
# 4 4 C
# 5 5 E

df <- df[order(df$x),]
df

#   v x
# 2 2 A
# 3 3 B
# 4 4 C
# 1 1 D
# 5 5 E

How to create a date object from string in javascript

First extract the string like this

var dateString = str.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);

Then,

var d = new Date( dateString[3], dateString[2]-1, dateString[1] );

Unsupported operand type(s) for +: 'int' and 'str'

You're trying to concatenate a string and an integer, which is incorrect.

Change print(numlist.pop(2)+" has been removed") to any of these:

Explicit int to str conversion:

print(str(numlist.pop(2)) + " has been removed")

Use , instead of +:

print(numlist.pop(2), "has been removed")

String formatting:

print("{} has been removed".format(numlist.pop(2)))

How to use onSaveInstanceState() and onRestoreInstanceState()?

When your activity is recreated after it was previously destroyed, you can recover your saved state from the Bundle that the system passes your activity. Both the onCreate() and onRestoreInstanceState() callback methods receive the same Bundle that contains the instance state information.

Because the onCreate() method is called whether the system is creating a new instance of your activity or recreating a previous one, you must check whether the state Bundle is null before you attempt to read it. If it is null, then the system is creating a new instance of the activity, instead of restoring a previous one that was destroyed.

static final String STATE_USER = "user";
private String mUser;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mUser = savedInstanceState.getString(STATE_USER);
    } else {
        // Probably initialize members with default values for a new instance
        mUser = "NewUser";
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putString(STATE_USER, mUser);
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

http://developer.android.com/training/basics/activity-lifecycle/recreating.html

What is the best way to implement nested dictionaries?

I have a similar thing going. I have a lot of cases where I do:

thedict = {}
for item in ('foo', 'bar', 'baz'):
  mydict = thedict.get(item, {})
  mydict = get_value_for(item)
  thedict[item] = mydict

But going many levels deep. It's the ".get(item, {})" that's the key as it'll make another dictionary if there isn't one already. Meanwhile, I've been thinking of ways to deal with this better. Right now, there's a lot of

value = mydict.get('foo', {}).get('bar', {}).get('baz', 0)

So instead, I made:

def dictgetter(thedict, default, *args):
  totalargs = len(args)
  for i,arg in enumerate(args):
    if i+1 == totalargs:
      thedict = thedict.get(arg, default)
    else:
      thedict = thedict.get(arg, {})
  return thedict

Which has the same effect if you do:

value = dictgetter(mydict, 0, 'foo', 'bar', 'baz')

Better? I think so.

Combine two integer arrays

I think you have to allocate a new array and put the values into the new array. For example:

int[] array1and2 = new int[array1.length + array2.length];
int currentPosition = 0;

for( int i = 0; i < array1.length; i++) {
    array1and2[currentPosition] = array1[i];
    currentPosition++;
}

for( int j = 0; j < array2.length; j++) {
    array1and2[currentPosition] = array2[j];
    currentPosition++;
}

As far as I can tell just looking at it, this code should work.

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

python: after installing anaconda, how to import pandas

even after installing anaconda i got the same error and entering python3 showed this:

$ python3
Python 3.6.9 (default, Nov  7 2019, 10:44:02) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

enter this command: source ~/.bashrc (it is kind of restarting the terminal) after running the command enter python3 again:

$ python3
Python 3.7.4 (default, Aug 13 2019, 20:35:49) 
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

this means anaconda is added. now import pandas will work.

Spring MVC Multipart Request with JSON

This must work!

client (angular):

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      var json = $scope.myJson;
      formData.append("file", file);
      formData.append("ad",JSON.stringify(json));//important: convert to JSON!
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

Backend-Spring Boot:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {

        Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd

Where is my m2 folder on Mac OS X Mavericks

On mac just run mvn clean install assuming maven has been installed and it will create .m2 automatically.

two divs the same line, one dynamic width, one fixed

HTML:

<div id="parent">
  <div class="right"></div>
  <div class="left"></div>
</div>

(div.right needs to be before div.left in the HTML markup)

CSS:

.right {
float:right;
width:200px;
}

How can I remove duplicate rows?

The other way is Create a new table with same fields and with Unique Index. Then move all data from old table to new table. Automatically SQL SERVER ignore (there is also an option about what to do if there will be a duplicate value: ignore, interrupt or sth) duplicate values. So we have the same table without duplicate rows. If you don't want Unique Index, after the transfer data you can drop it.

Especially for larger tables you may use DTS (SSIS package to import/export data) in order to transfer all data rapidly to your new uniquely indexed table. For 7 million row it takes just a few minute.

How to parse a JSON and turn its values into an Array?

for your example:

{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}

you will have to do something of this effect:

JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");

this returns the array object.

Then iterating will be as follows:

    int size = the_json_array.length();
    ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
    for (int i = 0; i < size; i++) {
        JSONObject another_json_object = the_json_array.getJSONObject(i);
            //Blah blah blah...
            arrays.add(another_json_object);
    }

//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);

//The end...

You will have to determine if the data is an array (simply checking that charAt(0) starts with [ character).

Hope this helps.

Calculating Distance between two Latitude and Longitude GeoCoordinates

The GeoCoordinate class (.NET Framework 4 and higher) already has GetDistanceTo method.

var sCoord = new GeoCoordinate(sLatitude, sLongitude);
var eCoord = new GeoCoordinate(eLatitude, eLongitude);

return sCoord.GetDistanceTo(eCoord);

The distance is in meters.

You need to reference System.Device.

Get response from PHP file using AJAX

var data="your data";//ex data="id="+id;
      $.ajax({
       method : "POST",
       url : "file name",  //url: "demo.php"
       data : "data",
       success : function(result){
               //set result to div or target 
              //ex $("#divid).html(result)
        }
   });

How to use cURL to send Cookies?

This worked for me:

curl -v --cookie "USER_TOKEN=Yes" http://127.0.0.1:5000/

I could see the value in backend using

print request.cookies

Unable to run Java GUI programs with Ubuntu

I would check with another Java implementation/vendor. Preferrably Oracle/Sun Java: http://www.java.com/en/ . The open-source implementations unfortunately differ in weird ways.

Responsive font size in CSS

As with many frameworks, once you "go off the grid" and override the framework's default CSS, things will start to break left and right. Frameworks are inherently rigid. If you were to use Zurb's default H1 style along with their default grid classes, then the web page should display properly on mobile (i.e., responsive).

However, it appears you want very large 6.2em headings, which means the text will have to shrink in order to fit inside a mobile display in portrait mode. Your best bet is to use a responsive text jQuery plugin such as FlowType and FitText. If you want something light-weight, then you can check out my Scalable Text jQuery plugin:

http://thdoan.github.io/scalable-text/

Sample usage:

<script>
$(document).ready(function() {
  $('.row .twelve h1').scaleText();
}
</script>

Full path from file input using jQuery

You can't: It's a security feature in all modern browsers.

For IE8, it's off by default, but can be reactivated using a security setting:

When a file is selected by using the input type=file object, the value of the value property depends on the value of the "Include local directory path when uploading files to a server" security setting for the security zone used to display the Web page containing the input object.

The fully qualified filename of the selected file is returned only when this setting is enabled. When the setting is disabled, Internet Explorer 8 replaces the local drive and directory path with the string C:\fakepath\ in order to prevent inappropriate information disclosure.

In all other current mainstream browsers I know of, it is also turned off. The file name is the best you can get.

More detailed info and good links in this question. It refers to getting the value server-side, but the issue is the same in JavaScript before the form's submission.

outline on only one border

I know this is old. But yeah. I prefer much shorter solution, than Giona answer

[contenteditable] {
    border-bottom: 1px solid transparent;
    &:focus {outline: none; border-bottom: 1px dashed #000;}
}

Entry point for Java applications: main(), init(), or run()?

The main method is the entry point of a Java application.

Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java application launcher), it will look for the main method with the signature of public static void main(String[]).

From Sun's java command page:

The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.

The method must be declared public and static, it must not return any value, and it must accept a String array as a parameter. The method declaration must look like the following:

public static void main(String args[])

For additional resources on how an Java application is executed, please refer to the following sources:

  1. Chapter 12: Execution from the Java Language Specification, Third Edition.
  2. Chapter 5: Linking, Loading, Initializing from the Java Virtual Machine Specifications, Second Edition.
  3. A Closer Look at the "Hello World" Application from the Java Tutorials.

The run method is the entry point for a new Thread or an class implementing the Runnable interface. It is not called by the Java Virutal Machine when it is started up by the java command.

As a Thread or Runnable itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start() method. This can be accomplished by instantiating a Thread and calling its start method in the main method of the application:

public class MyRunnable implements Runnable
{
    public void run()
    {
        System.out.println("Hello World!");
    }

    public static void main(String[] args)
    {
        new Thread(new MyRunnable()).start();
    }
}

For more information and an example of how to start a subclass of Thread or a class implementing Runnable, see Defining and Starting a Thread from the Java Tutorials.


The init method is the first method called in an Applet or JApplet.

When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init method. Any initializations that are required to use the applet should be executed here. After the init method is complete, the start method is called.

For more information about when the init method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.

See also: How to Make Applets from the Java Tutorial.

How do I select the "last child" with a specific class name in CSS?

This can be done using an attribute selector.

[class~='list']:last-of-type  {
    background: #000;
}

The class~ selects a specific whole word. This allows your list item to have multiple classes if need be, in various order. It'll still find the exact class "list" and apply the style to the last one.

See a working example here: http://codepen.io/chasebank/pen/ZYyeab

Read more on attribute selectors:

http://css-tricks.com/attribute-selectors/ http://www.w3schools.com/css/css_attribute_selectors.asp

How can I bring my application window to the front?

While I agree with everyone, this is no-nice behavior, here is code:

[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);   


SetForegroundWindow(Handle.ToInt32());

Update

David is completely right, for completeness I include the list of conditions that must apply for this to work (+1 for David!):

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.

What's the difference between process.cwd() vs __dirname?

$ find proj

proj
proj/src
proj/src/index.js

$ cat proj/src/index.js

console.log("process.cwd() = " + process.cwd());
console.log("__dirname = " + __dirname);

$ cd proj; node src/index.js

process.cwd() = /tmp/proj
__dirname = /tmp/proj/src

Import mysql DB with XAMPP in command LINE

The process is simple-

  1. Move the database to the desired folder e.g. /xampp/mysql folder.

  2. Open cmd and navigate to the above location

  3. Use command to import the db - "mysql -u root -p dbpassword newDbName < dbtoimport.sql"

  4. Check for the tables for verification.

Getting realtime output using subprocess

In Python 3.x the process might hang because the output is a byte array instead of a string. Make sure you decode it into a string.

Starting from Python 3.6 you can do it using the parameter encoding in Popen Constructor. The complete example:

process = subprocess.Popen(
    'my_command',
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    shell=True,
    encoding='utf-8',
    errors='replace'
)

while True:
    realtime_output = process.stdout.readline()

    if realtime_output == '' and process.poll() is not None:
        break

    if realtime_output:
        print(realtime_output.strip(), flush=True)

Note that this code redirects stderr to stdout and handles output errors.

Facebook Access Token for Pages

The documentation for this is good if not a little difficult to find.

Facebook Graph API - Page Tokens

After initializing node's fbgraph, you can run:

var facebookAccountID = yourAccountIdHere 

graph
.setOptions(options)
.get(facebookAccountId + "/accounts", function(err, res) {
  console.log(res); 
});

and receive a JSON response with the token you want to grab, located at:

res.data[0].access_token

What is the maximum possible length of a .NET string?

Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).

UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters.

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        int i = 100000000;
        try
        {
            for (i = i; i <= int.MaxValue; i += 5000)
            {
                string value = new string('x', i);
                //WL(i);
            }
        }
        catch (Exception exc)
        {
            WL(i);
            WL(exc);
        }
        WL(i);
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

Select statement to find duplicates on certain fields

try this query to have sepratley count of each SELECT statements :

select field1,count(field1) as field1Count,field2,count(field2) as field2Counts,field3, count(field3) as field3Counts
from table_name
group by field1,field2,field3
having count(*) > 1

How can I deploy an iPhone application from Xcode to a real iPhone device?

You can't, not if you are talking about applications built with the official SDK and deploying straight from xcode.

Update React component every second

class ShowDateTime extends React.Component {
   constructor() {
      super();
      this.state = {
        curTime : null
      }
    }
    componentDidMount() {
      setInterval( () => {
        this.setState({
          curTime : new Date().toLocaleString()
        })
      },1000)
    }
   render() {
        return(
          <div>
            <h2>{this.state.curTime}</h2>
          </div>
        );
      }
    }

How to use HTML to print header and footer on every printed page of a document?

I tried to fight this futile battle combining tfoot & css rules but it only worked on Firefox :(. When using plain css, the content flows over the footer. When using tfoot, the footer on the last page does not stay nicely on the bottom. This is because table footers are meant for tables, not physical pages. Tested on Chrome 16, Opera 11, Firefox 3 & 6 and IE6.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Header & Footer test</title>

<style>

  @media screen {
    div#footer_wrapper {
      display: none;
    }
  }

  @media print {
    tfoot { visibility: hidden; }

    div#footer_wrapper {
      margin: 0px 2px 0px 7px;
      position: fixed;
      bottom: 0;
    }

    div#footer_content {
      font-weight: bold;
    }
  }

</style>
</head>

<body>

<div id="footer_wrapper">
  <div id="footer_content">
    Total 4923
  </div>
</div>


<TABLE CELLPADDING=6>

<THEAD>
<TR> <TH>Weekday</TH> <TH>Date</TH> <TH>Manager</TH> <TH>Qty</TH> </TR>
</THEAD>

<TBODY>
<TR> <TD>Mon</TD> <TD>09/11</TD> <TD>Kelsey</TD>  <TD>639</TD>  </TR>
<TR> <TD>Tue</TD> <TD>09/12</TD> <TD>Lindsey</TD> <TD>596</TD>  </TR>
<TR> <TD>Wed</TD> <TD>09/13</TD> <TD>Randy</TD>   <TD>1135</TD> </TR>
<TR> <TD>Thu</TD> <TD>09/14</TD> <TD>Susan</TD>   <TD>1002</TD> </TR>
<TR> <TD>Fri</TD> <TD>09/15</TD> <TD>Randy</TD>   <TD>908</TD>  </TR>
<TR> <TD>Sat</TD> <TD>09/16</TD> <TD>Lindsey</TD> <TD>371</TD>  </TR>
<TR> <TD>Sun</TD> <TD>09/17</TD> <TD>Susan</TD>   <TD>272</TD>  </TR>
<TR> <TD>Mon</TD> <TD>09/11</TD> <TD>Kelsey</TD>  <TD>639</TD>  </TR>
<TR> <TD>Tue</TD> <TD>09/12</TD> <TD>Lindsey</TD> <TD>596</TD>  </TR>
<TR> <TD>Wed</TD> <TD>09/13</TD> <TD>Randy</TD>   <TD>1135</TD> </TR>
<TR> <TD>Thu</TD> <TD>09/14</TD> <TD>Susan</TD>   <TD>1002</TD> </TR>
<TR> <TD>Fri</TD> <TD>09/15</TD> <TD>Randy</TD>   <TD>908</TD>  </TR>
<TR> <TD>Sat</TD> <TD>09/16</TD> <TD>Lindsey</TD> <TD>371</TD>  </TR>
<TR> <TD>Sun</TD> <TD>09/17</TD> <TD>Susan</TD>   <TD>272</TD>  </TR>
<TR> <TD>Mon</TD> <TD>09/11</TD> <TD>Kelsey</TD>  <TD>639</TD>  </TR>
<TR> <TD>Tue</TD> <TD>09/12</TD> <TD>Lindsey</TD> <TD>596</TD>  </TR>
<TR> <TD>Wed</TD> <TD>09/13</TD> <TD>Randy</TD>   <TD>1135</TD> </TR>
<TR> <TD>Thu</TD> <TD>09/14</TD> <TD>Susan</TD>   <TD>1002</TD> </TR>
<TR> <TD>Fri</TD> <TD>09/15</TD> <TD>Randy</TD>   <TD>908</TD>  </TR>
<TR> <TD>Sat</TD> <TD>09/16</TD> <TD>Lindsey</TD> <TD>371</TD>  </TR>
<TR> <TD>Sun</TD> <TD>09/17</TD> <TD>Susan</TD>   <TD>272</TD>  </TR>
<TR> <TD>Mon</TD> <TD>09/11</TD> <TD>Kelsey</TD>  <TD>639</TD>  </TR>
<TR> <TD>Tue</TD> <TD>09/12</TD> <TD>Lindsey</TD> <TD>596</TD>  </TR>
<TR> <TD>Wed</TD> <TD>09/13</TD> <TD>Randy</TD>   <TD>1135</TD> </TR>
<TR> <TD>Thu</TD> <TD>09/14</TD> <TD>Susan</TD>   <TD>1002</TD> </TR>
<TR> <TD>Fri</TD> <TD>09/15</TD> <TD>Randy</TD>   <TD>908</TD>  </TR>
<TR> <TD>Sat</TD> <TD>09/16</TD> <TD>Lindsey</TD> <TD>371</TD>  </TR>
<TR> <TD>Sun</TD> <TD>09/17</TD> <TD>Susan</TD>   <TD>272</TD>  </TR>
<TR> <TD>Mon</TD> <TD>09/11</TD> <TD>Kelsey</TD>  <TD>639</TD>  </TR>
<TR> <TD>Tue</TD> <TD>09/12</TD> <TD>Lindsey</TD> <TD>596</TD>  </TR>
<TR> <TD>Wed</TD> <TD>09/13</TD> <TD>Randy</TD>   <TD>1135</TD> </TR>
<TR> <TD>Thu</TD> <TD>09/14</TD> <TD>Susan</TD>   <TD>1002</TD> </TR>
<TR> <TD>Fri</TD> <TD>09/15</TD> <TD>Randy</TD>   <TD>908</TD>  </TR>
<TR> <TD>Sat</TD> <TD>09/16</TD> <TD>Lindsey</TD> <TD>371</TD>  </TR>
<TR> <TD>Sun</TD> <TD>09/17</TD> <TD>Susan</TD>   <TD>272</TD>  </TR>
<TR> <TD>Mon</TD> <TD>09/11</TD> <TD>Kelsey</TD>  <TD>639</TD>  </TR>
<TR> <TD>Tue</TD> <TD>09/12</TD> <TD>Lindsey</TD> <TD>596</TD>  </TR>
<TR> <TD>Wed</TD> <TD>09/13</TD> <TD>Randy</TD>   <TD>1135</TD> </TR>
<TR> <TD>Thu</TD> <TD>09/14</TD> <TD>Susan</TD>   <TD>1002</TD> </TR>
<TR> <TD>Fri</TD> <TD>09/15</TD> <TD>Randy</TD>   <TD>908</TD>  </TR>
<TR> <TD>Sat</TD> <TD>09/16</TD> <TD>Lindsey</TD> <TD>371</TD>  </TR>
<TR> <TD>Sun</TD> <TD>09/17</TD> <TD>Susan</TD>   <TD>272</TD>  </TR>
<TR> <TD>Mon</TD> <TD>09/11</TD> <TD>Kelsey</TD>  <TD>639</TD>  </TR>
<TR> <TD>Tue</TD> <TD>09/12</TD> <TD>Lindsey</TD> <TD>596</TD>  </TR>
<TR> <TD>Wed</TD> <TD>09/13</TD> <TD>Randy</TD>   <TD>1135</TD> </TR>
<TR> <TD>Thu</TD> <TD>09/14</TD> <TD>Susan</TD>   <TD>1002</TD> </TR>
<TR> <TD>Fri</TD> <TD>09/15</TD> <TD>Randy</TD>   <TD>908</TD>  </TR>
<TR> <TD>Sat</TD> <TD>09/16</TD> <TD>Lindsey</TD> <TD>371</TD>  </TR>
<TR> <TD>Sun</TD> <TD>09/17</TD> <TD>Susan</TD>   <TD>272</TD>  </TR>
</TBODY>

<TFOOT id="table_footer">
<TR> <TH ALIGN=LEFT COLSPAN=3>Total</TH> <TH>4923</TH> </TR>
</TFOOT>

</TABLE>

</body>
</html>

How to deploy a Java Web Application (.war) on tomcat?

The tomcat manual says:

Copy the web application archive file into directory $CATALINA_HOME/webapps/. When Tomcat is started, it will automatically expand the web application archive file into its unpacked form, and execute the application that way.

How to break/exit from a each() function in JQuery?

Return false from the anonymous function:

$(xml).find("strengths").each(function() {
  // Code
  // To escape from this block based on a condition:
  if (something) return false;
});

From the documentation of the each method:

Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).

Fastest way to check if string contains only digits

Try this code:

bool isDigitsOnly(string str)
{
   try
   {
      int number = Convert.ToInt32(str);
      return true;
   }
   catch (Exception)
   {
      return false;
   }
}

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case, the file C:\Users\xxx\AppData\Local\PreEmptive Solutions\Dotfuscator Professional Edition\4.0\dfusrprf.xml was full of NULL.

I deleted it; it was recreated on the first launch of Dotfuscator, and after that, normality was restored.

Does Go have "if x in" construct similar to Python?

Just had similar question and decided to try out some of the suggestions in this thread.

I've benchmarked best and worst case scenarios of 3 types of lookup:

  • using a map
  • using a list
  • using a switch statement

here's the function code:

func belongsToMap(lookup string) bool {
list := map[string]bool{
    "900898296857": true,
    "900898302052": true,
    "900898296492": true,
    "900898296850": true,
    "900898296703": true,
    "900898296633": true,
    "900898296613": true,
    "900898296615": true,
    "900898296620": true,
    "900898296636": true,
}
if _, ok := list[lookup]; ok {
    return true
} else {
    return false
}
}


func belongsToList(lookup string) bool {
list := []string{
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636",
}
for _, val := range list {
    if val == lookup {
        return true
    }
}
return false
}

func belongsToSwitch(lookup string) bool {
switch lookup {
case
    "900898296857",
    "900898302052",
    "900898296492",
    "900898296850",
    "900898296703",
    "900898296633",
    "900898296613",
    "900898296615",
    "900898296620",
    "900898296636":
    return true
}
return false
}

best case scenarios pick the first item in lists, worst case ones use nonexistant value.

here are the results:

BenchmarkBelongsToMapWorstCase-4 2000000 787 ns/op BenchmarkBelongsToSwitchWorstCase-4 2000000000 0.35 ns/op BenchmarkBelongsToListWorstCase-4 100000000 14.7 ns/op BenchmarkBelongsToMapBestCase-4 2000000 683 ns/op BenchmarkBelongsToSwitchBestCase-4 100000000 10.6 ns/op BenchmarkBelongsToListBestCase-4 100000000 10.4 ns/op

Switch wins all the way, worst case is surpassingly quicker than best case. Maps are the worst and list is closer to switch.

So the moral is: If you have a static, reasonably small list, switch statement is the way to go.

Error: JAVA_HOME is not defined correctly executing maven

Use these two commands (for Java 8):

sudo update-java-alternatives --set java-8-oracle
java -XshowSettings 2>&1 | grep -e 'java.home' | awk '{print "JAVA_HOME="$3}' | sed "s/\/jre//g" >> /etc/environment

How do I test if a variable does not equal either of two values?

This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).

switch(test) {
    case A:
    case B:
        do other stuff;
        break;
    default:
        do stuff;
}

Colorized grep -- viewing the entire file with highlighted matches

Use colout program: http://nojhan.github.io/colout/

It is designed to add color highlights to a text stream. Given a regex and a color (e.g. "red"), it reproduces a text stream with matches highlighted. e.g:

# cat logfile but highlight instances of 'ERROR' in red
colout ERROR red <logfile

You can chain multiple invocations to add multiple different color highlights:

tail -f /var/log/nginx/access.log | \
    colout ' 5\d\d ' red | \
    colout ' 4\d\d ' yellow | \
    colout ' 3\d\d ' cyan | \
    colout ' 2\d\d ' green

Or you can achieve the same thing by using a regex with N groups (parenthesised parts of the regex), followed by a comma separated list of N colors.

vagrant status | \
    colout \
        '\''(^.+  running)|(^.+suspended)|(^.+not running)'\'' \
        green,yellow,red

Getting RSA private key from PEM BASE64 Encoded private key file

You will find below some code for reading unencrypted RSA keys encoded in the following formats:

  • PKCS#1 PEM (-----BEGIN RSA PRIVATE KEY-----)
  • PKCS#8 PEM (-----BEGIN PRIVATE KEY-----)
  • PKCS#8 DER (binary)

It works with Java 7+ (and after 9) and doesn't use third-party libraries (like BouncyCastle) or internal Java APIs (like DerInputStream or DerValue).

private static final String PKCS_1_PEM_HEADER = "-----BEGIN RSA PRIVATE KEY-----";
private static final String PKCS_1_PEM_FOOTER = "-----END RSA PRIVATE KEY-----";
private static final String PKCS_8_PEM_HEADER = "-----BEGIN PRIVATE KEY-----";
private static final String PKCS_8_PEM_FOOTER = "-----END PRIVATE KEY-----";

public static PrivateKey loadKey(String keyFilePath) throws GeneralSecurityException, IOException {
    byte[] keyDataBytes = Files.readAllBytes(Paths.get(keyFilePath));
    String keyDataString = new String(keyDataBytes, StandardCharsets.UTF_8);

    if (keyDataString.contains(PKCS_1_PEM_HEADER)) {
        // OpenSSL / PKCS#1 Base64 PEM encoded file
        keyDataString = keyDataString.replace(PKCS_1_PEM_HEADER, "");
        keyDataString = keyDataString.replace(PKCS_1_PEM_FOOTER, "");
        return readPkcs1PrivateKey(Base64.decodeBase64(keyDataString));
    }

    if (keyDataString.contains(PKCS_8_PEM_HEADER)) {
        // PKCS#8 Base64 PEM encoded file
        keyDataString = keyDataString.replace(PKCS_8_PEM_HEADER, "");
        keyDataString = keyDataString.replace(PKCS_8_PEM_FOOTER, "");
        return readPkcs8PrivateKey(Base64.decodeBase64(keyDataString));
    }

    // We assume it's a PKCS#8 DER encoded binary file
    return readPkcs8PrivateKey(Files.readAllBytes(Paths.get(keyFilePath)));
}

private static PrivateKey readPkcs8PrivateKey(byte[] pkcs8Bytes) throws GeneralSecurityException {
    KeyFactory keyFactory = KeyFactory.getInstance("RSA", "SunRsaSign");
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8Bytes);
    try {
        return keyFactory.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new IllegalArgumentException("Unexpected key format!", e);
    }
}

private static PrivateKey readPkcs1PrivateKey(byte[] pkcs1Bytes) throws GeneralSecurityException {
    // We can't use Java internal APIs to parse ASN.1 structures, so we build a PKCS#8 key Java can understand
    int pkcs1Length = pkcs1Bytes.length;
    int totalLength = pkcs1Length + 22;
    byte[] pkcs8Header = new byte[] {
            0x30, (byte) 0x82, (byte) ((totalLength >> 8) & 0xff), (byte) (totalLength & 0xff), // Sequence + total length
            0x2, 0x1, 0x0, // Integer (0)
            0x30, 0xD, 0x6, 0x9, 0x2A, (byte) 0x86, 0x48, (byte) 0x86, (byte) 0xF7, 0xD, 0x1, 0x1, 0x1, 0x5, 0x0, // Sequence: 1.2.840.113549.1.1.1, NULL
            0x4, (byte) 0x82, (byte) ((pkcs1Length >> 8) & 0xff), (byte) (pkcs1Length & 0xff) // Octet string + length
    };
    byte[] pkcs8bytes = join(pkcs8Header, pkcs1Bytes);
    return readPkcs8PrivateKey(pkcs8bytes);
}

private static byte[] join(byte[] byteArray1, byte[] byteArray2){
    byte[] bytes = new byte[byteArray1.length + byteArray2.length];
    System.arraycopy(byteArray1, 0, bytes, 0, byteArray1.length);
    System.arraycopy(byteArray2, 0, bytes, byteArray1.length, byteArray2.length);
    return bytes;
}

Source: https://github.com/Mastercard/client-encryption-java/blob/master/src/main/java/com/mastercard/developer/utils/EncryptionUtils.java

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

How to parse a query string into a NameValueCollection in .NET

To get all Querystring values try this:

    Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)

Dim sb As New StringBuilder("<br />")
For Each s As String In qscoll.AllKeys

  Response.Write(s & " - " & qscoll(s) & "<br />")

Next s

In R, how to find the standard error of the mean?

The standard error (SE) is just the standard deviation of the sampling distribution. The variance of the sampling distribution is the variance of the data divided by N and the SE is the square root of that. Going from that understanding one can see that it is more efficient to use variance in the SE calculation. The sd function in R already does one square root (code for sd is in R and revealed by just typing "sd"). Therefore, the following is most efficient.

se <- function(x) sqrt(var(x)/length(x))

in order to make the function only a bit more complex and handle all of the options that you could pass to var, you could make this modification.

se <- function(x, ...) sqrt(var(x, ...)/length(x))

Using this syntax one can take advantage of things like how var deals with missing values. Anything that can be passed to var as a named argument can be used in this se call.

C# : Out of Memory exception

I know this is an old question but since none of the answers mentioned the large object heap, this might be of use to others who find this question ...

Any memory allocation in .NET that is over 85,000 bytes comes from the large object heap (LOH) not the normal small object heap. Why does this matter? Because the large object heap is not compacted. Which means that the large object heap gets fragmented and in my experience this inevitably leads to out of memory errors.

In the original question the list has 50,000 items in it. Internally a list uses an array, and assuming 32 bit that requires 50,000 x 4bytes = 200,000 bytes (or double that if 64 bit). So that memory allocation is coming from the large object heap.

So what can you do about it?

If you are using a .net version prior to 4.5.1 then about all you can do about it is to be aware of the problem and try to avoid it. So, in this instance, instead of having a list of vehicles you could have a list of lists of vehicles, provided no list ever had more than about 18,000 elements in it. That can lead to some ugly code, but it is viable work around.

If you are using .net 4.5.1 or later then the behaviour of the garbage collector has changed subtly. If you add the following line where you are about to make large memory allocations:

System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;

it will force the garbage collector to compact the large object heap - next time only.

It might not be the best solution but the following has worked for me:

int tries = 0;
while (tries++ < 2)
{
  try 
  {
    . . some large allocation . .
    return;
  }
  catch (System.OutOfMemoryException)
  {
    System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
    GC.Collect();
  }
}

of course this only helps if you have the physical (or virtual) memory available.

How to get a dependency tree for an artifact?

If you bother creating a sample project and adding your 3rd party dependency to that, then you can run the following in order to see the full hierarchy of the dependencies.

You can search for a specific artifact using this maven command:

mvn dependency:tree -Dverbose -Dincludes=[groupId]:[artifactId]:[type]:[version]

According to the documentation:

where each pattern segment is optional and supports full and partial * wildcards. An empty pattern segment is treated as an implicit wildcard.

Imagine you are trying to find 'log4j-1.2-api' jar file among different modules of your project:

mvn dependency:tree -Dverbose -Dincludes=org.apache.logging.log4j:log4j-1.2-api

more information can be found here.

Edit: Please note that despite the advantages of using verbose parameter, it might not be so accurate in some conditions. Because it uses Maven 2 algorithm and may give wrong results when used with Maven 3.

JPanel Padding in Java

JPanel p=new JPanel();  
GridBagLayout layout=new GridBagLayout(); 
p.setLayout(layout); 
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill=GridBagConstraints.HORIZONTAL; 
gbc.gridx=0;   
gbc.gridy=0;   
p2.add("",gbc);

git-diff to ignore ^M

Is there an option like "treat ^M as newline when diffing" ?

There will be one with Git 2.16 (Q1 2018), as the "diff" family of commands learned to ignore differences in carriage return at the end of line.

See commit e9282f0 (26 Oct 2017) by Junio C Hamano (gitster).
Helped-by: Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 10f65c2, 27 Nov 2017)

diff: --ignore-cr-at-eol

A new option --ignore-cr-at-eol tells the diff machinery to treat a carriage-return at the end of a (complete) line as if it does not exist.

Just like other "--ignore-*" options to ignore various kinds of whitespace differences, this will help reviewing the real changes you made without getting distracted by spurious CRLF<->LF conversion made by your editor program.

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

How to find the last field using 'cut'

Without awk ?... But it's so simple with awk:

echo 'maps.google.com' | awk -F. '{print $NF}'

AWK is a way more powerful tool to have in your pocket. -F if for field separator NF is the number of fields (also stands for the index of the last)

Cannot find module cv2 when using OpenCV

I solved my issue using the following command :

pip install opencv-python

How can I get the source directory of a Bash script from within the script itself?

There is no 100% portable and reliable way to request a path to a current script directory. Especially between different backends like Cygwin, MinGW, MSYS, Linux, etc. This issue was not properly and completely resolved in Bash for ages.

For example, this could not be resolved if you want to request the path after the source command to make nested inclusion of another Bash script which is in turn use the same source command to include another Bash script and so on.

In case of the source command, I suggest to replace the source command with something like this:

function include()
{
  if [[ -n "$CURRENT_SCRIPT_DIR" ]]; then
    local dir_path=... get directory from `CURRENT_SCRIPT_DIR/$1`, depends if $1 is absolute path or relative ...
    local include_file_path=...
  else
    local dir_path=... request the directory from the "$1" argument using one of answered here methods...
    local include_file_path=...
  fi
  ... push $CURRENT_SCRIPT_DIR in to stack ...
  export CURRENT_SCRIPT_DIR=... export current script directory using $dir_path ...
  source "$include_file_path"
  ... pop $CURRENT_SCRIPT_DIR from stack ...
}

From now on, the use of include(...) is based on previous CURRENT_SCRIPT_DIR in your script.

This only works when you can replace all source commands by include command. If you can't, then you have no choice. At least until developers of the Bash interpreter make an explicit command to request the current running script directory path.

My own closest implementation to this: https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/bash/tacklelib/bash_entry

(search for the tkl_include function)

JPA EntityManager: Why use persist() over merge()?

There are some more differences between merge and persist (I will enumerate again those already posted here):

D1. merge does not make the passed entity managed, but rather returns another instance that is managed. persist on the other side will make the passed entity managed:

//MERGE: passedEntity remains unmanaged, but newEntity will be managed
Entity newEntity = em.merge(passedEntity);

//PERSIST: passedEntity will be managed after this
em.persist(passedEntity);

D2. If you remove an entity and then decide to persist the entity back, you may do that only with persist(), because merge will throw an IllegalArgumentException.

D3. If you decided to take care manually of your IDs (e.g by using UUIDs), then a merge operation will trigger subsequent SELECT queries in order to look for existent entities with that ID, while persist may not need those queries.

D4. There are cases when you simply do not trust the code that calls your code, and in order to make sure that no data is updated, but rather is inserted, you must use persist.

Object array initialization without default constructor

One way to solve is to give a static factory method to allocate the array if for some reason you want to give constructor private.

static Car*  Car::CreateCarArray(int dimensions)

But why are you keeping one constructor public and other private?

But anyhow one more way is to declare the public constructor with default value

#define DEFAULT_CAR_INIT 0
Car::Car(int _no=DEFAULT_CAR_INIT);

Two Divs next to each other, that then stack with responsive change

You can use CSS3 media query for this. Write like this:

CSS

.wrapper { 
  border : 2px solid #000; 
  overflow:hidden;
}

.wrapper div {
   min-height: 200px;
   padding: 10px;
}
#one {
  background-color: gray;
  float:left; 
  margin-right:20px;
  width:140px;
  border-right:2px solid #000;
}
#two { 
  background-color: white;
  overflow:hidden;
  margin:10px;
  border:2px dashed #ccc;
  min-height:170px;
}

@media screen and (max-width: 400px) {
   #one { 
    float: none;
    margin-right:0;
    width:auto;
    border:0;
    border-bottom:2px solid #000;    
  }
}

HTML

<div class="wrapper">
    <div id="one">one</div>
    <div id="two">two</div>
</div>

Check this for more http://jsfiddle.net/cUCvY/1/

JavaScript post request like a form submit

If you have Prototype installed, you can tighten up the code to generate and submit the hidden form like this:

 var form = new Element('form',
                        {method: 'post', action: 'http://example.com/'});
 form.insert(new Element('input',
                         {name: 'q', value: 'a', type: 'hidden'}));
 $(document.body).insert(form);
 form.submit();

How add class='active' to html menu with php

why don't you do it like this:

in the pages:

<html>
   <head></head>
   <body>
      <?php $page = 'one'; include('navigation.php'); ?>
   </body>
</html>

in the navigation.php

<div id="nav">
   <ul>
      <li>
          <a <?php echo ($page == 'one') ? "class='active'" : ""; ?> 
                 href="index1.php">Tab1</a>/</li>
      <li>
          <a <?php echo ($page == 'two') ? "class='active'" : ""; ?> 
                  href="index2.php">Tab2</a>/</li>
      <li>
          <a <?php echo ($page == 'three') ? "class='active'" : ""; ?> 
                  href="index3.php">Tab3</a>/</li>
   </ul>
</div>

You will actually be able to control where in the page you are putting the navigation and what parameters you are passing to it.

Later edit: fixed syntax error.

PHP passing $_GET in linux command prompt

php -r 'parse_str($argv[2],$_GET);include $argv[1];' index.php 'a=1&b=2'

You could make the first part as an alias:

alias php-get='php -r '\''parse_str($argv[2],$_GET);include $argv[1];'\'

then simply use:

php-get some_script.php 'a=1&b=2&c=3'

How do I get a Date without time in Java?

Yo can use joda time.

private Date dateWitoutTime(Date date){
 return new LocalDate(date).toDate()
}

and you call with:

Date date = new Date();
System.out.println("Without Time = " + dateWitoutTime(date) + "/n  With time = " + date);

Combine two tables that have no common fields

If the tables have no common fields then there is no way to combine the data in any meaningful view. You would more likely end up with a view that contains duplicated data from both tables.

Value cannot be null. Parameter name: source

I got this error when I had an invalid Type for an entity property.

public Type ObjectType {get;set;}

When I removed the property the error stopped occurring.

Is it possible to write data to file using only JavaScript?

Some suggestions for this -

  1. If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
  2. If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
  3. To store some information on the client side that is considerably small, you can go for cookies.
  4. Using the HTML5 API for Local Storage.

How to set custom location for local installation of npm package?

TL;DR

You can do this by using the --prefix flag and the --global* flag.

pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower

*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

TL;DR

Every configurable attribute of npm can be set in any of six different places. In order of priority:

  • Command-Line Flags: --prefix ./vendor/node_modules
  • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
  • User Config File: $HOME/.npmrc or userconfig param
  • Global Config File: $PREFIX/etc/npmrc or userconfig param
  • Built-In Config File: path/to/npm/itself/npmrc
  • Default Config: node_modules/npmconf/config-defs.js

By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

You can run npm config list to see your current config and npm config edit to change it.

PS

In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

Fatal error: unexpectedly found nil while unwrapping an Optional values

I got his error when i was trying to access UILabel. I forgot to connect the UILabel to IBOutlet in Storyboard and that was causing the app to crash with this error!!

How to set dialog to show in full screen?

based on this link , the correct answer (which i've tested myself) is:

put this code in the constructor or the onCreate() method of the dialog:

getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT);

in addition , set the style of the dialog to :

<style name="full_screen_dialog">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>

this could be achieved via the constructor , for example :

public FullScreenDialog(Context context)
{
  super(context, R.style.full_screen_dialog);
  ...

EDIT: an alternative to all of the above would be to set the style to android.R.style.ThemeOverlay and that's it.

convert '1' to '0001' in JavaScript

String.prototype.padZero= function(len, c){
    var s= this, c= c || '0';
    while(s.length< len) s= c+ s;
    return s;
}

dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.

How to add hours to current time in python

Import datetime and timedelta:

>>> from datetime import datetime, timedelta
>>> str(datetime.now() + timedelta(hours=9))[11:19]
'01:41:44'

But the better way is:

>>> (datetime.now() + timedelta(hours=9)).strftime('%H:%M:%S')
'01:42:05'

You can refer strptime and strftime behavior to better understand how python processes dates and time field

Where IN clause in LINQ

I like it as an extension method:

public static bool In<T>(this T source, params T[] list)
{
    return list.Contains(source);
}

Now you call:

var states = _objdatasources.StateList().Where(s => s.In(countrycodes));

You can pass individual values too:

var states = tooManyStates.Where(s => s.In("x", "y", "z"));

Feels more natural and closer to sql.

String date to xmlgregoriancalendar conversion

GregorianCalendar c = GregorianCalendar.from((LocalDate.parse("2016-06-22")).atStartOfDay(ZoneId.systemDefault()));
XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

for each project in your solution make sure that

Properties > Config. Properties > General > Platform Toolset

is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012

you also may be working on v100 from visual studio 2012

Is there a "do ... while" loop in Ruby?

How about this?

people = []

until (info = gets.chomp).empty?
  people += [Person.new(info)]
end

How do I Search/Find and Replace in a standard string?

#include <boost/algorithm/string.hpp> // include Boost, a C++ library
...
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all(target, "foo", "bar");

Here is the official documentation on replace_all.

Convert UTC date time to local date time

Based on @digitalbath answer, here is a small function to grab the UTC timestamp and display the local time in a given DOM element (using jQuery for this last part):

https://jsfiddle.net/moriz/6ktb4sv8/1/

<div id="eventTimestamp" class="timeStamp">
   </div>
   <script type="text/javascript">
   // Convert UTC timestamp to local time and display in specified DOM element
   function convertAndDisplayUTCtime(date,hour,minutes,elementID) {
    var eventDate = new Date(''+date+' '+hour+':'+minutes+':00 UTC');
    eventDate.toString();
    $('#'+elementID).html(eventDate);
   }
   convertAndDisplayUTCtime('06/03/2015',16,32,'eventTimestamp');
   </script>

Regex expressions in Java, \\s vs. \\s+

Those two replaceAll calls will always produce the same result, regardless of what x is. However, it is important to note that the two regular expressions are not the same:

  • \\s - matches single whitespace character
  • \\s+ - matches sequence of one or more whitespace characters.

In this case, it makes no difference, since you are replacing everything with an empty string (although it would be better to use \\s+ from an efficiency point of view). If you were replacing with a non-empty string, the two would behave differently.

AngularJS ng-click to go to another page (with Ionic framework)

If you simply want to go to another page, then what you might need is a link that looks like a button with a href like so:

<a href="/#/somepage.html" class="button">Back to Listings</a>

Hope this helps.

excel formula to subtract number of days from a date

You can paste it like this:

= "2010-12-20" - 180

And don't forget to format the cell as a Date [CTRL]+[F1] / Number Tab

How to center form in bootstrap 3

There is a simple way of doing this in Bootstrap. Whenever I need to make a div center in a page, I divide all columns by 3 (total Bootstrap columns = 12, divided by 3 >>> 12/3 = 4). Dividing by four gives me three columns. Then I put my div in middle column. And all this math is performed by this way:

<div class="col-md-4 col-md-offset-4">my div here</div>

col-md-4 makes one column of 4 Bootstrap columns. Let's say it's the main column. col-md-offset-4 adds one column (of width of 4 Bootstrap column) to both sides of the main column.

Resize image with javascript canvas (smoothly)

You can use down-stepping to achieve better results. Most browsers seem to use linear interpolation rather than bi-cubic when resizing images.

(Update There has been added a quality property to the specs, imageSmoothingQuality which is currently available in Chrome only.)

Unless one chooses no smoothing or nearest neighbor the browser will always interpolate the image after down-scaling it as this function as a low-pass filter to avoid aliasing.

Bi-linear uses 2x2 pixels to do the interpolation while bi-cubic uses 4x4 so by doing it in steps you can get close to bi-cubic result while using bi-linear interpolation as seen in the resulting images.

_x000D_
_x000D_
var canvas = document.getElementById("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
var img = new Image();_x000D_
_x000D_
img.onload = function () {_x000D_
_x000D_
    // set size proportional to image_x000D_
    canvas.height = canvas.width * (img.height / img.width);_x000D_
_x000D_
    // step 1 - resize to 50%_x000D_
    var oc = document.createElement('canvas'),_x000D_
        octx = oc.getContext('2d');_x000D_
_x000D_
    oc.width = img.width * 0.5;_x000D_
    oc.height = img.height * 0.5;_x000D_
    octx.drawImage(img, 0, 0, oc.width, oc.height);_x000D_
_x000D_
    // step 2_x000D_
    octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);_x000D_
_x000D_
    // step 3, resize to final size_x000D_
    ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5,_x000D_
    0, 0, canvas.width, canvas.height);_x000D_
}_x000D_
img.src = "//i.imgur.com/SHo6Fub.jpg";
_x000D_
<img src="//i.imgur.com/SHo6Fub.jpg" width="300" height="234">_x000D_
<canvas id="canvas" width=300></canvas>
_x000D_
_x000D_
_x000D_

Depending on how drastic your resize is you can might skip step 2 if the difference is less.

In the demo you can see the new result is now much similar to the image element.

Selecting Values from Oracle Table Variable / Array?

In Oracle, the PL/SQL and SQL engines maintain some separation. When you execute a SQL statement within PL/SQL, it is handed off to the SQL engine, which has no knowledge of PL/SQL-specific structures like INDEX BY tables.

So, instead of declaring the type in the PL/SQL block, you need to create an equivalent collection type within the database schema:

CREATE OR REPLACE TYPE array is table of number;
/

Then you can use it as in these two examples within PL/SQL:

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    for i in (select level from dual connect by level < 10) loop
  5      p.extend;
  6      p(p.count) := i.level;
  7    end loop;
  8    for x in (select column_value from table(cast(p as array))) loop
  9       dbms_output.put_line(x.column_value);
 10    end loop;
 11* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

SQL> l
  1  declare
  2    p  array := array();
  3  begin
  4    select level bulk collect into p from dual connect by level < 10;
  5    for x in (select column_value from table(cast(p as array))) loop
  6       dbms_output.put_line(x.column_value);
  7    end loop;
  8* end;
SQL> /
1
2
3
4
5
6
7
8
9

PL/SQL procedure successfully completed.

Additional example based on comments

Based on your comment on my answer and on the question itself, I think this is how I would implement it. Use a package so the records can be fetched from the actual table once and stored in a private package global; and have a function that returns an open ref cursor.

CREATE OR REPLACE PACKAGE p_cache AS
  FUNCTION get_p_cursor RETURN sys_refcursor;
END p_cache;
/

CREATE OR REPLACE PACKAGE BODY p_cache AS

  cache_array  array;

  FUNCTION get_p_cursor RETURN sys_refcursor IS
    pCursor  sys_refcursor;
  BEGIN
    OPEN pCursor FOR SELECT * from TABLE(CAST(cache_array AS array));
    RETURN pCursor;
  END get_p_cursor;

  -- Package initialization runs once in each session that references the package
  BEGIN
    SELECT level BULK COLLECT INTO cache_array FROM dual CONNECT BY LEVEL < 10;
  END p_cache;
/

how to pass parameters to query in SQL (Excel)

This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.

This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.

So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.

Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))

What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.

First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:

[Picture of a cell of prompt (label) text, an empty cell, then a button.]

Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.

Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).

Sub RefreshQuery()
 Dim queryPreText As String
 Dim queryPostText As String
 Dim valueToFilter As String
 Dim paramPosition As Integer
 valueToFilter = "DB_TABLE_NAME.Field_Name ="

 With ActiveWorkbook.Connections("Connection name").OLEDBConnection
     queryPreText = .CommandText
     paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
     queryPreText = Left(queryPreText, paramPosition)
     queryPostText = .CommandText
     queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
     queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
     .CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
 End With
 ActiveWorkbook.Connections("Connection name").Refresh
End Sub

Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).

Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).

Save and close the VBA editor.

Enter your parameter in the appropriate cell.

Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!

Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".

This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.

HTML - how to make an entire DIV a hyperlink?

You can put an <a> element inside the <div> and set it to display: block and height: 100%.

UTF-8 text is garbled when form is posted as multipart/form-data

To avoid converting all request parameters manually to UTF-8, you can define a method annotated with @InitBinder in your controller:

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(String.class, new CharacterEditor(true) {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            String properText = new String(text.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            setValue(properText);
        }
    });
}

The above will automatically convert all request parameters to UTF-8 in the controller where it is defined.

How can I customize the tab-to-space conversion factor?

We can control tab size by file type with EditorConfig and its EditorConfig for VS Code extension. We then can make Alt + Shift + F specific to each file type.

Installation

Open the VS Code command palette with CTRL + P and paste this:

ext install EditorConfig

Example Configuration

.editorconfig

[*]
indent_style = space

[*.{js,ts,json}]
indent_size = 2

[*.java]
indent_size = 4

[*.go]
indent_style = tab

settings.json

EditorConfig overrides whatever settings.json configures for the editor. There is no need to change editor.detectIndentation.

How to get the scroll bar with CSS overflow on iOS

Apply this code in your css

::-webkit-scrollbar{

    -webkit-appearance: none;
    width: 7px;

}

::-webkit-scrollbar-thumb {

    border-radius: 4px;
    background-color: rgba(0,0,0,.5); 
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}

What does the question mark in Java generics' type parameter mean?

Perhaps a contrived "real world" example would help.

At my place of work we have rubbish bins that come in different flavours. All bins contain rubbish, but some bins are specialist and do not take all types of rubbish. So we have Bin<CupRubbish> and Bin<RecylcableRubbish>. The type system needs to make sure I can't put my HalfEatenSandwichRubbish into either of these types, but it can go into a general rubbish bin Bin<Rubbish>. If I wanted to talk about a Bin of Rubbish which may be specialised so I can't put in incompatible rubbish, then that would be Bin<? extends Rubbish>.

(Note: ? extends does not mean read-only. For instance, I can with proper precautions take out a piece of rubbish from a bin of unknown speciality and later put it back in a different place.)

Not sure how much that helps. Pointer-to-pointer in presence of polymorphism isn't entirely obvious.

seek() function?

For strings, forget about using WHENCE: use f.seek(0) to position at beginning of file and f.seek(len(f)+1) to position at the end of file. Use open(file, "r+") to read/write anywhere in a file. If you use "a+" you'll only be able to write (append) at the end of the file regardless of where you position the cursor.

How to check if the docker engine and a docker container are running?

Sometimes you don't know the full container name, in this case this is what worked for me:

if docker ps | grep -q keyword
then 
    echo "Running!"
else
    echo "Not running!"
    exit 1
fi

We list all the running container processes (docker ps -a would show us also not running ones, but that's not what I needed), we search for a specific word (grep part) and simply fail if we did not find at least one running container whose name contains our keyword.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

Reading a .txt file using Scanner class in Java

You should use either

File file = new File("bin/10_Random.txt");

Or

File file = new File("src/10_Random.txt");

Relative to the project folder in Eclipse.

How to import large sql file in phpmyadmin

Edit the config.inc.php file located in the phpmyadmin directory. In my case it is located at C:\wamp\apps\phpmyadmin3.2.0.1\config.inc.php.

Find the line with $cfg['UploadDir'] on it and update it to $cfg['UploadDir'] = 'upload';

Then, create a directory called ‘upload’ within the phpmyadmin directory (for me, at C:\wamp\apps\phpmyadmin3.2.0.1\upload\).

Then place the large SQL file that you are trying to import into the new upload directory. Now when you go onto the db import page within phpmyadmin console you will notice a drop down present that wasn’t there before – it contains all of the sql files in the upload directory that you have just created. You can now select this and begin the import.

If you’re not using WAMP on Windows, then I’m sure you’ll be able to adapt this to your environment without too much trouble.

Reference : http://daipratt.co.uk/importing-large-files-into-mysql-with-phpmyadmin/comment-page-4/

Python JSON serialize a Decimal object

You can create a custom JSON encoder as per your requirement.

import json
from datetime import datetime, date
from time import time, struct_time, mktime
import decimal

class CustomJSONEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, datetime):
            return str(o)
        if isinstance(o, date):
            return str(o)
        if isinstance(o, decimal.Decimal):
            return float(o)
        if isinstance(o, struct_time):
            return datetime.fromtimestamp(mktime(o))
        # Any other serializer if needed
        return super(CustomJSONEncoder, self).default(o)

The Decoder can be called like this,

import json
from decimal import Decimal
json.dumps({'x': Decimal('3.9')}, cls=CustomJSONEncoder)

and the output will be:

>>'{"x": 3.9}'

React JS - Uncaught TypeError: this.props.data.map is not a function

As mentioned in the accepted answer, this error is usually caused when the API returns data in a format, say object, instead of in an array.

If no existing answer here cuts it for you, you might want to convert the data you are dealing with into an array with something like:

let madeArr = Object.entries(initialApiResponse)

The resulting madeArr with will be an array of arrays.

This works fine for me whenever I encounter this error.

Accessing JPEG EXIF rotation data in JavaScript on the client side

Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)

There is also a bug to implement this in Chrome.

Beware that this property is only supported by Firefox and is likely to be deprecated.

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

Replace a string in a file with nodejs

Since replace wasn't working for me, I've created a simple npm package replace-in-file to quickly replace text in one or more files. It's partially based on @asgoth's answer.

Edit (3 October 2016): The package now supports promises and globs, and the usage instructions have been updated to reflect this.

Edit (16 March 2018): The package has amassed over 100k monthly downloads now and has been extended with additional features as well as a CLI tool.

Install:

npm install replace-in-file

Require module

const replace = require('replace-in-file');

Specify replacement options

const options = {

  //Single file
  files: 'path/to/file',

  //Multiple files
  files: [
    'path/to/file',
    'path/to/other/file',
  ],

  //Glob(s) 
  files: [
    'path/to/files/*.html',
    'another/**/*.path',
  ],

  //Replacement to make (string or regex) 
  from: /Find me/g,
  to: 'Replacement',
};

Asynchronous replacement with promises:

replace(options)
  .then(changedFiles => {
    console.log('Modified files:', changedFiles.join(', '));
  })
  .catch(error => {
    console.error('Error occurred:', error);
  });

Asynchronous replacement with callback:

replace(options, (error, changedFiles) => {
  if (error) {
    return console.error('Error occurred:', error);
  }
  console.log('Modified files:', changedFiles.join(', '));
});

Synchronous replacement:

try {
  let changedFiles = replace.sync(options);
  console.log('Modified files:', changedFiles.join(', '));
}
catch (error) {
  console.error('Error occurred:', error);
}

How do I use tools:overrideLibrary in a build.gradle file?

I just changed minSdkVersion="7" in C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml and it worked.

Steps:

  1. Path: C:\MyApp\platforms\android\CordovaLib\AndroidManifest.xml
  2. Value: <uses-sdk android:minSdkVersion="7"/>
  3. Ran command in new cmd prompt:

    C:\MyApp>phonegap build android --debug [phonegap] executing 'cordova build android --debug'... [phonegap] completed 'cordova build android --debug'

Saving an Excel sheet in a current directory with VBA

If the Path is omitted the file will be saved automaticaly in the current directory. Try something like this:

ActiveWorkbook.SaveAs "Filename.xslx"

How to use Apple's new San Francisco font on a webpage

If the user is running El Capitan or higher, it will work in Chrome with

font-family: 'BlinkMacSystemFont';

Interface extends another interface but implements its methods

An interface defines behavior. For example, a Vehicle interface might define the move() method.

A Car is a Vehicle, but has additional behavior. For example, the Car interface might define the startEngine() method. Since a Car is also a Vehicle, the Car interface extends the Vehicle interface, and thus defines two methods: move() (inherited) and startEngine().

The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move() and startEngine().

An interface may not implement any other interface. It can only extend it.

Usage of the backtick character (`) in JavaScript

Backticks enclose template literals, previously known as template strings. Template literals are string literals that allow embedded expressions and string interpolation features.

Template literals have expressions embedded in placeholders, denoted by the dollar sign and curly brackets around an expression, i.e. ${expression}. The placeholder / expressions get passed to a function. The default function just concatenates the string.

To escape a backtick, put a backslash before it:

`\`` === '`'; => true

Use backticks to more easily write multi-line string:

console.log(`string text line 1
string text line 2`);

or

console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);

vs. vanilla JavaScript:

console.log('string text line 1\n' +
'string text line 2');

or

console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');

Escape sequences:

  • Unicode escapes started by \u, for example \u00A9
  • Unicode code point escapes indicated by \u{}, for example \u{2F804}
  • Hexadecimal escapes started by \x, for example \xA9
  • Octal literal escapes started by \ and (a) digit(s), for example \251

System.Net.WebException HTTP status code

By using the null-conditional operator (?.) you can get the HTTP status code with a single line of code:

 HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;

The variable status will contain the HttpStatusCode. When the there is a more general failure like a network error where no HTTP status code is ever sent then status will be null. In that case you can inspect ex.Status to get the WebExceptionStatus.

If you just want a descriptive string to log in case of a failure you can use the null-coalescing operator (??) to get the relevant error:

string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
    ?? ex.Status.ToString();

If the exception is thrown as a result of a 404 HTTP status code the string will contain "NotFound". On the other hand, if the server is offline the string will contain "ConnectFailure" and so on.

(And for anybody that wants to know how to get the HTTP substatus code. That is not possible. It is a Microsoft IIS concept that is only logged on the server and never sent to the client.)

Checking if a double (or float) is NaN in C++

There is no isnan() function available in current C++ Standard Library. It was introduced in C99 and defined as a macro not a function. Elements of standard library defined by C99 are not part of current C++ standard ISO/IEC 14882:1998 neither its update ISO/IEC 14882:2003.

In 2005 Technical Report 1 was proposed. The TR1 brings compatibility with C99 to C++. In spite of the fact it has never been officially adopted to become C++ standard, many (GCC 4.0+ or Visual C++ 9.0+ C++ implementations do provide TR1 features, all of them or only some (Visual C++ 9.0 does not provide C99 math functions).

If TR1 is available, then cmath includes C99 elements like isnan(), isfinite(), etc. but they are defined as functions, not macros, usually in std::tr1:: namespace, though many implementations (i.e. GCC 4+ on Linux or in XCode on Mac OS X 10.5+) inject them directly to std::, so std::isnan is well defined.

Moreover, some implementations of C++ still make C99 isnan() macro available for C++ (included through cmath or math.h), what may cause more confusions and developers may assume it's a standard behaviour.

A note about Viusal C++, as mentioned above, it does not provide std::isnan neither std::tr1::isnan, but it provides an extension function defined as _isnan() which has been available since Visual C++ 6.0

On XCode, there is even more fun. As mentioned, GCC 4+ defines std::isnan. For older versions of compiler and library form XCode, it seems (here is relevant discussion), haven't had chance to check myself) two functions are defined, __inline_isnand() on Intel and __isnand() on Power PC.

Return Boolean Value on SQL Select Statement

I do it like this:

SELECT 1 FROM [dbo].[User] WHERE UserID = 20070022

Seeing as a boolean can never be null (at least in .NET), it should default to false or you can set it to that yourself if it's defaulting true. However 1 = true, so null = false, and no extra syntax.

Note: I use Dapper as my micro orm, I'd imagine ADO should work the same.

How do I get the directory that a program is running from?

As Minok mentioned, there is no such functionality specified ini C standard or C++ standard. This is considered to be purely OS-specific feature and it is specified in POSIX standard, for example.

Thorsten79 has given good suggestion, it is Boost.Filesystem library. However, it may be inconvenient in case you don't want to have any link-time dependencies in binary form for your program.

A good alternative I would recommend is collection of 100% headers-only STLSoft C++ Libraries Matthew Wilson (author of must-read books about C++). There is portable facade PlatformSTL gives access to system-specific API: WinSTL for Windows and UnixSTL on Unix, so it is portable solution. All the system-specific elements are specified with use of traits and policies, so it is extensible framework. There is filesystem library provided, of course.

Angular ng-repeat Error "Duplicates in a repeater are not allowed."

My JSON response was like this:

{"items": 
  &nbsp;[
    &nbsp;&nbsp;{
      "index": 1,
      "name": "Samantha",
      "rarity": "Scarborough",
      "email": "[email protected]"
    },
    &nbsp;&nbsp;{
      "index": 2,
      "name": "Amanda",
      "rarity": "Vick",
      "email": "[email protected]"
    }]
}

So, I used ng-repeat = "item in variables.items" to display it.

Using setImageDrawable dynamically to set image in an ImageView

Try this,

int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following

imageview.setImageResource(id);

Angular window resize event

Assuming that < 600px means mobile to you, you can use this observable and subscribe to it:

First we need the current window size. So we create an observable which only emits a single value: the current window size.

initial$ = Observable.of(window.innerWidth > 599 ? false : true);

Then we need to create another observable, so that we know when the window size was changed. For this we can use the "fromEvent" operator. To learn more about rxjs`s operators please visit: rxjs

resize$ = Observable.fromEvent(window, 'resize').map((event: any) => {
  return event.target.innerWidth > 599 ? false : true;
 });

Merg these two streams to receive our observable:

mobile$ = Observable.merge(this.resize$, this.initial$).distinctUntilChanged();

Now you can subscribe to it like this:

mobile$.subscribe((event) => { console.log(event); });

Remember to unsubscribe :)

Comment shortcut Android Studio

Mac:

To comment/uncomment one line, use: Ctrl + /.

To comment/uncomment a block, use: Ctrl + Shift + /.

Google Map API v3 — set bounds and center

The answers are perfect for adjust map boundaries for markers but if you like to expand Google Maps boundaries for shapes like polygons and circles, you can use following codes:

For Circles

bounds.union(circle.getBounds());

For Polygons

polygon.getPaths().forEach(function(path, index)
{
    var points = path.getArray();
    for(var p in points) bounds.extend(points[p]);
});

For Rectangles

bounds.union(overlay.getBounds());

For Polylines

var path = polyline.getPath();

var slat, blat = path.getAt(0).lat();
var slng, blng = path.getAt(0).lng();

for(var i = 1; i < path.getLength(); i++)
{
    var e = path.getAt(i);
    slat = ((slat < e.lat()) ? slat : e.lat());
    blat = ((blat > e.lat()) ? blat : e.lat());
    slng = ((slng < e.lng()) ? slng : e.lng());
    blng = ((blng > e.lng()) ? blng : e.lng());
}

bounds.extend(new google.maps.LatLng(slat, slng));
bounds.extend(new google.maps.LatLng(blat, blng));

Transform only one axis to log10 scale with ggplot2

I had a similar problem and this scale worked for me like a charm:

breaks = 10**(1:10)
scale_y_log10(breaks = breaks, labels = comma(breaks))

as you want the intermediate levels, too (10^3.5), you need to tweak the formatting:

breaks = 10**(1:10 * 0.5)
m <- ggplot(diamonds, aes(y = price, x = color)) + geom_boxplot()
m + scale_y_log10(breaks = breaks, labels = comma(breaks, digits = 1))

After executing::

enter image description here

How to disable scrolling the document body?

If you want to use the iframe's scrollbar and not the parent's use this:

document.body.style.overflow = 'hidden';

If you want to use the parent's scrollbar and not the iframe's then you need to use:

document.getElementById('your_iframes_id').scrolling = 'no';

or set the scrolling="no" attribute in your iframe's tag: <iframe src="some_url" scrolling="no">.

bash script use cut command at variable and store result at another variable

You can avoid the loop and cut etc by using:

awk -F ':' '{system("ping " $1);}' config.txt

However it would be better if you post a snippet of your config.txt

How to declare variable and use it in the same Oracle SQL script?

Try using double quotes if it's a char variable:

DEFINE stupidvar = "'stupidvarcontent'";

or

DEFINE stupidvar = 'stupidvarcontent';

SELECT stupiddata  
FROM stupidtable  
WHERE stupidcolumn = '&stupidvar'

upd:

SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 25 17:13:26 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> conn od/od@etalon
Connected.
SQL> define var = "'FL-208'";
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = 'FL-208'

CODE
---------------
FL-208

SQL> define var = 'FL-208';
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = FL-208
select code from product where code = FL-208
                                      *
ERROR at line 1:
ORA-06553: PLS-221: 'FL' is not a procedure or is undefined

CAST to DECIMAL in MySQL

If you need a lot of decimal numbers, in this example 17, I share with you MySql code:

This is the calculate:

=(9/1147)*100

SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);

new Date() is working in Chrome but not Firefox

You can't instantiate a date object any way you want. It has to be in a specific way. Here are some valid examples:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

or

d1 = new Date("October 13, 1975 11:13:00")
d2 = new Date(79,5,24)
d3 = new Date(79,5,24,11,33,0)

Chrome must just be more flexible.

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

From apsillers comment:

the EMCAScript specification requires exactly one date format (i.e., YYYY-MM-DDTHH:mm:ss.sssZ) but custom date formats may be freely supported by an implementation: "If the String does not conform to that [ECMAScript-defined] format the function may fall back to any implementation-specific heuristics or implementation-specific date formats." Chrome and FF simply have different "implementation-specific date formats."

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

Error in plot.new() : figure margins too large, Scatter plot

Every time you are creating plots you might get this error - "Error in plot.new() : figure margins too large". To avoid such errors you can first check par("mar") output. You should be getting:

[1] 5.1 4.1 4.1 2.1

To change that write:

par(mar=c(1,1,1,1))

This should rectify the error. Or else you can change the values accordingly.

Hope this works for you.

Simplest code for array intersection in javascript

If you need to have it handle intersecting multiple arrays:

_x000D_
_x000D_
const intersect = (a1, a2, ...rest) => {
  const a12 = a1.filter(value => a2.includes(value))
  if (rest.length === 0) { return a12; }
  return intersect(a12, ...rest);
};

console.log(intersect([1,2,3,4,5], [1,2], [1, 2, 3,4,5], [2, 10, 1])) 
_x000D_
_x000D_
_x000D_

How can I group data with an Angular filter?

I originally used Plantface's answer, but I didn't like how the syntax looked in my view.

I reworked it to use $q.defer to post-process the data and return a list on unique teams, which is then uses as the filter.

http://plnkr.co/edit/waWv1donzEMdsNMlMHBa?p=preview

View

<ul>
  <li ng-repeat="team in teams">{{team}}
    <ul>
      <li ng-repeat="player in players | filter: {team: team}">{{player.name}}</li> 
    </ul>
  </li>
</ul>

Controller

app.controller('MainCtrl', function($scope, $q) {

  $scope.players = []; // omitted from SO for brevity

  // create a deferred object to be resolved later
  var teamsDeferred = $q.defer();

  // return a promise. The promise says, "I promise that I'll give you your
  // data as soon as I have it (which is when I am resolved)".
  $scope.teams = teamsDeferred.promise;

  // create a list of unique teams. unique() definition omitted from SO for brevity
  var uniqueTeams = unique($scope.players, 'team');

  // resolve the deferred object with the unique teams
  // this will trigger an update on the view
  teamsDeferred.resolve(uniqueTeams);

});

Angular/RxJs When should I unsubscribe from `Subscription`

A lot of great answers here...

Let me add another alternative:

import { interval    } from "rxjs";
import { takeUntil   } from "rxjs/operators";
import { Component   } from "@angular/core";
import { Destroyable } from "@bespunky/angular-zen/core";

@Component({
    selector: 'app-no-leak-demo',
    template: ' Destroyable component rendered. Unload me and watch me cleanup...'
})
export class NoLeakComponent extends Destroyable
{
    constructor()
    {
        super();

        this.subscribeToInterval();
    }

    private subscribeToInterval(): void
    {
        const value    = interval(1000);
        const observer = {
            next    : value => console.log(` Destroyable: ${value}`),
            complete: ()    => console.log(' Observable completed.')
        };

        // ==== Comment one and uncomment the other to see the difference ====
        
        // Subscribe using the inherited subscribe method
         this.subscribe(value, observer);

        // ... or pipe-in the inherited destroyed subject
        //value.pipe(takeUntil(this.destroyed)).subscribe(observer);
    }
}

Live Example

What's happening here

The component/service extends Destroyable (which comes from a library called @bespunky/angular-zen).

The class can now simply use this.subscribe() or takeUntil(this.destroyed) without any additional boilerplate code.

To install the library use:
> npm install @bespunky/angular-zen

How to cd into a directory with space in the name?

To change to a directory with spaces on the name you just have to type like this:

cd My\ Documents

Hit enter and you will be good

Comparing mongoose _id and strings

The three possible solutions suggested here have different use cases.

  1. Use .equals when comparing ObjectID on two mongoDocuments like this

    results.userId.equals(AnotherMongoDocument._id)

  2. Use .toString() when comparing a string representation of ObjectID to an ObjectID of a mongoDocument. like this

    results.userId === AnotherMongoDocument._id.toString()

Issue in installing php7.2-mcrypt

@praneeth-nidarshan has covered mostly all the steps, except some:

  • Check if you have pear installed (or install):

$ sudo apt-get install php-pear

  • Install, if isn't already installed, php7.2-dev, in order to avoid the error:

sh: phpize: not found

ERROR: `phpize’ failed

$ sudo apt-get install php7.2-dev

  • Install mcrypt using pecl:

$ sudo pecl install mcrypt-1.0.1

  • Add the extention extension=mcrypt.so to your php.ini configuration file; if you don't know where it is, search with:

$ sudo php -i | grep 'Configuration File'

How to read a PEM RSA private key from .NET

ok, Im using mac to generate my self signed keys. Here is the working method I used.

I created a shell script to speed up my key generation.

genkey.sh

#/bin/sh

ssh-keygen -f host.key
openssl req -new -key host.key -out request.csr
openssl x509 -req -days 99999 -in request.csr -signkey host.key -out server.crt
openssl pkcs12 -export -inkey host.key -in server.crt -out private_public.p12 -name "SslCert"
openssl base64 -in private_public.p12 -out Base64.key

add the +x execute flag to the script

chmod +x genkey.sh

then call genkey.sh

./genkey.sh

I enter a password (important to include a password at least for the export at the end)

Enter pass phrase for host.key:
Enter Export Password:   {Important to enter a password here}
Verifying - Enter Export Password: { Same password here }

I then take everything in Base64.Key and put it into a string named sslKey

private string sslKey = "MIIJiAIBA...................................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        "......................ETC...................." +
                        ".............ugICCAA=";

I then used a lazy load Property getter to get my X509 Cert with a private key.

X509Certificate2 _serverCertificate = null;
X509Certificate2 serverCertificate{
    get
    {
        if (_serverCertificate == null){
            string pass = "Your Export Password Here";
            _serverCertificate = new X509Certificate(Convert.FromBase64String(sslKey), pass, X509KeyStorageFlags.Exportable);
        }
        return _serverCertificate;
    }
}

I wanted to go this route because I am using .net 2.0 and Mono on mac and I wanted to use vanilla Framework code with no compiled libraries or dependencies.

My final use for this was the SslStream to secure TCP communication to my app

SslStream sslStream = new SslStream(serverCertificate, false, SslProtocols.Tls, true);

I hope this helps other people.

NOTE

Without a password I was unable to correctly unlock the private key for export.

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

Importing JSON into an Eclipse project

You should take the json implementation from here : http://code.google.com/p/json-simple/ .

  • Download the *.jar
  • Add it to the classpath (right-click on the project, Properties->Libraries and add new JAR.)

Allow anything through CORS Policy

Just encountered with this issue in my rails application in production. A lot of answers here gave me hints and helped me to finally come to an answer that worked fine for me.

I am running Nginx and it was simple enough to just modify the my_app.conf file (where my_app is your app name). You can find this file in /etc/nginx/conf.d

If you do not have location / {} already you can just add it under server {}, then add add_header 'Access-Control-Allow-Origin' '*'; under location / {}.

The final format should look something like this:

server {
    server_name ...;
    listen ...;
    root ...;

    location / {
        add_header 'Access-Control-Allow-Origin' '*';
    }
}

Redis: How to access Redis log file

You can also login to the redis-cli and use the MONITOR command to see what queries are happening against Redis.

How can I list all tags for a Docker image on a remote registry?

The Docker V2 API requires an OAuth bearer token with the appropriate claims. In my opinion, the official documentation is rather vague on the topic. So that others don't go through the same pain I did, I offer the below docker-tags function.

The most recent version of docker-tags can be found in my GitHubGist : "List Docker Image Tags using bash".

The docker-tags function has a dependency on jq. If you're playing with JSON, you likely already have it.

#!/usr/bin/env bash
docker-tags() {
    arr=("$@")

    for item in "${arr[@]}";
    do
        tokenUri="https://auth.docker.io/token"
        data=("service=registry.docker.io" "scope=repository:$item:pull")
        token="$(curl --silent --get --data-urlencode ${data[0]} --data-urlencode ${data[1]} $tokenUri | jq --raw-output '.token')"
        listUri="https://registry-1.docker.io/v2/$item/tags/list"
        authz="Authorization: Bearer $token"
        result="$(curl --silent --get -H "Accept: application/json" -H "Authorization: Bearer $token" $listUri | jq --raw-output '.')"
        echo $result
    done
}

Example

docker-tags "microsoft/nanoserver" "microsoft/dotnet" "library/mongo" "library/redis"

Admittedly, docker-tags makes several assumptions. Specifically, the OAuth request parameters are mostly hard coded. A more ambitious implementation would make an unauthenticated request to the registry and derive the OAuth parameters from the unauthenticated response.

How to print number with commas as thousands separators?

Slightly expanding the answer of Ian Schneider:

If you want to use a custom thousands separator, the simplest solution is:

'{:,}'.format(value).replace(',', your_custom_thousands_separator)

Examples

'{:,.2f}'.format(123456789.012345).replace(',', ' ')

If you want the German representation like this, it gets a bit more complicated:

('{:,.2f}'.format(123456789.012345)
          .replace(',', ' ')  # 'save' the thousands separators 
          .replace('.', ',')  # dot to comma
          .replace(' ', '.')) # thousand separators to dot

Move div to new line

I've found that you can move div elements to the next line simply by setting the property Display: block;

On each div.

How to call Stored Procedure in a View?

exec sp_addlinkedserver 
        @server = 'local',
        @srvproduct = '',
        @provider='SQLNCLI',
        @datasrc = @@SERVERNAME
go

create view ViewTest
as
select * from openquery(local, 'sp_who')
go

select * from ViewTest
go

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code a little bit later on the same thread, I use this:

new android.os.Handler(Looper.getMainLooper()).postDelayed(
    new Runnable() {
        public void run() {
            Log.i("tag", "This'll run 300 milliseconds later");
        }
    }, 
300);

.. this is pretty much equivalent to

setTimeout( 
    function() {
        console.log("This will run 300 milliseconds later");
    },
300);

Defining private module functions in python

There may be confusion between class privates and module privates.

A module private starts with one underscore
Such a element is not copied along when using the from <module_name> import * form of the import command; it is however imported if using the import <moudule_name> syntax (see Ben Wilhelm's answer)
Simply remove one underscore from the a.__num of the question's example and it won't show in modules that import a.py using the from a import * syntax.

A class private starts with two underscores (aka dunder i.e. d-ouble under-score)
Such a variable has its name "mangled" to include the classname etc.
It can still be accessed outside of the class logic, through the mangled name.
Although the name mangling can serve as a mild prevention device against unauthorized access, its main purpose is to prevent possible name collisions with class members of the ancestor classes. See Alex Martelli's funny but accurate reference to consenting adults as he describes the convention used in regards to these variables.

>>> class Foo(object):
...    __bar = 99
...    def PrintBar(self):
...        print(self.__bar)
...
>>> myFoo = Foo()
>>> myFoo.__bar  #direct attempt no go
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'Foo' object has no attribute '__bar'
>>> myFoo.PrintBar()  # the class itself of course can access it
99
>>> dir(Foo)    # yet can see it
['PrintBar', '_Foo__bar', '__class__', '__delattr__', '__dict__', '__doc__', '__
format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__',
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__
', '__subclasshook__', '__weakref__']
>>> myFoo._Foo__bar  #and get to it by its mangled name !  (but I shouldn't!!!)
99
>>>

Fastest way to extract frames using ffmpeg?

I tried it. 3600 frame in 32 seconds. your method is really slow. You should try this.

ffmpeg -i file.mpg -s 240x135 -vf fps=1 %d.jpg

Why my regexp for hyphenated words doesn't work?

This regex should do it.

\b[a-z]+-[a-z]+\b 

\b indicates a word-boundary.

What does set -e mean in a bash script?

This is an old question, but none of the answers here discuss the use of set -e aka set -o errexit in Debian package handling scripts. The use of this option is mandatory in these scripts, per Debian policy; the intent is apparently to avoid any possibility of an unhandled error condition.

What this means in practice is that you have to understand under what conditions the commands you run could return an error, and handle each of those errors explicitly.

Common gotchas are e.g. diff (returns an error when there is a difference) and grep (returns an error when there is no match). You can avoid the errors with explicit handling:

diff this that ||
  echo "$0: there was a difference" >&2
grep cat food ||
  echo "$0: no cat in the food" >&2

(Notice also how we take care to include the current script's name in the message, and writing diagnostic messages to standard error instead of standard output.)

If no explicit handling is really necessary or useful, explicitly do nothing:

diff this that || true
grep cat food || :

(The use of the shell's : no-op command is slightly obscure, but fairly commonly seen.)

Just to reiterate,

something || other

is shorthand for

if something; then
    : nothing
else
    other
fi

i.e. we explicitly say other should be run if and only if something fails. The longhand if (and other shell flow control statements like while, until) is also a valid way to handle an error (indeed, if it weren't, shell scripts with set -e could never contain flow control statements!)

And also, just to be explicit, in the absence of a handler like this, set -e would cause the entire script to immediately fail with an error if diff found a difference, or if grep didn't find a match.

On the other hand, some commands don't produce an error exit status when you'd want them to. Commonly problematic commands are find (exit status does not reflect whether files were actually found) and sed (exit status won't reveal whether the script received any input or actually performed any commands successfully). A simple guard in some scenarios is to pipe to a command which does scream if there is no output:

find things | grep .
sed -e 's/o/me/' stuff | grep ^

It should be noted that the exit status of a pipeline is the exit status of the last command in that pipeline. So the above commands actually completely mask the status of find and sed, and only tell you whether grep finally succeeded.

(Bash, of course, has set -o pipefail; but Debian package scripts cannot use Bash features. The policy firmly dictates the use of POSIX sh for these scripts, though this was not always the case.)

In many situations, this is something to separately watch out for when coding defensively. Sometimes you have to e.g. go through a temporary file so you can see whether the command which produced that output finished successfully, even when idiom and convenience would otherwise direct you to use a shell pipeline.

A more useful statusline in vim?

What I've found useful is to know which copy/paste buffer (register) is currently active: %{v:register}. Otherwise, my complete status line looks almost exactly like the standard line.

:set statusline=%<%f\ %h%m%r\ %y%=%{v:register}\ %-14.(%l,%c%V%)\ %P

What is SELF JOIN and when would you use it?

You use a self join when a table references data in itself.

E.g., an Employee table may have a SupervisorID column that points to the employee that is the boss of the current employee.

To query the data and get information for both people in one row, you could self join like this:

select e1.EmployeeID, 
    e1.FirstName, 
    e1.LastName,
    e1.SupervisorID, 
    e2.FirstName as SupervisorFirstName, 
    e2.LastName as SupervisorLastName
from Employee e1
left outer join Employee e2 on e1.SupervisorID = e2.EmployeeID

Using File.listFiles with FileNameExtensionFilter

The FileNameExtensionFilter class is intended for Swing to be used in a JFileChooser.

Try using a FilenameFilter instead. For example:

File dir = new File("/users/blah/dirname");
File[] files = dir.listFiles(new FilenameFilter() {
    public boolean accept(File dir, String name) {
        return name.toLowerCase().endsWith(".txt");
    }
});

Setting a divs background image to fit its size?

Set your css to this

img {
    max-width:100%,
    max-height100%
}

Subtract two dates in Java

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

Can I set the cookies to be used by a WKWebView?

Here is how I am doing this-

call initWebConfig in didFinishLaunchingWithOptions of AppDelegate (or anywhere before creating the WebView) otherwise sometimes Cookies do not sync properly-

    func initWebConfig() {
        self.webConfig = WKWebViewConfiguration()
        self.webConfig.websiteDataStore = WKWebsiteDataStore.nonPersistent()
    }
           
    func setCookie(key: String, value: AnyObject, domain: String? = nil, group: DispatchGroup? = nil) {
                        
                        let cookieProps: [HTTPCookiePropertyKey : Any] = [
                            .domain: domain ?? "google.com",
                            .path: "/",
                            .name: key,
                            .value: value,
                        ]
                        
                        if let cookie = HTTPCookie(properties: cookieProps) {
                            group?.enter()
                            let webConfig = (UIApplication.shared.delegate as? AppDelegate)?.webConfig
          
webConfig?.websiteDataStore.httpCookieStore.setCookie(cookie) {
                                group?.leave()
                            }
                        }
                    }

Where required, set cookies in dispatch group-

 let group = DispatchGroup()
                self.setCookie(key: "uuid", value: "tempUdid" as AnyObject, group: group)
                self.setCookie(key: "name", value: "tempName" as AnyObject, group: group)
                
                group.notify(queue: DispatchQueue.main) {
                    //Create and Load WebView here 
                    let webConfig = (UIApplication.shared.delegate as? AppDelegate)?.webConfig ?? WKWebViewConfiguration()
                    //create urlRequest
                    let webView = WKWebView(frame: .zero, configuration: webConfig)
                    self.webView.load(urlRequest)
                }

Create a zip file and download it

One of the error could be that the file is not read as 'archive' format. check out ZipArchive not opening file - Error Code: 19. Open the downloaded file in text editor, if you have any html tags or debug statements at the starting, clear the buffer before reading the file.

ob_clean();
flush();
readfile("$archive_file_name");

How to get the HTML's input element of "file" type to only accept pdf files?

Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.

Parsing HTTP Response in Python

When I printed response.read() I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.

I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

Div height 100% and expands to fit content

Here is what you should do in the CSS style, on the main div

display: block;
overflow: auto;

And do not touch height

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

I had a problem where I needed the default action only after some custom action (enable otherwise disabled input fields on a form) had concluded. I wrapped the default action (submit()) into an own, recursive function (dosubmit()).

var prevdef=true;
var dosubmit=function(){
    if(prevdef==true){
        //here we can do something else first//
        prevdef=false;
        dosubmit();
    }
    else{
        $(this).submit();//which was the default action
    }
};

$('input#somebutton').click(function(){dosubmit()});

Getting the name / key of a JToken with JSON.net

JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"].ToList<JToken>(); 

foreach (JToken attribute in attributes)
{   
    JProperty jProperty = attribute.ToObject<JProperty>();
    string propertyName = jProperty.Name;
}

Xcode build failure "Undefined symbols for architecture x86_64"

For me, this started to happen after merge conflict.

I tried to clean and remove build folder, but none of it helped. This issue kept happening regardless. Then I relinked the reference by deleting the groups that was problematic and re-added to the project and it worked.

Logical Operators, || or OR?

The difference between respectively || and OR and && and AND is operator precedence :

$bool = FALSE || TRUE;

  • interpreted as ($bool = (FALSE || TRUE))
  • value of $bool is TRUE

$bool = FALSE OR TRUE;

  • interpreted as (($bool = FALSE) OR TRUE)
  • value of $bool is FALSE

$bool = TRUE && FALSE;

  • interpreted as ($bool = (TRUE && FALSE))
  • value of $bool is FALSE

$bool = TRUE AND FALSE;

  • interpreted as (($bool = TRUE) AND FALSE)
  • value of $bool is TRUE

How to change Angular CLI favicon

The ensure the browser downloads a new version of the favicon and does not use a cached version you can add a dummy parameter to the favicon url:

<link rel="icon" type="image/x-icon" href="favicon.ico?any=param">

Multipart File Upload Using Spring Rest Template + Spring Web MVC

For those who are getting the error as:

I/O error on POST request for "anothermachine:31112/url/path";: class path 
resource [fileName.csv] cannot be resolved to URL because it does not exist.

It can be resolved by using the

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(file));

If the file is not present in the classpath, and an absolute path is required.

Set type for function parameters?

Not in javascript it self but using Google Closure Compiler's advanced mode you can do that:

/**
 * @param {Date} myDate The date
 * @param {string} myString The string
 */
function myFunction(myDate, myString)
{
    //do stuff
}

See http://code.google.com/closure/compiler/docs/js-for-compiler.html

Unzip All Files In A Directory

This is a variant of Pedro Lobito answer using How to loop through a directory recursively to delete files with certain extensions teachings:

shopt -s globstar
root_directory="."

for zip_file_name in **/*.{zip,sublime\-package}; do
    directory_name=`echo $zip_file_name | sed 's/\.\(zip\|sublime\-package\)$//'`
    printf "Unpacking zip file \`$root_directory/$zip_file_name\`...\n"

    if [ -f "$root_directory/$zip_file_name" ]; then
        mkdir -p "$root_directory/$directory_name"
        unzip -o -q "$root_directory/$zip_file_name" -d "$directory_name"

        # Some files have the executable flag and were not being deleted because of it.
        # chmod -x "$root_directory/$zip_file_name"
        # rm -f "$root_directory/$zip_file_name"
    fi
done

How to return dictionary keys as a list in Python?

If you need to store the keys separately, here's a solution that requires less typing than every other solution presented thus far, using Extended Iterable Unpacking (python3.x+).

newdict = {1: 0, 2: 0, 3: 0}
*k, = newdict

k
# [1, 2, 3]

            +---------------------------------------------------------+
            ¦ k = list(d)   ¦   9 characters (excluding whitespace)   ¦
            +---------------+-----------------------------------------¦
            ¦ k = [*d]      ¦   6 characters                          ¦
            +---------------+-----------------------------------------¦
            ¦ *k, = d       ¦   5 characters                          ¦
            +---------------------------------------------------------+

How can I compare two dates in PHP?

first of all, try to give the format you want to the current date time of your server:

  1. Obtain current date time

    $current_date = getdate();

  2. Separate date and time to manage them as you wish:

$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday]; $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];

  1. Compare it depending if you are using donly date or datetime in your DB:

    $today = $current_date_only.' '.$current_time_only;

    or

    $today = $current_date_only;

    if($today < $expireDate)

hope it helps

Minimum Hardware requirements for Android development

Hey, I have used the same software on an AMD 3Ghz chip, dual core. had 2gbs of ram at the time, and i noticed the emulator ran at an alright speed, but took a ridiculous amount of time to load. I have not done enough development on Android to tell you if this is a common, or even still existing problem, but it is certainly something I remember from my experience.