Programs & Examples On #Visualize

Keras input explanation: input_shape, units, batch_size, dim, etc

Input Dimension Clarified:

Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:

It (the word dimension alone) can refer to:

a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"

b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or

"Input Layer / Input Feature Dimension"

c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.

"N Dimensionality of Input"

d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:

Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature

model = Sequential()
model.add(Dense(32, input_dim=784))  #or 3 in the current posted example above
model.add(Activation('relu'))

In Keras LSTM, it refers to the total Time Steps

The term has been very confusing, is correct and we live in a very confusing world!!

I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.

Error:Execution failed for task ':app:compileDebugKotlin'. > Compilation error. See log for more details

in my case I accidentally changed version="1.0" to xml version="1.0" in my XML file.

I only had to change it back.

if you have the same problem and the solutions above didn't work for you. open Gradle Console and scroll to Run with --debug option click it and it will show you more useful info about your error.

some notes:

this error doesn't appear directly after I make the change in XML it appear only after I change some java code. I think it has something to do with the instant run and build cash.

How to plot vectors in python using matplotlib

Thanks to everyone, each of your posts helped me a lot. rbierman code was pretty straight for my question, I have modified a bit and created a function to plot vectors from given arrays. I'd love to see any suggestions to improve it further.

import numpy as np
import matplotlib.pyplot as plt
def plotv(M):
    rows,cols = M.T.shape
    print(rows,cols)

    #Get absolute maxes for axis ranges to center origin
    #This is optional
    maxes = 1.1*np.amax(abs(M), axis = 0)
    colors = ['b','r','k']
    fig = plt.figure()
    fig.suptitle('Vectors', fontsize=10, fontweight='bold')

    ax = fig.add_subplot(111)
    fig.subplots_adjust(top=0.85)
    ax.set_title('Vector operations')

    ax.set_xlabel('x')
    ax.set_ylabel('y')

    for i,l in enumerate(range(0,cols)):
        # print(i)
        plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.2,head_length=0.1,zorder=3)

        ax.text(M[i,0],M[i,1], str(M[i]), style='italic',
            bbox={'facecolor':'red', 'alpha':0.5, 'pad':0.5})

    plt.plot(0,0,'ok') #<-- plot a black point at the origin
    # plt.axis('equal')  #<-- set the axes to the same scale
    plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
    plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits

    plt.grid(b=True, which='major') #<-- plot grid lines
    plt.show()

r = np.random.randint(4,size=[2,2])
print(r[0,:])
print(r[1,:])
r12 = np.add(r[0,:],r[1,:])
print(r12)
plotv(np.vstack((r,r12)))

Vector addition performed on random vectors

How do I use the Tensorboard callback of Keras?

You wrote log_dir='/Graph' did you mean ./Graph instead? You sent it to /home/user/Graph at the moment.

Correlation heatmap

Another alternative is to use the heatmap function in seaborn to plot the covariance. This example uses the Auto data set from the ISLR package in R (the same as in the example you showed).

import pandas.rpy.common as com
import seaborn as sns
%matplotlib inline

# load the R package ISLR
infert = com.importr("ISLR")

# load the Auto dataset
auto_df = com.load_data('Auto')

# calculate the correlation matrix
corr = auto_df.corr()

# plot the heatmap
sns.heatmap(corr, 
        xticklabels=corr.columns,
        yticklabels=corr.columns)

enter image description here

If you wanted to be even more fancy, you can use Pandas Style, for example:

cmap = cmap=sns.diverging_palette(5, 250, as_cmap=True)

def magnify():
    return [dict(selector="th",
                 props=[("font-size", "7pt")]),
            dict(selector="td",
                 props=[('padding', "0em 0em")]),
            dict(selector="th:hover",
                 props=[("font-size", "12pt")]),
            dict(selector="tr:hover td:hover",
                 props=[('max-width', '200px'),
                        ('font-size', '12pt')])
]

corr.style.background_gradient(cmap, axis=1)\
    .set_properties(**{'max-width': '80px', 'font-size': '10pt'})\
    .set_caption("Hover to magify")\
    .set_precision(2)\
    .set_table_styles(magnify())

enter image description here

How can I view the Git history in Visual Studio Code?

GitLens has a nice Git history browser. Install GitLens from the extensions marketplace, and then run "Show GitLens Explorer" from the command palette.

collapse cell in jupyter notebook

There are many answers to this question, all of which I feel are not satisfactory (some more than others), of the many extensions - code folding, folding by headings etc etc. None do what I want in simple and effective way. I am literally amazed that a solution has not been implemented (as it has for Jupyter Lab).

In fact, I was so dissatisfied that I have developed a very simple notebook extension that can expand/collapse the code in a notebook cell, while keeping it executable.

The GitHub repository: https://github.com/BenedictWilkinsAI/cellfolding

Below is a small demo of what the extension does:

Simply double clicking left of the code cell will collapse it to a single line:

Double clicking again will expand the cell.

The extension can be installed easily with pip:

pip install nbextension-cellfolding
jupyter nbextension install --py cellfolding --user
jupyter nbextension enable --py cellfolding --user 

and is also compatible with nbextension configurator. I hope that people will find this useful!

How to hide code from cells in ipython notebook visualized with nbviewer?

This is now possible directly from nbconvert as of version 5.2.1: content can be filtered using the built-in template exporter exclude options. For example:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb

will exclude the "input code" cells, ie the code itself. Similar options exist to exclude prompts, markdown cells, or outputs, or both inputs and outputs.

(These options should work irrespective of output format.)

Visualizing decision tree in scikit-learn

sklearn.tree.export_graphviz doesn't return anything, and so by default returns None.

By doing dotfile = tree.export_graphviz(...) you overwrite your open file object, which had been previously assigned to dotfile, so you get an error when you try to close the file (as it's now None).

To fix it change your code to

...
dotfile = open("D:/dtree2.dot", 'w')
tree.export_graphviz(dtree, out_file = dotfile, feature_names = X.columns)
dotfile.close()
...

Eclipse error "Could not find or load main class"

I was using eclipse oxygen and the problem persists everytime. Later i found that if your Eclipse workspace is under the directory with non ascii characters then somehow javaw.exe couldn't reach the bin directory. Suppose your directory name is Work_Hello the remove underscore sign and clean the project and run configurations. This worked for me. Reference: https://www.eclipse.org/forums/index.php/t/1093209/

How does one convert a grayscale image to RGB in OpenCV (Python)?

Try this:

import cv2
import cv

color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)

I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.

sklearn plot confusion matrix with labels

To add to @akilat90's update about sklearn.metrics.plot_confusion_matrix:

You can use the ConfusionMatrixDisplay class within sklearn.metrics directly and bypass the need to pass a classifier to plot_confusion_matrix. It also has the display_labels argument, which allows you to specify the labels displayed in the plot as desired.

The constructor for ConfusionMatrixDisplay doesn't provide a way to do much additional customization of the plot, but you can access the matplotlib axes obect via the ax_ attribute after calling its plot() method. I've added a second example showing this.

I found it annoying to have to rerun a classifier over a large amount of data just to produce the plot with plot_confusion_matrix. I am producing other plots off the predicted data, so I don't want to waste my time re-predicting every time. This was an easy solution to that problem as well.

Example:

from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()

confusion matrix example 1

Example using ax_:

cm = confusion_matrix(y_true, y_preds, normalize='all')
cmd = ConfusionMatrixDisplay(cm, display_labels=['business','health'])
cmd.plot()
cmd.ax_.set(xlabel='Predicted', ylabel='True')

confusion matrix example

How to retrieve unique count of a field using Kibana + Elastic Search

Create "topN" query on "clientip" and then histogram with count on "clientip" and set "topN" query as source. Then you will see count of different ips per time.

Add line break to ::after or ::before pseudo-element content

Add line break to ::after or ::before pseudo-element content

.yourclass:before {
    content: 'text here first \A  text here second';
    white-space: pre;
}

matplotlib: Group boxplots

Grouped boxplots, towards subtle academic publication styling... (source)

(Left) Python 2.7.12 Matplotlib v1.5.3. (Right) Python 3.7.3. Matplotlib v3.1.0.

grouped boxplot example png for Python 2.7.12 Matplotlib v1.5.3 grouped boxplot example png for Python 3.7.3 Matplotlib v3.1.0

Code:

import numpy as np
import matplotlib.pyplot as plt

# --- Your data, e.g. results per algorithm:
data1 = [5,5,4,3,3,5]
data2 = [6,6,4,6,8,5]
data3 = [7,8,4,5,8,2]
data4 = [6,9,3,6,8,4]

# --- Combining your data:
data_group1 = [data1, data2]
data_group2 = [data3, data4]

# --- Labels for your data:
labels_list = ['a','b']
xlocations  = range(len(data_group1))
width       = 0.3
symbol      = 'r+'
ymin        = 0
ymax        = 10

ax = plt.gca()
ax.set_ylim(ymin,ymax)
ax.set_xticklabels( labels_list, rotation=0 )
ax.grid(True, linestyle='dotted')
ax.set_axisbelow(True)
ax.set_xticks(xlocations)
plt.xlabel('X axis label')
plt.ylabel('Y axis label')
plt.title('title')

# --- Offset the positions per group:
positions_group1 = [x-(width+0.01) for x in xlocations]
positions_group2 = xlocations

plt.boxplot(data_group1, 
            sym=symbol,
            labels=['']*len(labels_list),
            positions=positions_group1, 
            widths=width, 
#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,
            )

plt.boxplot(data_group2, 
            labels=labels_list,
            sym=symbol,
            positions=positions_group2, 
            widths=width, 
#           notch=False,  
#           vert=True, 
#           whis=1.5,
#           bootstrap=None, 
#           usermedians=None, 
#           conf_intervals=None,
#           patch_artist=False,
            )

plt.savefig('boxplot_grouped.png')  
plt.savefig('boxplot_grouped.pdf')    # when publishing, use high quality PDFs
#plt.show()                   # uncomment to show the plot. 

Pointer-to-pointer dynamic two-dimensional array

this can be done this way

  1. I have used Operator Overloading
  2. Overloaded Assignment
  3. Overloaded Copy Constructor

    /*
     * Soumil Nitin SHah
     * Github: https://github.com/soumilshah1995
     */
    
    #include <iostream>
    using namespace std;
            class Matrix{
    
    public:
        /*
         * Declare the Row and Column
         *
         */
        int r_size;
        int c_size;
        int **arr;
    
    public:
        /*
         * Constructor and Destructor
         */
    
        Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
        {
            arr = new int*[r_size];
            // This Creates a 2-D Pointers
            for (int i=0 ;i < r_size; i++)
            {
                arr[i] = new int[c_size];
            }
    
            // Initialize all the Vector to 0 initially
            for (int row=0; row<r_size; row ++)
            {
                for (int column=0; column < c_size; column ++)
                {
                    arr[row][column] = 0;
                }
            }
            std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
        }
    
        ~Matrix()
        {
            std::cout << "Destructpr  -- Deleting  Array Size ::" << r_size <<" " << c_size << endl;
    
        }
    
        Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
    
        {
            for (int row=0; row<source.r_size; row ++)
            {
                for (int column=0; column < source.c_size; column ++)
                {
                    arr[row][column] = source.arr[row][column];
                }
            }
    
            cout << "Copy Constructor " << endl;
        }
    
    
    public:
        /*
         * Operator Overloading
         */
    
        friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
        {
            int rowCounter = 0;
            int columnCOUNTER = 0;
            int globalCounter = 0;
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    globalCounter = globalCounter + 1;
                }
                rowCounter = rowCounter + 1;
            }
    
    
            os << "Total There are " << globalCounter << " Elements" << endl;
            os << "Array Elements are as follow -------" << endl;
            os << "\n";
    
            for (int row =0; row < rhs.r_size; row ++)
            {
                for (int column=0; column < rhs.c_size ; column++)
                {
                    os << rhs.arr[row][column] << " ";
                }
            os <<"\n";
            }
            return os;
        }
    
        void operator()(int row, int column , int Data)
        {
            arr[row][column] = Data;
        }
    
        int &operator()(int row, int column)
        {
            return arr[row][column];
        }
    
        Matrix &operator=(Matrix &rhs)
                {
                    cout << "Assingment Operator called " << endl;cout <<"\n";
                    if(this == &rhs)
                    {
                        return *this;
                    } else
                        {
                        delete [] arr;
    
                            arr = new int*[r_size];
                            // This Creates a 2-D Pointers
                            for (int i=0 ;i < r_size; i++)
                            {
                                arr[i] = new int[c_size];
                            }
    
                            // Initialize all the Vector to 0 initially
                            for (int row=0; row<r_size; row ++)
                            {
                                for (int column=0; column < c_size; column ++)
                                {
                                    arr[row][column] = rhs.arr[row][column];
                                }
                            }
    
                            return *this;
                        }
    
                }
    
    };
    
                int main()
    {
    
        Matrix m1(3,3);         // Initialize Matrix 3x3
    
        cout << m1;cout << "\n";
    
        m1(0,0,1);
        m1(0,1,2);
        m1(0,2,3);
    
        m1(1,0,4);
        m1(1,1,5);
        m1(1,2,6);
    
        m1(2,0,7);
        m1(2,1,8);
        m1(2,2,9);
    
        cout << m1;cout <<"\n";             // print Matrix
        cout << "Element at Position (1,2) : " << m1(1,2) << endl;
    
        Matrix m2(3,3);
        m2 = m1;
        cout << m2;cout <<"\n";
    
        print(m2);
    
        return 0;
    }
    

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

How to remove outliers in boxplot in R?

See ?boxplot for all the help you need.

 outline: if ‘outline’ is not true, the outliers are not drawn (as
          points whereas S+ uses lines).

boxplot(x,horizontal=TRUE,axes=FALSE,outline=FALSE)

And for extending the range of the whiskers and suppressing the outliers inside this range:

   range: this determines how far the plot whiskers extend out from the
          box.  If ‘range’ is positive, the whiskers extend to the most
          extreme data point which is no more than ‘range’ times the
          interquartile range from the box. A value of zero causes the
          whiskers to extend to the data extremes.

# change the value of range to change the whisker length
boxplot(x,horizontal=TRUE,axes=FALSE,range=2)

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Margin is the spacing outside your element, just as padding is the spacing inside your element.

Setting the bottom margin indicates what distance you want below the current block. Setting a negative top margin indicates that you want negative spacing above your block. Negative spacing may in itself be a confusing concept, but just the way positive top margin pushes content down, a negative top margin pulls content up.

figure of imshow() is too small

If you don't give an aspect argument to imshow, it will use the value for image.aspect in your matplotlibrc. The default for this value in a new matplotlibrc is equal. So imshow will plot your array with equal aspect ratio.

If you don't need an equal aspect you can set aspect to auto

imshow(random.rand(8, 90), interpolation='nearest', aspect='auto')

which gives the following figure

imshow-auto

If you want an equal aspect ratio you have to adapt your figsize according to the aspect

fig, ax = subplots(figsize=(18, 2))
ax.imshow(random.rand(8, 90), interpolation='nearest')
tight_layout()

which gives you:

imshow-equal

Url to a google maps page to show a pin given a latitude / longitude?

From my notes:

http://maps.google.com/maps?q=37.4185N+122.08774W+(label)&ll=37.419731,-122.088715&spn=0.004250,0.011579&t=h&iwloc=A&hl=en

Which parses like this:

    q=latN+lonW+(label)     location of teardrop

    t=k             keyhole (satelite map)
    t=h             hybrid

    ll=lat,-lon     center of map
    spn=w.w,h.h     span of map, degrees

iwloc has something to do with the info window. hl is obviously language.

See also: http://www.seomoz.org/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

How can I reconcile detached HEAD with master/origin?

Get your detached commit onto its own branch

Simply run git checkout -b mynewbranch.

Then run git log, and you'll see that commit is now HEAD on this new branch.

How Can I Override Style Info from a CSS Class in the Body of a Page?

you can test a color by writing the CSS inline like <div style="color:red";>...</div>

Transform only one axis to log10 scale with ggplot2

The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:

m + geom_boxplot() + scale_y_continuous(trans='log10')

EDIT: Or if you don't like that, then either of these appears to give different but useful results:

m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot() 
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()

EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):

fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) + 
  geom_boxplot() + 
  scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)

alt text

Note added mid 2017 in comment about package syntax change:

scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I found this arrow(start, end) function on MATLAB Central which is perfect for this purpose of drawing vectors with true magnitude and direction.

What is the best free SQL GUI for Linux for various DBMS systems

I tried many GUI's, and the best for me continue being "SQLyog-comunity" by using wine. Is complete, is nice, and is intuitive. (and in wine work perfect)

compare differences between two tables in mysql

I found another solution in this link

SELECT MIN (tbl_name) AS tbl_name, PK, column_list
FROM
 (
  SELECT ' source_table ' as tbl_name, S.PK, S.column_list
  FROM source_table AS S
  UNION ALL
  SELECT 'destination_table' as tbl_name, D.PK, D.column_list
  FROM destination_table AS D 
)  AS alias_table
GROUP BY PK, column_list
HAVING COUNT(*) = 1
ORDER BY PK

How do I import a pre-existing Java project into Eclipse and get up and running?

  1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files).

  2. Also create a lib folder (the name isn't that important, but it follows standard conventions).

  3. Copy the ./com/* folders into the /src folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).

  4. Copy any dependencies (jar files that your project itself depends on) into /lib (note that this should NOT include the TGGL jar - thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!)

  5. Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)

  6. Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.

  7. The content of the /src folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). If you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files from the project classpath.

  8. Finally, open the /lib folder in Eclipse, right click on each required jar file and choose Build Path->Add to build path.

That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.

Eclipse/Maven error: "No compiler is provided in this environment"

  1. Uninstall older Java(JDK/JRE) from the system( Keep one (latest) java version), Also remove if any old java jre/jdk entries in environment variables PATH/CLASSPATH
  2. Eclipse->Window->Preferences->Installed JREs->Add/Edit JDK from the latest installation
  3. Eclipse->Window->Preferences->Installed JREs->Execution Environment->Select the desired java version on left and click the check box on right
  4. If you are using maven include the following tag in pom.xml (update versions as needed) inside plugins tag.

    <plugin>  
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
    
  5. Right click on eclipse project Maven - > Update Project

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

How to create checkbox inside dropdown?

Here is a simple dropdown checklist:

_x000D_
_x000D_
var checkList = document.getElementById('list1');
checkList.getElementsByClassName('anchor')[0].onclick = function(evt) {
  if (checkList.classList.contains('visible'))
    checkList.classList.remove('visible');
  else
    checkList.classList.add('visible');
}
_x000D_
.dropdown-check-list {
  display: inline-block;
}

.dropdown-check-list .anchor {
  position: relative;
  cursor: pointer;
  display: inline-block;
  padding: 5px 50px 5px 10px;
  border: 1px solid #ccc;
}

.dropdown-check-list .anchor:after {
  position: absolute;
  content: "";
  border-left: 2px solid black;
  border-top: 2px solid black;
  padding: 5px;
  right: 10px;
  top: 20%;
  -moz-transform: rotate(-135deg);
  -ms-transform: rotate(-135deg);
  -o-transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
  transform: rotate(-135deg);
}

.dropdown-check-list .anchor:active:after {
  right: 8px;
  top: 21%;
}

.dropdown-check-list ul.items {
  padding: 2px;
  display: none;
  margin: 0;
  border: 1px solid #ccc;
  border-top: none;
}

.dropdown-check-list ul.items li {
  list-style: none;
}

.dropdown-check-list.visible .anchor {
  color: #0094ff;
}

.dropdown-check-list.visible .items {
  display: block;
}
_x000D_
<div id="list1" class="dropdown-check-list" tabindex="100">
  <span class="anchor">Select Fruits</span>
  <ul class="items">
    <li><input type="checkbox" />Apple </li>
    <li><input type="checkbox" />Orange</li>
    <li><input type="checkbox" />Grapes </li>
    <li><input type="checkbox" />Berry </li>
    <li><input type="checkbox" />Mango </li>
    <li><input type="checkbox" />Banana </li>
    <li><input type="checkbox" />Tomato</li>
  </ul>
</div>
_x000D_
_x000D_
_x000D_

How to use Morgan logger?

Using morgan is pretty much straightforward. As the documentation suggests, there are different ways to get your desired output with morgan. It comes with preconfigured logging methods or you can define one yourself. Eg.

const morgan = require('morgan')

app.use(morgan('tiny')

This will give you the preconfiguration called tiny. You will notice in your terminal what it does. In case you are not satisfied with this and you want deeper e.g. lets say the request url, then this is where tokens come in.

morgan.token('url', function (req, res){ return '/api/myendpoint' })

then use it like so:

app.use(morgan(' :url ')

Check the documentation its all highlighted there.

How can I add to a List's first position?

Use List<T>.Insert(0, item) or a LinkedList<T>.AddFirst().

Height of status bar in Android

Since multi-window mode is available now, your app may not have statusbar on top.

Following solution handle all the cases automatically for you.

android:fitsSystemWindows="true"

or programatically

findViewById(R.id.your_root_view).setFitsSystemWindows(true);

you may also get root view by

findViewById(android.R.id.content).getRootView();
or
getWindow().getDecorView().findViewById(android.R.id.content)

For more details on getting root-view refer - https://stackoverflow.com/a/4488149/9640177

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

I finished my work on this stuff - that is, iOS 4 + iTunes 9.2 update of my backup decoder library for Python - http://www.iki.fi/fingon/iphonebackupdb.py

It does what I need, little documentation, but feel free to copy ideas from there ;-)

(Seems to work fine with my backups at least.)

array of string with unknown size

You can't create an array without a size. You'd need to use a list for that.

How do I trim a file extension from a String in Java?

public static String removeExtension(String file) {
    if(file != null && file.length() > 0) {
        while(file.contains(".")) {
            file = file.substring(0, file.lastIndexOf('.'));
        }
    }
    return file;
}

SQL Developer with JDK (64 bit) cannot find JVM

Installing jdk1.8.0_211 and setting the below variable in product.conf (located in C:\Users\\AppData\Roaming\sqldeveloper\19.1.0) to JDK8 home worked for me

SetJavaHome D:\jdk1.8.0_211

Linux bash script to extract IP address

A slight modification to one of the previous ip route ... solutions, which eliminates the need for a grep:

ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

I have also encounter the same issue. One possible solution is to go to Xcode -> Preferences -> Accounts and from the left menu select on App ID then click on the View Details and tap on the refresh button. while reloading you will get following error

The selected team's agent, 'ADMIN NAME' must agree to the latest Program License Agreement.

If you will not get above error, Following solution will not work.

It means that you need to login into the developer account using Admin login and accept that latest agreement. Then you will be able to upload binary on the app store.

Purpose of Unions in C and C++

@bobobobo code is correct as @Joshua pointed out (sadly I'm not allowed to add comments, so doing it here, IMO bad decision to disallow it in first place):

https://en.cppreference.com/w/cpp/language/data_members#Standard_layout tells that it is fine to do so, at least since C++14

In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2 (except that reading a volatile member through non-volatile glvalue is undefined).

since in the current case T1 and T2 donate the same type anyway.

What is the canonical way to check for errors using the CUDA runtime API?

talonmies' answer above is a fine way to abort an application in an assert-style manner.

Occasionally we may wish to report and recover from an error condition in a C++ context as part of a larger application.

Here's a reasonably terse way to do that by throwing a C++ exception derived from std::runtime_error using thrust::system_error:

#include <thrust/system_error.h>
#include <thrust/system/cuda/error.h>
#include <sstream>

void throw_on_cuda_error(cudaError_t code, const char *file, int line)
{
  if(code != cudaSuccess)
  {
    std::stringstream ss;
    ss << file << "(" << line << ")";
    std::string file_and_line;
    ss >> file_and_line;
    throw thrust::system_error(code, thrust::cuda_category(), file_and_line);
  }
}

This will incorporate the filename, line number, and an English language description of the cudaError_t into the thrown exception's .what() member:

#include <iostream>

int main()
{
  try
  {
    // do something crazy
    throw_on_cuda_error(cudaSetDevice(-1), __FILE__, __LINE__);
  }
  catch(thrust::system_error &e)
  {
    std::cerr << "CUDA error after cudaSetDevice: " << e.what() << std::endl;

    // oops, recover
    cudaSetDevice(0);
  }

  return 0;
}

The output:

$ nvcc exception.cu -run
CUDA error after cudaSetDevice: exception.cu(23): invalid device ordinal

A client of some_function can distinguish CUDA errors from other kinds of errors if desired:

try
{
  // call some_function which may throw something
  some_function();
}
catch(thrust::system_error &e)
{
  std::cerr << "CUDA error during some_function: " << e.what() << std::endl;
}
catch(std::bad_alloc &e)
{
  std::cerr << "Bad memory allocation during some_function: " << e.what() << std::endl;
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}
catch(...)
{
  std::cerr << "Some other kind of error during some_function" << std::endl;

  // no idea what to do, so just rethrow the exception
  throw;
}

Because thrust::system_error is a std::runtime_error, we can alternatively handle it in the same manner of a broad class of errors if we don't require the precision of the previous example:

try
{
  // call some_function which may throw something
  some_function();
}
catch(std::runtime_error &e)
{
  std::cerr << "Runtime error during some_function: " << e.what() << std::endl;
}

Hashing a dictionary?

While hash(frozenset(x.items()) and hash(tuple(sorted(x.items())) work, that's doing a lot of work allocating and copying all the key-value pairs. A hash function really should avoid a lot of memory allocation.

A little bit of math can help here. The problem with most hash functions is that they assume that order matters. To hash an unordered structure, you need a commutative operation. Multiplication doesn't work well as any element hashing to 0 means the whole product is 0. Bitwise & and | tend towards all 0's or 1's. There are two good candidates: addition and xor.

from functools import reduce
from operator import xor

class hashable(dict):
    def __hash__(self):
        return reduce(xor, map(hash, self.items()), 0)

    # Alternative
    def __hash__(self):
        return sum(map(hash, self.items()))

One point: xor works, in part, because dict guarantees keys are unique. And sum works because Python will bitwise truncate the results.

If you want to hash a multiset, sum is preferable. With xor, {a} would hash to the same value as {a, a, a} because x ^ x ^ x = x.

If you really need the guarantees that SHA makes, this won't work for you. But to use a dictionary in a set, this will work fine; Python containers are resiliant to some collisions, and the underlying hash functions are pretty good.

Convert ndarray from float64 to integer

While astype is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr in the following examples:

>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1.,  2.,  3.,  4.])

The int* functions from NumPy

>>> np.int64(arr)
array([1, 2, 3, 4])

>>> np.int_(arr)
array([1, 2, 3, 4])

The NumPy *array functions themselves:

>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])

The astype method (that was already mentioned but for completeness sake):

>>> arr.astype(int)
array([1, 2, 3, 4])

Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32 or np.int64.

What is the maximum float in Python?

sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.

Detect element content changes with jQuery

what about http://jsbin.com/esepal/2

$(document).bind("DOMSubtreeModified",function(){
  console.log($('body').width() + ' x '+$('body').height());
})

This event has been deprecated in favor of the Mutation Observer API

Adding delay between execution of two following lines

This line calls the selector secondMethod after 3 seconds:

[self performSelector:@selector(secondMethod) withObject:nil afterDelay:3.0 ];

Use it on your second operation with your desired delay. If you have a lot of code, place it in its own method and call that method with performSelector:. It wont block the UI like sleep

Edit: If you do not want a second method you could add a category to be able to use blocks with performSelector:

@implementation NSObject (PerformBlockAfterDelay)

- (void)performBlock:(void (^)(void))block 
          afterDelay:(NSTimeInterval)delay
{
    block = [block copy];
    [self performSelector:@selector(fireBlockAfterDelay:) 
               withObject:block 
               afterDelay:delay];
}

- (void)fireBlockAfterDelay:(void (^)(void))block
{
    block();
}

@end

Or perhaps even cleaner:

void RunBlockAfterDelay(NSTimeInterval delay, void (^block)(void))
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC*delay),
      dispatch_get_current_queue(), block);
}

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

How to add a .dll reference to a project in Visual Studio

Another method is by using the menu within visual studio. Project -> Add Reference... I recommend copying the needed .dll to your resource folder, or local project folder.

How to convert JSON object to an Typescript array?

To convert any JSON to array, use the below code:

const usersJson: any[] = Array.of(res.json());

How do I hide an element when printing a web page?

You could place the link within a div, then use JavaScript on the anchor tag to hide the div when clicked. Example (not tested, may need to be tweaked but you get the idea):

<div id="printOption">
    <a href="javascript:void();" 
       onclick="document.getElementById('printOption').style.visibility = 'hidden'; 
       document.print(); 
       return true;">
       Print
    </a>
</div>

The downside is that once clicked, the button disappears and they lose that option on the page (there's always Ctrl+P though).

The better solution would be to create a print stylesheet and within that stylesheet specify the hidden status of the printOption ID (or whatever you call it). You can do this in the head section of the HTML and specify a second stylesheet with a media attribute.

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

I also ran into that problem. My MVC4 App is running on a Windows Server 2012 R2 with IIS 8.5. None of these posted solutions worked for me...installing the missing frameworks through IIS Features could have solved it but the installation always failed.

I had to use the Web Platform Installer and installed the following packages:

enter image description here

How do I check/uncheck all checkboxes with a button using jQuery?

This is the shortest way I've found (needs jQuery1.6+)

HTML:

<input type="checkbox" id="checkAll"/>

JS:

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});

I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.

Example-

_x000D_
_x000D_
$("#checkAll").change(function () {_x000D_
    $("input:checkbox").prop('checked', $(this).prop("checked"));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form action="#">_x000D_
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>_x000D_
    _x000D_
    <fieldset>_x000D_
        <legend>Loads of checkboxes</legend>_x000D_
        <p><label><input type="checkbox" /> Option 1</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 2</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 3</label></p>_x000D_
        <p><label><input type="checkbox" /> Option 4</label></p>_x000D_
    </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Android Gradle Could not reserve enough space for object heap

I tried several solutions, nothing seemed to work. Setting my system JDK to match Android Studio's solved the problem.

Ensure your system java

java -version

Is the same as Androids

File > Project Structure > JDK Location

Including another class in SCSS

Looks like @mixin and @include are not needed for a simple case like this.

One can just do:

.myclass {
  font-weight: bold;
  font-size: 90px;
}

.myotherclass {
  @extend .myclass;
  color: #000000;
}

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

How to Empty Caches and Clean All Targets Xcode 4 and later

In addition to doing the following, you may experience this issue if your app's Storyboard's files are localized. First, do each of these:

  • Clean Build
  • Reset Simulator
  • Restart Xcode
  • Delete your DerivedData folder in ~/Library/Developer/Xcode/DerivedData
  • Restart Computer

What finally worked for me was re-generating the storyboard localization files and deleting the English localization (which was unneeded because the Base Locale is English). To reload your Storyboard strings, see this answer on StackOverflow.

I had noticed that the non-text parts of my Storyboard were being updated, but not the localized text. If you have a localization in your app, I would recommend checking to make sure your localizations are updated (even if they're .strings files).

Check if value is zero or not null in python

You can check if it can be converted to decimal. If yes, then its a number

from decimal import Decimal

def is_number(value):
    try:
        value = Decimal(value)
        return True
    except:
        return False

print is_number(None)   // False
print is_number(0)      // True
print is_number(2.3)    // True
print is_number('2.3')  // True (caveat!)

Python: What OS am I running on?

/usr/bin/python3.2

def cls():
    from subprocess import call
    from platform import system

    os = system()
    if os == 'Linux':
        call('clear', shell = True)
    elif os == 'Windows':
        call('cls', shell = True)

lists and arrays in VBA

You will have to change some of your data types but the basics of what you just posted could be converted to something similar to this given the data types I used may not be accurate.

Dim DateToday As String: DateToday = Format(Date, "yyyy/MM/dd")
Dim Computers As New Collection
Dim disabledList As New Collection
Dim compArray(1 To 1) As String

'Assign data to first item in array
compArray(1) = "asdf"

'Format = Item, Key
Computers.Add "ErrorState", "Computer Name"

'Prints "ErrorState"
Debug.Print Computers("Computer Name")

Collections cannot be sorted so if you need to sort data you will probably want to use an array.

Here is a link to the outlook developer reference. http://msdn.microsoft.com/en-us/library/office/ff866465%28v=office.14%29.aspx

Another great site to help you get started is http://www.cpearson.com/Excel/Topic.aspx

Moving everything over to VBA from VB.Net is not going to be simple since not all the data types are the same and you do not have the .Net framework. If you get stuck just post the code you're stuck converting and you will surely get some help!

Edit:

Sub ArrayExample()
    Dim subject As String
    Dim TestArray() As String
    Dim counter As Long

    subject = "Example"
    counter = Len(subject)

    ReDim TestArray(1 To counter) As String

    For counter = 1 To Len(subject)
        TestArray(counter) = Right(Left(subject, counter), 1)
    Next
End Sub

Importing larger sql files into MySQL

If you are using the source command on Windows remember to use f:/myfolder/mysubfolder/file.sql and not f:\myfolder\mysubfolder\file.sql

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

add to array if it isn't there already

Try adding as key instead of value:

Adding an entry

function addEntry($entry) {
    $this->entries[$entry] = true;
}

Getting all entries

function getEntries() {
    return array_keys($this->enties);
}

RVM is not a function, selecting rubies with 'rvm use ...' will not work

Following work for me in ubuntu 19.1

source ~/.rvm/scripts/rvm

Matching a space in regex

I'm trying out [[:space:]] in an instance where it looks like bloggers in WordPress are using non-standard space characters. It looks like it will work.

PHP - Getting the index of a element from a array

PHP arrays are both integer-indexed and string-indexed. You can even mix them:

array('red', 'green', 'white', 'color3'=>'blue', 3=>'yellow');

What do you want the index to be for the value 'blue'? Is it 3? But that's actually the index of the value 'yellow', so that would be an ambiguity.

Another solution for you is to coerce the array to an integer-indexed list of values.

foreach (array_values($array) as $i => $value) {
  echo "$i: $value\n";
}

Output:

0: red
1: green
2: white
3: blue
4: yellow

preg_match(); - Unknown modifier '+'

Try this code:

preg_match('/[a-zA-Z]+<\/a>.$/', $lastgame, $match);
print_r($match);

Using / as a delimiter means you also need to escape it here, like so: <\/a>.

UPDATE

preg_match('/<a.*<a.*>(.*)</', $lastgame, $match);
echo'['.$match[1].']';

Might not be the best way...

How do I commit only some files?

Suppose you made changes to multiple files, like:

  • File1
  • File2
  • File3
  • File4
  • File5

But you want to commit only changes of File1 and File3.

There are two ways for doing this:

1.Stage only these two files, using:

git add file1 file2

then, commit

git commit -m "your message"

then push,

git push

2.Direct commit

git commit file1 file3 -m "my message"

then push,

git push

Actually first method is useful in case if we are modifying files regularly and staging them --> Large Projects, generally Live projects.
But if we are modifying files and not staging them then we can do direct commit --> Small projects

how to remove untracked files in Git?

For deleting untracked files:

git clean -f

For deleting untracked directories as well, use:

git clean -f -d

For preventing any cardiac arrest, use

git clean -n -f -d

how do I get a new line, after using float:left?

Another approach that's a little more semantic is to have a UL defined as your total 6 image width, each LI defined as float left and width defined - so that when LI #7 hits, it runs into the boundry of the UL, and is pushed down to the new row. You'll still have an open float that you'll want to clear after the /UL - but that can be done on the next element of the page, or as a clear div. Here's sort of the idea, you may have to mess with actual values, but this should give you the idea. The code is a little cleaner.

 <style type="text/css"> 
ul#imageSet { width: 600px; margin: 0; padding:0; }
ul#imageSet li { float: left; width: 100px;  height: 188px; margin: 0; padding:0; position: relative; list-style-type: none; }
.cornerimage { position: absolute; bottom: 0; right: 0; } 
h3.nextelement { clear: both; }
</style>


<ul id="imageSet">
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
     <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
    <li>
        <img border="0" height="188" src="http://farm3.static.flickr.com/2459/3534790964_5d8bed17c0.jpg" width="100" />
        <img class="cornerimage" height="140" src="http://farm4.static.flickr.com/3310/3514664446_08e9745681.jpg" width="50" />
    </li>
</ul>


<h3 class="nextelement">Next Element in Doc</h3>

How can I do a BEFORE UPDATED trigger with sql server?

The updated or deleted values are stored in DELETED. we can get it by the below method in trigger

Full example,

CREATE TRIGGER PRODUCT_UPDATE ON PRODUCTS
FOR UPDATE 
AS
BEGIN
DECLARE @PRODUCT_NAME_OLD VARCHAR(100)
DECLARE @PRODUCT_NAME_NEW VARCHAR(100)

SELECT @PRODUCT_NAME_OLD = product_name from DELETED
SELECT @PRODUCT_NAME_NEW = product_name from INSERTED

END

json_decode() expects parameter 1 to be string, array given

Ok I was running into the same issue. What I failed to notice is that I was using json_decode() instead of using json_encode() so for those who are going to come here please make sure you are using the right function, which is json_encode()

Note: Depends on what you are working on but make sure you are using the right function.

#1273 – Unknown collation: ‘utf8mb4_unicode_520_ci’

I believe this error is caused because the local server and live server are running different versions of MySQL. To solve this:

  1. Open the sql file in your text editor
  2. Find and replace all utf8mb4_unicode_520_ci with utf8mb4_unicode_ci
  3. Save and upload to a fresh mySql db

Hope that helpsenter image description here

Windows Explorer "Command Prompt Here"

You can edit the registry to add the Command Prompt item to the context menu. Here are a couple of .reg files that I use.

Cmdhere.reg - for WinNT/2000/XP/Vista/7:

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew]
@="Command Prompt"
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew\Command]
@="cmd.exe /k cd %1"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew]
@="Command Prompt"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew\Command]
@="cmd.exe /k cd %1"

Doshere.reg - for Win9x:

REGEDIT4
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew]
@="MS-DOS Prompt"
[HKEY_CLASSES_ROOT\Directory\shell\OpenNew\Command]
@="command.com /k cd %1"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew]
@="MS-DOS Prompt"
[HKEY_CLASSES_ROOT\Drive\shell\OpenNew\Command]
@="command.com /k cd %1"

Copy this into an empty text file and change the extension to .reg. Double-clicking on this in Windows Explorer will add these key to the registry.

How to make fixed header table inside scrollable div?

Using position: sticky on th will do the trick.

Note: if you use position: sticky on thead or tr, it won't work.

https://jsfiddle.net/hrg3tmxj/

SQL select join: is it possible to prefix all columns as 'prefix.*'?

There is no SQL standard for this.

However With code generation (either on demand as the tables are created or altered or at runtime), you can do this quite easily:

CREATE TABLE [dbo].[stackoverflow_329931_a](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_a] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

CREATE TABLE [dbo].[stackoverflow_329931_b](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [col2] [nchar](10) NULL,
    [col3] [nchar](10) NULL,
    [col4] [nchar](10) NULL,
 CONSTRAINT [PK_stackoverflow_329931_b] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

DECLARE @table1_name AS varchar(255)
DECLARE @table1_prefix AS varchar(255)
DECLARE @table2_name AS varchar(255)
DECLARE @table2_prefix AS varchar(255)
DECLARE @join_condition AS varchar(255)
SET @table1_name = 'stackoverflow_329931_a'
SET @table1_prefix = 'a_'
SET @table2_name = 'stackoverflow_329931_b'
SET @table2_prefix = 'b_'
SET @join_condition = 'a.[id] = b.[id]'

DECLARE @CRLF AS varchar(2)
SET @CRLF = CHAR(13) + CHAR(10)

DECLARE @a_columnlist AS varchar(MAX)
DECLARE @b_columnlist AS varchar(MAX)
DECLARE @sql AS varchar(MAX)

SELECT @a_columnlist = COALESCE(@a_columnlist + @CRLF + ',', '') + 'a.[' + COLUMN_NAME + '] AS [' + @table1_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table1_name
ORDER BY ORDINAL_POSITION

SELECT @b_columnlist = COALESCE(@b_columnlist + @CRLF + ',', '') + 'b.[' + COLUMN_NAME + '] AS [' + @table2_prefix + COLUMN_NAME + ']'
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = @table2_name
ORDER BY ORDINAL_POSITION

SET @sql = 'SELECT ' + @a_columnlist + '
,' + @b_columnlist + '
FROM [' + @table1_name + '] AS a
INNER JOIN [' + @table2_name + '] AS b
ON (' + @join_condition + ')'

PRINT @sql
-- EXEC (@sql)

What is the best way to measure execution time of a function?

Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.

Hibernate Annotations - Which is better, field or property access?

To make your classes cleaner, put the annotation in the field then use @Access(AccessType.PROPERTY)

Calling a Sub and returning a value

Sub don't return values and functions don't have side effects.

Sometimes you want both side effect and return value.

This is easy to be done once you know that VBA passes arguments by default by reference so you can write your code in this way:

Sub getValue(retValue as Long)
    ...
    retValue = 42 
End SUb 

Sub Main()
    Dim retValue As Long
    getValue retValue 
    ... 
End SUb

Python: Select subset from list based on index set

I see 2 options.

  1. Using numpy:

    property_a = numpy.array([545., 656., 5.4, 33.])
    property_b = numpy.array([ 1.2,  1.3, 2.3, 0.3])
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = property_a[good_objects]
    property_bsel = property_b[good_indices]
    
  2. Using a list comprehension and zip it:

    property_a = [545., 656., 5.4, 33.]
    property_b = [ 1.2,  1.3, 2.3, 0.3]
    good_objects = [True, False, False, True]
    good_indices = [0, 3]
    property_asel = [x for x, y in zip(property_a, good_objects) if y]
    property_bsel = [property_b[i] for i in good_indices]
    

R Markdown - changing font size and font type in html output

I had the same issue and solved by making sure that 1. when you make the style.css file, make sure you didn't just rename a text file as "style.css", make sure it's really the .css format (e.g, use visual studio code); 2. put that style.css file in the same folder with your .rmd file. Hopefully this works for you.

.NET - Get protocol, host, and port

The following (C#) code should do the trick

Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;

The model backing the <Database> context has changed since the database was created

Good suggestion, however, nt so accurate in all cases. I figure one out. Please you need to make sure you run "enable-migrations" using PM windows in Visual Studio, and Migration folder would be added to you project.

Make sure the two c# class files added to the folder on will contain all your models and their respective properties.

If you have all that build the solution, and publis for deployment.

The logic is that the existing metadata cannot be overwritten because your application has no metadata to replace the current. As a result you are getting this error "The model backing the context has changed since the database was created"

How do I set up a private Git repository on GitHub? Is it even possible?

Update (2019, latest)

Since Jan 2019, GitHub allows private repositories for up to three collaborators.

Previous answer:

Here is the comparison for free plans listed by tree main Git Cloud based solutions:

Enter image description here

Here is the comparison for paid plans listed by tree main Git Cloud based solutions:

Enter image description here

Conclusion:

I'm not seeing people mentioning GitLab here, but it seems like the best free private plan for me. I myself am using it with no problems.

GitHub: If you have a student account or want to pay for $7 monthly, GitHub has the biggest community and you can take advantage of it's public repositories, forks, etc.

Bitbucket: If you use other products from Atlassian like Jira or Confluence, Bitbucket works great with them.

GitLab: Everything that I care about (free private repository, number of private repositories, number of collaborators, etc.) are offered for free. This seems like the best choice for me.

Why would you use String.Equals over ==?

There's a writeup on this article which you might find to be interesting, with some quotes from Jon Skeet. It seems like the use is pretty much the same.

Jon Skeet states that the performance of instance Equals "is slightly better when the strings are short—as the strings increase in length, that difference becomes completely insignificant."

Insertion Sort vs. Selection Sort

I'll give it yet another try: consider what happens in the lucky case of almost sorted array.

While sorting, the array can be thought of as having two parts: left hand side - sorted, right hand side - unsorted.

Insertion sort - pick first unsorted element and try to find a place for it among the already sorted part. Since you search from right to left it might very well happen that the first sorted element you are comparing to (the largest one, most right in the left part) is smaller than the picked element so you can immediately continue with the next unsorted element.

Selection sort - pick the first unsorted element and try to find the smallest element of the whole unsorted part, and exchange those two if desirable. The problem is, since the right part is unsorted, you have to go thought every element every time, since you cannot possibly be sure whether there is or is not even smaller element than the picked one.

Btw., this is exactly what heapsort improves upon selection sort - it is able to find the smallest element much more quickly because of the heap.

Tooltips with Twitter Bootstrap

I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:

<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>

Then you can trigger all links with the .link class attached as tooltips like so:

$('.link').tooltip()

Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel attribute. With this attribute you can target all links or elements with the rel property set to tooltip, like so:

$('[rel=tooltip]').tooltip() 

And your links would look like something like this:

<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>

Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:

$('#example').tooltip({
    selector: "a[rel=tooltip]"
})

This selector will target all of your tooltips with the rel attribute "within" your #example div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.

Add a new line to the end of a JtextArea

Are you using JTextArea's append(String) method to add additional text?

JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");

Centering elements in jQuery Mobile

In the situation where you are NOT going to use this over and over (i.e. not needed in your style sheet), inline style statements usually work anywhere they would work inyour style sheet. E.g:

<div data-role="controlgroup" data-type="horizontal" style="text-align:center;">

How can I specify system properties in Tomcat configuration on startup?

(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).

You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:

http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.

Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:

<env-entry>
    <env-entry-name>SMTP_PASSWORD</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>abc123ftw</env-entry-value>
</env-entry>

Eclipse compilation error: The hierarchy of the type 'Class name' is inconsistent

One more case I have had. Give the correct project path, and import it to eclipse.

Then go to Project--> Clean --> Clean all projects.

How to do a JUnit assert on a message in a logger

Another option is to mock Appender and verify if message was logged to this appender. Example for Log4j 1.2.x and mockito:

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

import org.apache.log4j.Appender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

public class MyTest {

    private final Appender appender = mock(Appender.class);
    private final Logger logger = Logger.getRootLogger();

    @Before
    public void setup() {
        logger.addAppender(appender);
    }

    @Test
    public void test() {
        // when
        Logger.getLogger(MyTest.class).info("Test");

        // then
        ArgumentCaptor<LoggingEvent> argument = ArgumentCaptor.forClass(LoggingEvent.class);
        verify(appender).doAppend(argument.capture());
        assertEquals(Level.INFO, argument.getValue().getLevel());
        assertEquals("Test", argument.getValue().getMessage());
        assertEquals("MyTest", argument.getValue().getLoggerName());
    }

    @After
    public void cleanup() {
        logger.removeAppender(appender);
    }
}

duplicate 'row.names' are not allowed error

This related question points out a part of the ?read.table documentation that explains your problem:

If there is a header and the first row contains one fewer field than the number of columns, the first column in the input is used for the row names. Otherwise if row.names is missing, the rows are numbered.

Your header row likely has 1 fewer column than the rest of the file and so read.table assumes that the first column is the row.names (which must all be unique), not a column (which can contain duplicated values). You can fix this by using one of the following two Solutions:

  1. adding a delimiter (ie \t or ,) to the front or end of your header row in the source file, or,
  2. removing any trailing delimiters in your data

The choice will depend on the structure of your data.

Example:
Here the header row is interpreted as having one fewer column than the data because the delimiters don't match:

v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

This is how it is interpreted by default:

   v1,v2,v3   # 3 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

The first column (with no header) values are interpreted as row.names: a1 and b1. If this column contains duplicates, which is entirely possible, then you get the duplicate 'row.names' are not allowed error.

If you set row.names = FALSE, the shift doesn't happen, but you still have a mismatching number of items in the header and in the data because the delimiters don't match.

Solution 1 Add trailing delimiter to header:

v1,v2,v3,  # 4 items!!
a1,a2,a3,  # 4 items
b1,b2,b3,  # 4 items

Solution 2 Remove excess trailing delimiter from non-header rows:

v1,v2,v3   # 3 items
a1,a2,a3   # 3 items!!
b1,b2,b3   # 3 items!!

How to convert JTextField to String and String to JTextField?

JTextField allows us to getText() and setText() these are used to get and set the contents of the text field, for example.

text = texfield.getText();

hope this helps

Google Android USB Driver and ADB

Locate the following file

C:\Users\[your name]\.android\adb_usb.ini

And make the following changes:

# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207

I added 0x2207 to the file. This number is part of the hardware id, which can be found under the device's hardware information.

Mine was:

USB\VID_2207&PID_0010&MI_01

(I tried executing android update adb, but it did nothing.)

Excel date to Unix timestamp

Here's my ultimate answer to this.

Also apparently javascript's new Date(year, month, day) constructor doesn't account for leap seconds too.

// Parses an Excel Date ("serial") into a
// corresponding javascript Date in UTC+0 timezone.
//
// Doesn't account for leap seconds.
// Therefore is not 100% correct.
// But will do, I guess, since we're
// not doing rocket science here.
//
// https://www.pcworld.com/article/3063622/software/mastering-excel-date-time-serial-numbers-networkdays-datevalue-and-more.html
// "If you need to calculate dates in your spreadsheets,
//  Excel uses its own unique system, which it calls Serial Numbers".
//
lib.parseExcelDate = function (excelSerialDate) {
  // "Excel serial date" is just
  // the count of days since `01/01/1900`
  // (seems that it may be even fractional).
  //
  // The count of days elapsed
  // since `01/01/1900` (Excel epoch)
  // till `01/01/1970` (Unix epoch).
  // Accounts for leap years
  // (19 of them, yielding 19 extra days).
  const daysBeforeUnixEpoch = 70 * 365 + 19;

  // An hour, approximately, because a minute
  // may be longer than 60 seconds, see "leap seconds".
  const hour = 60 * 60 * 1000;

  // "In the 1900 system, the serial number 1 represents January 1, 1900, 12:00:00 a.m.
  //  while the number 0 represents the fictitious date January 0, 1900".
  // These extra 12 hours are a hack to make things
  // a little bit less weird when rendering parsed dates.
  // E.g. if a date `Jan 1st, 2017` gets parsed as
  // `Jan 1st, 2017, 00:00 UTC` then when displayed in the US
  // it would show up as `Dec 31st, 2016, 19:00 UTC-05` (Austin, Texas).
  // That would be weird for a website user.
  // Therefore this extra 12-hour padding is added
  // to compensate for the most weird cases like this
  // (doesn't solve all of them, but most of them).
  // And if you ask what about -12/+12 border then
  // the answer is people there are already accustomed
  // to the weird time behaviour when their neighbours
  // may have completely different date than they do.
  //
  // `Math.round()` rounds all time fractions
  // smaller than a millisecond (e.g. nanoseconds)
  // but it's unlikely that an Excel serial date
  // is gonna contain even seconds.
  //
  return new Date(Math.round((excelSerialDate - daysBeforeUnixEpoch) * 24 * hour) + 12 * hour);
};

When to favor ng-if vs. ng-show/ng-hide?

If you use ng-show or ng-hide the content (eg. thumbnails from server) will be loaded irrespective of the value of expression but will be displayed based on the value of the expression.

If you use ng-if the content will be loaded only if the expression of the ng-if evaluates to truthy.

Using ng-if is a good idea in a situation where you are going to load data or images from the server and show those only depending on users interaction. This way your page load will not be blocked by unnecessary nw intensive tasks.

Eclipse does not highlight matching variables

Alt + Shift + o
Will solve your problem and agree with @Korhan Ozturk as well :)

This is known as Toggle Mark occurrence (Alt + Shift + O), Means will highlight all occurrence of focused variable. Same thing can be achieved from tool bar as follows

enter image description here

In same tool bar there is another switch if you turn that on you will see complete path for opened file, That is Breadcrumb enter image description here

there are some more very useful switches like word wrap, Show white Characters just after toggle mark occurrence

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Why doesn't the Scanner class have a nextChar method?

To get a definitive reason, you'd need to ask the designer(s) of that API.

But one possible reason is that the intent of a (hypothetical) nextChar would not fit into the scanning model very well.

  • If nextChar() to behaved like read() on a Reader and simply returned the next unconsumed character from the scanner, then it is behaving inconsistently with the other next<Type> methods. These skip over delimiter characters before they attempt to parse a value.

  • If nextChar() to behaved like (say) nextInt then:

    • the delimiter skipping would be "unexpected" for some folks, and

    • there is the issue of whether it should accept a single "raw" character, or a sequence of digits that are the numeric representation of a char, or maybe even support escaping or something1.

No matter what choice they made, some people wouldn't be happy. My guess is that the designers decided to stay away from the tarpit.


1 - Would vote strongly for the raw character approach ... but the point is that there are alternatives that need to be analysed, etc.

RegEx pattern any two letters followed by six numbers

You could try something like this:

[a-zA-Z]{2}[0-9]{6}

Here is a break down of the expression:

[a-zA-Z]    # Match a single character present in the list below
               # A character in the range between “a” and “z”
               # A character in the range between “A” and “Z”
   {2}         # Exactly 2 times
[0-9]       # Match a single character in the range between “0” and “9”
   {6}         # Exactly 6 times

This will match anywhere in a subject. If you need boundaries around the subject then you could do either of the following:

^[a-zA-Z]{2}[0-9]{6}$

Which ensures that the whole subject matches. I.e there is nothing before or after the subject.

or

\b[a-zA-Z]{2}[0-9]{6}\b

which ensures there is a word boundary on each side of the subject.

As pointed out by @Phrogz, you could make the expression more terse by replacing the [0-9] for a \d as in some of the other answers.

[a-zA-Z]{2}\d{6}

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

Open multiple Eclipse workspaces on the Mac

Window -> New Window

This opens a new window and you can then open another project in it. You can use this as a workaround hopefully.

It actually allows you to work in same workspace.

How to safely call an async method in C# without await

I guess the question arises, why would you need to do this? The reason for async in C# 5.0 is so you can await a result. This method is not actually asynchronous, but simply called at a time so as not to interfere too much with the current thread.

Perhaps it may be better to start a thread and leave it to finish on its own.

How to do INSERT into a table records extracted from another table

No "VALUES", no parenthesis:

INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;

Sorting arrays in javascript by object key value

Use Array's sort() method, eg

myArray.sort(function(a, b) {
    return a.distance - b.distance;
});

Cannot implicitly convert type 'int?' to 'int'.

The first problem encountered with your code is the message

Local variable OrdersPerHour might not be initialized before accessing.

It happens because in the case where your database query would throw an exception, the value might not be set to something (you have an empty catch clause).

To fix this, set the value to what you'd want to have if the query fails, which is probably 0 :

int? OrdersPerHour = 0;

Once this is fixed, now there's the error you're posting about. This happens because your method signature declares you are returning an int, but you are in fact returning a nullable int, int?, variable.

So to get the int part of your int?, you can use the .Value property:

return OrdersPerHour.Value;

However, if you declared your OrdersPerHour to be null at start instead of 0, the value can be null so a proper validation before returning is probably needed (Throw a more specific exception, for example).

To do so, you can use the HasValue property to be sure you're having a value before returning it:

if (OrdersPerHour.HasValue){
    return OrdersPerHour.Value;
}
else{
    // Handle the case here
}

As a side note, since you're coding in C# it would be better if you followed C#'s conventions. Your parameter and variables should be in camelCase, not PascalCase. So User and OrdersPerHour would be user and ordersPerHour.

VirtualBox Cannot register the hard disk already exists

1 - Open the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid (take note to revert this change on step 6)

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

2 - Reboot machine

4 - Stop Virtual Machine (if started)

5 - On terminal:

su vbox
cd /home/virtualbox/WindowsServer/
VBoxManage modifyhd WindowsServer.vdi --resize SIZE
exit
exit

change SIZE for a number in Megabytes, example 80000 (80GB)

6 - Open again the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid whith the original value

Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox

Change:

<HardDisks>
        <HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

To:

<HardDisks>
        <HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>

7 - Reboot machine

Running a shell script through Cygwin on Windows

Just wanted to add that you can do this to apply dos2unix fix for all files under a directory, as it saved me heaps of time when we had to 'fix' a bunch of our scripts.

find . -type f -exec dos2unix.exe {} \;

I'd do it as a comment to Roman's answer, but I don't have access to commenting yet.

Excel Reference To Current Cell

Full credit to the top answer by @rick-teachey, but you can extend that approach to work with Conditional Formatting. So that this answer is complete, I will duplicate Rick's answer in summary form and then extend it:

  1. Select cell A1 in any worksheet.
  2. Create a Named Range called THIS and set the Refers to: to =!A1.

Attempting to use THIS in Conditional Formatting formulas will result in the error:

You may not use references to other workbooks for Conditional Formatting criteria

If you want THIS to work in Conditional Formatting formulas:

  1. Create another Named Range called THIS_CF and set the Refers to: to =THIS.

You can now use THIS_CF to refer to the current cell in Conditional Formatting formulas.

You can also use this approach to create other relative Named Ranges, such as THIS_COLUMN, THIS_ROW, ROW_ABOVE, COLUMN_LEFT, etc.

How do I programmatically change file permissions?

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;

public class FileAndDirectory1 {
    public static void main(String[] args) {
        
        File file = new File("fileTest1.txt");
        System.out.println(file.getAbsoluteFile());
        try {
            //file.createNewFile();
            if(!file.exists())
            {
                //PosixFilePermission is an enum class, PosixFilePermissions is a final class
                
                //create file permissions from string
                Set<PosixFilePermission> filePermissions = PosixFilePermissions.fromString("---------"/* "rwxrwxrwx" */);
                FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(filePermissions);
                Files.createFile(file.toPath(), permissions);
                // printing the permissions associated with the file
                System.out.println("Executable: " + file.canExecute());
                System.out.println("Readable: " + file.canRead());
                System.out.println("Writable: "+ file.canWrite());

                file.setExecutable(true);
                file.setReadable(true);
                file.setWritable(true);
            }
            else
            {
                //modify permissions
                
                //get the permission using file attributes
                Set<PosixFilePermission> perms = Files.readAttributes(file.toPath(), PosixFileAttributes.class).permissions();
                perms.remove(PosixFilePermission.OWNER_WRITE);

                perms.add(PosixFilePermission.OWNER_READ);
                perms.add(PosixFilePermission.OWNER_EXECUTE);
                perms.add(PosixFilePermission.GROUP_WRITE);
                perms.add(PosixFilePermission.GROUP_READ);
                perms.add(PosixFilePermission.GROUP_EXECUTE);
                perms.add(PosixFilePermission.OTHERS_WRITE);
                perms.add(PosixFilePermission.OTHERS_READ);
                perms.add(PosixFilePermission.OTHERS_EXECUTE);
                Files.setPosixFilePermissions(file.toPath(), perms);

                System.out.println("Executable: " + file.canExecute());
                System.out.println("Readable: " + file.canRead());
                System.out.println("Writable: "+ file.canWrite());

                file.delete();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Path path = Paths.get(String.valueOf(file));
        System.out.println(path);
    }
}

Access a JavaScript variable from PHP

I'm looking at this and thinking, if you can only get variables into php in a form, why not just make a form and put a hidden input in the thing so it doesn't show on screen, and then put the value from your javascript into the hidden input and POST that into the php? It would sure be a lot less hassle than some of this other stuff right?

Fill remaining vertical space with CSS using display:flex

Here is the codepen demo showing the solution:

Important highlights:

  • all containers from html, body, ... .container, should have the height set to 100%
  • introducing flex to ANY of the flex items will trigger calculation of the items sizes based on flex distribution:
    • if only one cell is set to flex, for example: flex: 1 then this flex item will occupy the remaining of the space
    • if there are more than one with the flex property, the calculation will be more complicated. For example, if the item 1 is set to flex: 1 and the item 2 is se to flex: 2 then the item 2 will take twice more of the remaining space
  • Main Size Property

How do I type a TAB character in PowerShell?

Test with [char]9, such as:

$Tab = [char]9
Write-Output "$Tab hello"

Output:

     hello

How to get the current directory in a C program?

Although the question is tagged Unix, people also get to visit it when their target platform is Windows, and the answer for Windows is the GetCurrentDirectory() function:

DWORD WINAPI GetCurrentDirectory(
  _In_  DWORD  nBufferLength,
  _Out_ LPTSTR lpBuffer
);

These answers apply to both C and C++ code.

Link suggested by user4581301 in a comment to another question, and verified as the current top choice with a Google search 'site:microsoft.com getcurrentdirectory'.

Write bytes to file

Try this:

private byte[] Hex2Bin(string hex) 
{
 if ((hex == null) || (hex.Length < 1)) {
  return new byte[0];
 }
 int num = hex.Length / 2;
 byte[] buffer = new byte[num];
 num *= 2;
 for (int i = 0; i < num; i++) {
  int num3 = int.Parse(hex.Substring(i, 2), NumberStyles.HexNumber);
  buffer[i / 2] = (byte) num3;
  i++;
 }
 return buffer;
}

private string Bin2Hex(byte[] binary) 
{
 StringBuilder builder = new StringBuilder();
 foreach(byte num in binary) {
  if (num > 15) {
   builder.AppendFormat("{0:X}", num);
  } else {
   builder.AppendFormat("0{0:X}", num); /////// ?? 15 ???? 0
  }
 }
 return builder.ToString();
}

How do you stop MySQL on a Mac OS install?

For me it's working with a "mysql5"

sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

Create a OpenSSL certificate on Windows

To create a self signed certificate on Windows 7 with IIS 6...

  1. Open IIS

  2. Select your server (top level item or your computer's name)

  3. Under the IIS section, open "Server Certificates"

  4. Click "Create Self-Signed Certificate"

  5. Name it "localhost" (or something like that that is not specific)

  6. Click "OK"

You can then bind that certificate to your website...

  1. Right click on your website and choose "Edit bindings..."

  2. Click "Add"

    • Type: https
    • IP address: "All Unassigned"
    • Port: 443
    • SSL certificate: "localhost"
  3. Click "OK"

  4. Click "Close"

Is it possible to indent JavaScript code in Notepad++?

Could you use online services like this ?

Update: (as per request)

Google chrome will do this also http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html

Display filename before matching line

grep 'search this' *.txt

worked for me to search through all .txt files (enter your own search value, of course).

How to install "ifconfig" command in my ubuntu docker image?

From within a Dockerfile something like the following should do the trick:

RUN apt-get update && \
     apt-get install -y net-tools

From memory it's best practice to combine the update and the package installation lines to prevent docker caching the update step which can result in out-dated packages being installed.

Installing it via the CLI or a shell script:

apt-get update && apt-get install net-tools

Best practices for Storyboard login screen, handling clearing of data upon logout

Your storyboard should look like this

In your appDelegate.m inside your didFinishLaunchingWithOptions

//authenticatedUser: check from NSUserDefaults User credential if its present then set your navigation flow accordingly

if (authenticatedUser) 
{
    self.window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateInitialViewController];        
}
else
{
    UIViewController* rootController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"LoginViewController"];
    UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:rootController];

    self.window.rootViewController = navigation;
}

In SignUpViewController.m file

- (IBAction)actionSignup:(id)sender
{
    AppDelegate *appDelegateTemp = [[UIApplication sharedApplication]delegate];

    appDelegateTemp.window.rootViewController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateInitialViewController];
}

In file MyTabThreeViewController.m

- (IBAction)actionLogout:(id)sender {

    // Delete User credential from NSUserDefaults and other data related to user

    AppDelegate *appDelegateTemp = [[UIApplication sharedApplication]delegate];

    UIViewController* rootController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"LoginViewController"];

    UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:rootController];
    appDelegateTemp.window.rootViewController = navigation;

}

Swift 4 Version

didFinishLaunchingWithOptions in app delegate assuming your initial view controller is the signed in TabbarController.

if Auth.auth().currentUser == nil {
        let rootController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "WelcomeNavigation")
        self.window?.rootViewController = rootController
    }

    return true

In Sign up view controller:

@IBAction func actionSignup(_ sender: Any) {
let appDelegateTemp = UIApplication.shared.delegate as? AppDelegate
appDelegateTemp?.window?.rootViewController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateInitialViewController()
}

MyTabThreeViewController

 //Remove user credentials
guard let appDel = UIApplication.shared.delegate as? AppDelegate else { return }
        let rootController = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "WelcomeNavigation")
        appDel.window?.rootViewController = rootController

Access files stored on Amazon S3 through web browser

Filestash is the perfect tool for that:

  1. login to your bucket from https://www.filestash.app/s3-browser.html:

enter image description here

  1. create a shared link:

enter image description here

  1. Share it with the world

Also Filestash is open source. (Disclaimer: I am the author)

PHP CSV string to array

Handy oneliner:

$csv = array_map('str_getcsv', file('data.csv'));

Explaining the 'find -mtime' command

The POSIX specification for find says:

-mtimen The primary shall evaluate as true if the file modification time subtracted from the initialization time, divided by 86400 (with any remainder discarded), is n.

Interestingly, the description of find does not further specify 'initialization time'. It is probably, though, the time when find is initialized (run).

In the descriptions, wherever n is used as a primary argument, it shall be interpreted as a decimal integer optionally preceded by a plus ( '+' ) or minus-sign ( '-' ) sign, as follows:

+n More than n.
  n Exactly n.
-n Less than n.

At the given time (2014-09-01 00:53:44 -4:00, where I'm deducing that AST is Atlantic Standard Time, and therefore the time zone offset from UTC is -4:00 in ISO 8601 but +4:00 in ISO 9945 (POSIX), but it doesn't matter all that much):

1409547224 = 2014-09-01 00:53:44 -04:00
1409457540 = 2014-08-30 23:59:00 -04:00

so:

1409547224 - 1409457540 = 89684
89684 / 86400 = 1

Even if the 'seconds since the epoch' values are wrong, the relative values are correct (for some time zone somewhere in the world, they are correct).

The n value calculated for the 2014-08-30 log file therefore is exactly 1 (the calculation is done with integer arithmetic), and the +1 rejects it because it is strictly a > 1 comparison (and not >= 1).

Getting the current date in visual Basic 2008

User can use this

Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)

this will format the date as required whereas user can change the string type dd/MM/yyyy or MM/dd/yyyy or yyyy/MM/dd or even can have this format to get the time from date

yyyy/MM/dd HH:mm:ss 

How can I know which radio button is selected via jQuery?

try this one. it worked for me $('input[type="radio"][name="name"]:checked').val();

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

This is a very stubborn warning and while it is a valid warning there are some cases where it cannot be resolved due to use of 3rd party components and other reasons. I have a similar issue except that the warning is because my projects platform is AnyCPU and I'm referencing an MS library built for AMD64. This is in Visual Studio 2010 by the way, and appears to be introduced by installing the VS2012 and .Net 4.5.

Since I can't change the MS library I'm referencing, and since I know that my target deployment environment will only ever be 64-bit, I can safely ignore this issue.

What about the warning? Microsoft posted in response to a Connect report that one option is to disable that warning. You should only do this is you're very aware of your solution architecture and you fully understand your deployment target and know that it's not really an issue outside the development environment.

You can edit your project file and add this property group and setting to disable the warning:

<PropertyGroup>
  <ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>None</ResolveAssemblyWarnOrErrorOnTargetArchitectureMismatch>
</PropertyGroup>

Combine two (or more) PDF's

There's some good answers here already, but I thought I might mention that pdftk might be useful for this task. Instead of producing one PDF directly, you could produce each PDF you need and then combine them together as a post-process with pdftk. This could even be done from within your program using a system() or ShellExecute() call.

Why AVD Manager options are not showing in Android Studio

Usually this implies some Android setup issue with the project. Go to the "Resource Manager" tab where you will be able to click on "Add Android Module" and click on import gradle files. If the import fails, you will get error messages that you can work with enter image description here

How to update a record using sequelize for node?

You can use Model.update() method.

With async/await:

try{
  const result = await Project.update(
    { title: "Updated Title" }, //what going to be updated
    { where: { id: 1 }} // where clause
  )  
} catch (error) {
  // error handling
}

With .then().catch():

Project.update(
    { title: "Updated Title" }, //what going to be updated
    { where: { id: 1 }} // where clause
)
.then(result => {
  // code with result
})
.catch(error => {
  // error handling
})

error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

I have a similar problem. I try to run an example in tensorflow/models/objective_detection and met the same message. Try to change Python3 to Python2

Image resolution for new iPhone 6 and 6+, @3x support added?

UPDATE:

New link for the icons image size by apple.

https://developer.apple.com/ios/human-interface-guidelines/graphics/image-size-and-resolution/

enter image description here


Yes it's True here it is Apple provide Official documentation regarding icon's or image size

enter image description here

you have to set images for iPhone6 and iPhone6+

For iPhone 6:

750 x 1334 (@2x) for portrait

1334 x 750 (@2x) for landscape

For iPhone 6 Plus:

1242 x 2208 (@3x) for portrait

2208 x 1242 (@3x) for landscape

For more info regarding Images and it's resolution this is best ever helpful post

For setting images size for controls you can set 1x @2x and @3x like following:

enter image description here

How to call Oracle MD5 hash function?

In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.

select standard_hash('foo', 'MD5') from dual;

The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:

select rawtohex(
    DBMS_CRYPTO.Hash (
        UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
        2)
    ) from dual;

Output:

ACBD18DB4CC2F85CEDEF654FCCC4A4D8

Add a lower function call if needed. More on DBMS_CRYPTO.

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

There are some good answers for it. I want to explain it through demo per Doc

  • CMD defines default commands and/or parameters for a container. CMD is an instruction that is best to use if you need a default command which users can easily override. If a Dockerfile has multiple CMDs, it only applies the instructions from the last one.
  • ENTRYPOINT is preferred when you want to define a container with a specific executable.

You cannot override an ENTRYPOINT when starting a container unless you add the --entrypoint flag.

  1. CMD

Docker file

  FROM centos:8.1.1911

  CMD ["echo", "Hello Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname   # hostname is exec to override CMD
244be5006f32
  1. ENTRYPOINT

Docker file

  FROM centos:8.1.1911

  ENTRYPOINT ["echo", "Hello Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> hostname   # hostname as parameter to exec
Hello Docker hostname
  1. There are many situations in which combining CMD and ENTRYPOINT would be the best solution for your Docker container. In such cases, the executable is defined with ENTRYPOINT, while CMD specifies the default parameter.

Docker file

  FROM centos:8.1.1911

  ENTRYPOINT ["echo", "Hello"]
  CMD ["Docker"]

Run result

$ sudo docker run <image-id>
Hello Docker
$ sudo docker run <image-id> Ben
Hello Ben

Extract a substring according to a pattern

The unglue package provides an alternative, no knowledge about regular expressions is required for simple cases, here we'd do :

# install.packages("unglue")
library(unglue)
string = c("G1:E001", "G2:E002", "G3:E003")
unglue_vec(string,"{x}:{y}", var = "y")
#> [1] "E001" "E002" "E003"

Created on 2019-11-06 by the reprex package (v0.3.0)

More info : https://github.com/moodymudskipper/unglue/blob/master/README.md

How to open a new window on form submit

In a web-based database application that uses a pop-up window to display print-outs of database data, this worked well enough for our needs (tested in Chrome 48):

<form method="post" 
      target="print_popup" 
      action="/myFormProcessorInNewWindow.aspx"
      onsubmit="window.open('about:blank','print_popup','width=1000,height=800');">

The trick is to match the target attribute on the <form> tag with the second argument in the window.open call in the onsubmit handler.

JPQL IN clause: Java-Arrays (or Lists, Sets...)?

I had a problem with this kind of sql, I was giving empty list in IN clause(always check the list if it is not empty). Maybe my practice will help somebody.

How to obtain the start time and end time of a day?

Java 8


public static Date atStartOfDay(Date date) {
    LocalDateTime localDateTime = dateToLocalDateTime(date);
    LocalDateTime startOfDay = localDateTime.with(LocalTime.MIN);
    return localDateTimeToDate(startOfDay);
}

public static Date atEndOfDay(Date date) {
    LocalDateTime localDateTime = dateToLocalDateTime(date);
    LocalDateTime endOfDay = localDateTime.with(LocalTime.MAX);
    return localDateTimeToDate(endOfDay);
}

private static LocalDateTime dateToLocalDateTime(Date date) {
    return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}

private static Date localDateTimeToDate(LocalDateTime localDateTime) {
    return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
}

Update: I've added these 2 methods to my Java Utility Classes here

It is in the Maven Central Repository at:

<dependency>
  <groupId>com.github.rkumsher</groupId>
  <artifactId>utils</artifactId>
  <version>1.3</version>
</dependency>

Java 7 and Earlier


With Apache Commons

public static Date atEndOfDay(Date date) {
    return DateUtils.addMilliseconds(DateUtils.ceiling(date, Calendar.DATE), -1);
}

public static Date atStartOfDay(Date date) {
    return DateUtils.truncate(date, Calendar.DATE);
}

Without Apache Commons

public Date atEndOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 23);
    calendar.set(Calendar.MINUTE, 59);
    calendar.set(Calendar.SECOND, 59);
    calendar.set(Calendar.MILLISECOND, 999);
    return calendar.getTime();
}

public Date atStartOfDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);
    return calendar.getTime();
}

Using python's mock patch.object to change the return value of a method called within another method

This can be done with something like this:

# foo.py
class Foo:
    def method_1():
        results = uses_some_other_method()


# testing.py
from mock import patch

@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
    foo = Foo()
    the_value = foo.method_1()
    assert the_value == "specific_value"

Here's a source that you can read: Patching in the wrong place

How to get current time in python and break up into year, month, day, hour, minute?

For python 3

import datetime
now = datetime.datetime.now()
print(now.year, now.month, now.day, now.hour, now.minute, now.second)

Why is Visual Studio 2010 not able to find/open PDB files?

Referring to the first thread / another possibility VS cant open or find pdb file of the process is when you have your executable running in the background. I was working with mpiexec and ran into this issue. Always check your task manager and kill any exec process that your gonna build in your project. Once I did that, it debugged or built fine.

Also, if you try to continue with the warning , the breakpoints would not be hit and it would not have the current executable

Pass a javascript variable value into input type hidden value

You could give your hidden field an id:

<input type="hidden" id="myField" value="" />

and then when you want to assign its value:

document.getElementById('myField').value = product(2, 3);

Make sure that you are performing this assignment after the DOM has been fully loaded, for example in the window.load event.

Python CSV error: line contains NULL byte

As @S.Lott says, you should be opening your files in 'rb' mode, not 'rU' mode. However that may NOT be causing your current problem. As far as I know, using 'rU' mode would mess you up if there are embedded \r in the data, but not cause any other dramas. I also note that you have several files (all opened with 'rU' ??) but only one causing a problem.

If the csv module says that you have a "NULL" (silly message, should be "NUL") byte in your file, then you need to check out what is in your file. I would suggest that you do this even if using 'rb' makes the problem go away.

repr() is (or wants to be) your debugging friend. It will show unambiguously what you've got, in a platform independant fashion (which is helpful to helpers who are unaware what od is or does). Do this:

print repr(open('my.csv', 'rb').read(200)) # dump 1st 200 bytes of file

and carefully copy/paste (don't retype) the result into an edit of your question (not into a comment).

Also note that if the file is really dodgy e.g. no \r or \n within reasonable distance from the start of the file, the line number reported by reader.line_num will be (unhelpfully) 1. Find where the first \x00 is (if any) by doing

data = open('my.csv', 'rb').read()
print data.find('\x00')

and make sure that you dump at least that many bytes with repr or od.

What does data.count('\x00') tell you? If there are many, you may want to do something like

for i, c in enumerate(data):
    if c == '\x00':
        print i, repr(data[i-30:i]) + ' *NUL* ' + repr(data[i+1:i+31])

so that you can see the NUL bytes in context.

If you can see \x00 in the output (or \0 in your od -c output), then you definitely have NUL byte(s) in the file, and you will need to do something like this:

fi = open('my.csv', 'rb')
data = fi.read()
fi.close()
fo = open('mynew.csv', 'wb')
fo.write(data.replace('\x00', ''))
fo.close()

By the way, have you looked at the file (including the last few lines) with a text editor? Does it actually look like a reasonable CSV file like the other (no "NULL byte" exception) files?

:before and background-image... should it work?

@michi; define height in your before pseudo class

CSS:

#videos-part:before{
    width: 16px;
    content: " ";
    background-image: url(/img/border-left3.png);
    position: absolute;
    left: -16px;
    top: -6px;
    height:20px;
}

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

How do I loop through a list by twos?

You can also use this syntax (L[start:stop:step]):

mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
    print i,
# prints 1 3 5 7 9

for i in mylist[1::2]:
    print i,
# prints 2 4 6 8 10

Where the first digit is the starting index (defaults to beginning of list or 0), 2nd is ending slice index (defaults to end of list), and the third digit is the offset or step.

How to get last 7 days data from current datetime to last 7 days in sql server

This worked for me!!

SELECT * FROM `users` where `created_at` BETWEEN CURDATE()-7 AND CURDATE()

How to assign pointer address manually in C programming language?

Like this:

void * p = (void *)0x28ff44;

Or if you want it as a char *:

char * p = (char *)0x28ff44;

...etc.

If you're pointing to something you really, really aren't meant to change, add a const:

const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;

...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.

html - table row like a link

When i want simulate a <tr> with a link but respecting the html standards, I do this.

HTML:

<table>
    <tr class="trLink">
        <td>
            <a href="#">Something</a>
        </td>
    </tr>
</table>

CSS:

tr.trLink {
    cursor: pointer;
}
tr.trLink:hover {
   /*TR-HOVER-STYLES*/
}

tr.trLink a{
    display: block;
    height: 100%;
    width: 100%;
}
tr.trLink:hover a{
   /*LINK-HOVER-STYLES*/
}

In this way, when someone go with his mouse on a TR, all the row (and this links) gets the hover style and he can't see that there are multiple links.

Hope can help someone.

Fiddle HERE

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

At first, the problem is because you did't put any parameter for mysqli_error. I can see that it has been solved based on the post here. Most probably, the next problem is cause by wrong file path for the included file.. .

Are you sure this code

$myConnection = mysqli_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");

is in the 'scripts' folder and your main code file is on the same level as the script folder?

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Node.js Web Application examples/tutorials

The Node Knockout competition wrapped up recently, and many of the submissions are available on github. The competition site doesn't appear to be working right now, but I'm sure you could Google up a few entries to check out.

Laravel PDOException SQLSTATE[HY000] [1049] Unknown database 'forge'

write

php artisan config:cache 

in your terminal and it will be fixed

Using <style> tags in the <body> with other HTML

Not valid HTML, anyway pretty much every browser seems to consider just the second instance.

Tested under the last versions of FF and Google Chrome under Fedora, and FF, Opera, IE, and Chrome under XP.

AngularJs: Reload page

My solution to avoid the infinite loop was to create another state which have made the redirection:

$stateProvider.state('app.admin.main', {
    url: '/admin/main',
    authenticate: 'admin',
    controller: ($state, $window) => {
      $state.go('app.admin.overview').then(() => {
        $window.location.reload();
      });
    }
  });

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Security is one aspect you missed.

With Websockets the data has to go via a central webserver which typically sees all the traffic and can access it.

With WebRTC the data is end-to-end encrypted and does not pass through a server (except sometimes TURN servers are needed, but they have no access to the body of the messages they forward).

Depending on your application this may or may not matter.

If you are sending large amounts of data, the saving in cloud bandwidth costs due to webRTC's P2P architecture may be worth considering too.

HTML list-style-type dash

You could use :before and content: bearing in mind that this is not supported in IE 7 or below. If you're OK with that then this is your best solution. See the Can I Use or QuirksMode CSS compatibility tables for full details.

A slightly nastier solution that should work in older browsers is to use an image for the bullet point and just make the image look like a dash. See the W3C list-style-image page for examples.

Sass Variable in CSS calc() function

To use $variables inside your calc() of the height property:

HTML:

<div></div>

SCSS:

$a: 4em;

div {
  height: calc(#{$a} + 7px);
  background: #e53b2c;
}

Adding close button in div to close the box

You can use this jsFiddle

And HTML:

<div id="previewBox">
    <button id="closeButton">Close</button>
<a class="fragment" href="google.com">
    <div>
    <img src ="http://placehold.it/116x116" alt="some description"/> 
    <h3>the title will go here</h3>
        <h4> www.myurlwill.com </h4>
    <p class="text">
        this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc 
    </p>
</div>
</a>
</div>

With JS (jquery required):

$(document).ready(function() {
    $('#closeButton').on('click', function(e) { 
        $('#previewBox').remove(); 
    });
});

How do you run `apt-get` in a dockerfile behind a proxy?

Use --build-arg in lower case environment variable:

docker build --build-arg http_proxy=http://proxy:port/ --build-arg https_proxy=http://proxy:port/ --build-arg ftp_proxy=http://proxy:port --build-arg no_proxy=localhost,127.0.0.1,company.com -q=false .

Chmod 777 to a folder and all contents

for mac, should be a ‘superuser do’;

so first :

sudo -s 
password:

and then

chmod -R 777 directory_path

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

It's a bit of a guess but could the quotes around happy be the problem? There have been some problems in the past where Android would either add or not recognize quotes around an SSID. Try setting up the hosted network connection again, but without the quotes that we see in the output for netsh wlan show hostednetwork.

How can I access my localhost from my Android device?

If you're running on Linux this works for me

sudo iptables -F

Move layouts up when soft keyboard is shown?

Alright this is very late however I've discovered that if you add a List View under your edit text then the keyboard will move all layouts under that edittext without moving the ListView

<EditText
android:id="@+id/et"
android:layout_height="match_parent"
android:layout_width="match_parent"



/>

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"//can make as 1dp
    android:layout_below="@+id/et" // set to below editext
    android:id="@+id/view"
    >
**<any layout**

This is the only solution that worked for me.

Determine the size of an InputStream

Use this method, you just have to pass the InputStream

public String readIt(InputStream is) {
    if (is != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);

        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line).append("\n");
        }
        is.close();
        return sb.toString();
    }
    return "error: ";
}

Get GPS location via a service in Android

ok , i've solved it by creating a handler on the onCreate of the service , and calling the gps functions through there .

The code is as simple as this:

final handler=new Handler(Looper.getMainLooper()); 

And then to force running things on the UI, I call post on it.

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

What does "The APR based Apache Tomcat Native library was not found" mean?

If you don't have Tomcat Native library install it with:

sudo apt-get install libtcnative-1

and if it's still there an old version upgrade it with:

sudo apt-get upgrade libtcnative-1

How to change an input button image using CSS?

A variation on the previous answers. I found that opacity needs to be set, of course this will work in IE6 and on. There was a problem with the line-height solution in IE8 where the button would not respond. And with this you get a hand cursor as well!

<div id="myButton">
  <input id="myInputButton" type="submit" name="" value="">
</div>

#myButton {
 background: url("form_send_button.gif") no-repeat;
 width: 62px;
 height: 24px;
 }

#myInputButton { 
 background: url("form_send_button.gif") no-repeat;
 opacity: 0;
 -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
 filter: alpha(opacity=0);
 width: 67px;
 height: 26px;
 cursor: pointer;
 cursor: hand;
}

Using Exit button to close a winform program

If you only want to Close the form than you can use this.Close(); else if you want the whole application to be closed use Application.Exit();

HTTP Error 401.2 - Unauthorized You are not authorized to view this page due to invalid authentication headers

Make sure Anonymous access is enabled on IIS -> Authentication.

But also right click on it, then click on Edit, and choose a domain\username and password. (With access to the physical folder of the application).

How to open an existing project in Eclipse?

I also have just faced with this problem that how to open existing file. And none of answers was helpful. That's why I tried by myself.

Direction: File -> Open file -> Workspace (with you had chosen first in creating your project) -> Package (which you already created your project in) -> src (source file) -> Created package ->

And now your searching project's nodepad format. I hope it would be helpful. If any mistake here, sorry beforehand.

Set up git to pull and push all branches

To see all the branches with out using git branch -a you should execute:

for remote in `git branch -r`; do git branch --track $remote; done
git fetch --all
git pull --all

Now you can see all the branches:

git branch

To push all the branches try:

git push --all

Definitive way to trigger keypress events with jQuery

If you want to trigger the keypress or keydown event then all you have to do is:

var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
$("input").trigger(e);

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Select all columns except one in MySQL?

I agree that it isn't sufficient to Select *, if that one you don't need, as mentioned elsewhere, is a BLOB, you don't want to have that overhead creep in.

I would create a view with the required data, then you can Select * in comfort --if the database software supports them. Else, put the huge data in another table.

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

How to set an HTTP proxy in Python 2.7?

For installing pip with get-pip.py behind a proxy I went with the steps below. My server was even behind a jump server.

From the jump server:

ssh -R 18080:proxy-server:8080 my-python-server

On the "python-server"

export https_proxy=https://localhost:18080 ; export http_proxy=http://localhost:18080 ; export ftp_proxy=$http_proxy
python get-pip.py

Success.

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

You can create branch with HEAD set to one commit before merge. Then, you can do:

git merge --squash testing

This will merge, but not commit. Then:

git diff

Converting string to numeric

I suspect you are having a problem with factors. For example,

> x = factor(4:8)
> x
[1] 4 5 6 7 8
Levels: 4 5 6 7 8
> as.numeric(x)
[1] 1 2 3 4 5
> as.numeric(as.character(x))
[1] 4 5 6 7 8

Some comments:

  • You mention that your vector contains the characters "Down" and "NoData". What do expect/want as.numeric to do with these values?
  • In read.csv, try using the argument stringsAsFactors=FALSE
  • Are you sure it's sep="/t and not sep="\t"
  • Use the command head(pitchman) to check the first fews rows of your data
  • Also, it's very tricky to guess what your problem is when you don't provide data. A minimal working example is always preferable. For example, I can't run the command pichman <- read.csv(file="picman.txt", header=TRUE, sep="/t") since I don't have access to the data set.

How to format font style and color in echo

You should also use the style 'color' and not 'font-color'

<?php

foreach($months as $key => $month){
  if(strpos($filename,$month)!==false){
        echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
    }
}

?>

In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.

Check if multiple strings exist in another string

It depends on the context suppose if you want to check single literal like(any single word a,e,w,..etc) in is enough

original_word ="hackerearcth"
for 'h' in original_word:
      print("YES")

if you want to check any of the character among the original_word: make use of

if any(your_required in yourinput for your_required in original_word ):

if you want all the input you want in that original_word,make use of all simple

original_word = ['h', 'a', 'c', 'k', 'e', 'r', 'e', 'a', 'r', 't', 'h']
yourinput = str(input()).lower()
if all(requested_word in yourinput for requested_word in original_word):
    print("yes")

How to create a QR code reader in a HTML5 website?

There aren't many JavaScript decoders.

There is one at http://www.webqr.com/index.html

The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

I think the best and cleanest solution you can imagine is this:

@Component( {
  selector: 'app-my-component',
  template: `<p>{{ myData?.anyfield }}</p>`,
  styles: [ '' ]
} )
export class MyComponent implements OnInit {
  private myData;

  constructor( private myService: MyService ) { }

  ngOnInit( ) {
    /* 
      async .. await 
      clears the ExpressionChangedAfterItHasBeenCheckedError exception.
    */
    this.myService.myObservable.subscribe(
      async (data) => { this.myData = await data }
    );
  }
}

Tested with Angular 5.2.9

Java time-based map/cache with expiring keys

If anybody needs a simple thing, following is a simple key-expiring set. It might be converted to a map easily.

public class CacheSet<K> {
    public static final int TIME_OUT = 86400 * 1000;

    LinkedHashMap<K, Hit> linkedHashMap = new LinkedHashMap<K, Hit>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, Hit> eldest) {
            final long time = System.currentTimeMillis();
            if( time - eldest.getValue().time > TIME_OUT) {
                Iterator<Hit> i = values().iterator();

                i.next();
                do {
                    i.remove();
                } while( i.hasNext() && time - i.next().time > TIME_OUT );
            }
            return false;
        }
    };


    public boolean putIfNotExists(K key) {
        Hit value = linkedHashMap.get(key);
        if( value != null ) {
            return false;
        }

        linkedHashMap.put(key, new Hit());
        return true;
    }

    private static class Hit {
        final long time;


        Hit() {
            this.time = System.currentTimeMillis();
        }
    }
}

Keeping session alive with Curl and PHP

Yup, often called a 'cookie jar' Google should provide many examples:

http://devzone.zend.com/16/php-101-part-10-a-session-in-the-cookie-jar/

http://curl.haxx.se/libcurl/php/examples/cookiejar.html <- good example IMHO

Copying that last one here so it does not go away...

Login to on one page and then get another page passing all cookies from the first page along Written by Mitchell

<?php
/*
This script is an example of using curl in php to log into on one page and 
then get another page passing all cookies from the first page along with you.
If this script was a bit more advanced it might trick the server into 
thinking its netscape and even pass a fake referer, yo look like it surfed 
from a local page.
*/

$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/checkpwd.asp");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "UserID=username&password=passwd");

ob_start();      // prevent any output
curl_exec ($ch); // execute the curl command
ob_end_clean();  // stop preventing output

curl_close ($ch);
unset($ch);

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_COOKIEFILE, "/tmp/cookieFileName");
curl_setopt($ch, CURLOPT_URL,"http://www.myterminal.com/list.asp");

$buf2 = curl_exec ($ch);

curl_close ($ch);

echo "<PRE>".htmlentities($buf2);
?>  

How to print out more than 20 items (documents) in MongoDB's shell?

Could always do:

db.foo.find().forEach(function(f){print(tojson(f, '', true));});

To get that compact view.

Also, I find it very useful to limit the fields returned by the find so:

db.foo.find({},{name:1}).forEach(function(f){print(tojson(f, '', true));});

which would return only the _id and name field from foo.

How to delete row in gridview using rowdeleting event?

I know this is a late answer but still it would help someone in need of a solution. I recommend to use OnRowCommand for delete operation along with DataKeyNames, keep OnRowDeleting function to avoid exception.

<asp:gridview ID="Gridview1" runat="server" ShowFooter="true" 
     AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting" OnRowCommand="Gridview1_RowCommand" DataKeyNames="ID">

Include DataKeyNames="ID" in the gridView and specify the same in link button.

<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("ID")%>'>Delete</asp:LinkButton>

protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Delete")
    {
      int ID = Convert.ToInt32(e.CommandArgument);
      //now perform the delete operation using ID value
    }
}

protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)    
{
//Leave it blank
}

If this is helpful, give me +

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.


Just for completeness:

x += y is not always doing an in-place operation, there are (at least) three exceptions:

  • If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int.

  • If __iadd__ returns NotImplemented, Python falls back to x = x + y.

  • The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.

As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.

You can read more on this in the Python documentation of "Emulating Numeric Types".

These [__i*__] methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. In certain situations, augmented assignment can result in unexpected errors (see Why does a_tuple[i] += ["item"] raise an exception when the addition works?), but this behavior is in fact part of the data model.

HTTP test server accepting GET/POST requests

nc one-liner local test server

Setup a local test server in one line under Linux:

nc -kdl localhost 8000

Sample request maker on another shell:

wget http://localhost:8000

then on the first shell you see the request that was made appear:

GET / HTTP/1.1
User-Agent: Wget/1.19.4 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Host: localhost:8000
Connection: Keep-Alive

nc from the netcat-openbsd package is widely available and pre-installed on Ubuntu.

Tested on Ubuntu 18.04.

Removing duplicate rows in Notepad++

If you don't care about row order (which I don't think you do), then you can use a Linux/FreeBSD/Mac OS X/Cygwin box and do:

$ cat yourfile | sort | uniq > yourfile_nodups

Then open the file again in Notepad++.

How to convert an array of strings to an array of floats in numpy?

If you have (or create) a single string, you can use np.fromstring:

import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )

Note, x = ','.join(x) transforms the x array to string '1.1, 2.2, 3.2'. If you read a line from a txt file, each line will be already a string.

Android read text raw resource file

Here goes mix of weekens's and Vovodroid's solutions.

It is more correct than Vovodroid's solution and more complete than weekens's solution.

    try {
        InputStream inputStream = res.openRawResource(resId);
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            try {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                return result.toString();
            } finally {
                reader.close();
            }
        } finally {
            inputStream.close();
        }
    } catch (IOException e) {
        // process exception
    }

RS256 vs HS256: What's the difference?

In cryptography there are two types of algorithms used:

Symmetric algorithms

A single key is used to encrypt data. When encrypted with the key, the data can be decrypted using the same key. If, for example, Mary encrypts a message using the key "my-secret" and sends it to John, he will be able to decrypt the message correctly with the same key "my-secret".

Asymmetric algorithms

Two keys are used to encrypt and decrypt messages. While one key(public) is used to encrypt the message, the other key(private) can only be used to decrypt it. So, John can generate both public and private keys, then send only the public key to Mary to encrypt her message. The message can only be decrypted using the private key.

HS256 and RS256 Scenario

These algorithms are NOT used to encrypt/decryt data. Rather they are used to verify the origin or the authenticity of the data. When Mary needs to send an open message to Jhon and he needs to verify that the message is surely from Mary, HS256 or RS256 can be used.

HS256 can create a signature for a given sample of data using a single key. When the message is transmitted along with the signature, the receiving party can use the same key to verify that the signature matches the message.

RS256 uses pair of keys to do the same. A signature can only be generated using the private key. And the public key has to be used to verify the signature. In this scenario, even if Jack finds the public key, he cannot create a spoof message with a signature to impersonate Mary.

How to compute the sum and average of elements in an array?

If you are in need of the average and can skip the requirement of calculating the sum, you can compute the average with a single call of reduce:

// Assumes an array with only values that can be parsed to a Float
var reducer = function(cumulativeAverage, currentValue, currentIndex) {
  // 1. multiply average by currentIndex to find cumulative sum of previous elements
  // 2. add currentValue to get cumulative sum, including current element
  // 3. divide by total number of elements, including current element (zero-based index + 1)
  return (cumulativeAverage * currentIndex + parseFloat(currentValue))/(currentIndex + 1)
}
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(reducer, 0)); // => 5.5
console.log([].reduce(reducer, 0)); // => 0
console.log([0].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0
console.log([,,,].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0

Default SecurityProtocol in .NET 4.5

Create a text file with a .reg extension and the following contents:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

Or download it from the following source:

https://tls1test.salesforce.com/s/NET40-Enable-TLS-1_2.reg

Double-click to install...

How to set the locale inside a Debian/Ubuntu Docker container?

Specify the LANG and LC_ALL environment variables using -e when running your command:

docker run -e LANG=C.UTF-8 -e LC_ALL=C.UTF-8 -it --rm <yourimage> <yourcommand>

It's not necessary to modify the Dockerfile.

Best way to check if object exists in Entity Framework?

If you don't want to execute SQL directly, the best way is to use Any(). This is because Any() will return as soon as it finds a match. Another option is Count(), but this might need to check every row before returning.

Here's an example of how to use it:

if (context.MyEntity.Any(o => o.Id == idToMatch))
{
    // Match!
}

And in vb.net

If context.MyEntity.Any(function(o) o.Id = idToMatch) Then
    ' Match!
End If

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

How to make div follow scrolling smoothly with jQuery?

There's a fantastic jQuery tutorial for this at https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/.

It replicates the Apple.com shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".

CSS - display: none; not working

Another trick is to use

.class {
position: absolute;
visibility:hidden;
display:none;
}

This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none works later on it will be working. Keep in mind that visibility:hidden may not remove it from screen readers.

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

This Example Code will Help you out!

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Solution {
    public static void main(String[] args) {
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("a", 10);
        map.put("b", 30);
        map.put("c", 50);
        map.put("d", 40);
        map.put("e", 20);
        System.out.println(map);

        Map sortedMap = sortByValue(map);
        System.out.println(sortedMap);
    }

    public static Map sortByValue(Map unsortedMap) {
        Map sortedMap = new TreeMap(new ValueComparator(unsortedMap));
        sortedMap.putAll(unsortedMap);
        return sortedMap;
    }

}

class ValueComparator implements Comparator {
    Map map;

    public ValueComparator(Map map) {
        this.map = map;
    }

    public int compare(Object keyA, Object keyB) {
        Comparable valueA = (Comparable) map.get(keyA);
        Comparable valueB = (Comparable) map.get(keyB);
        return valueB.compareTo(valueA);
    }
}

How to change a particular element of a C++ STL vector

Even though @JamesMcNellis answer is a valid one I would like to explain something about error handling and also the fact that there is another way of doing what you want.

You have four ways of accessing a specific item in a vector:

  • Using the [] operator
  • Using the member function at(...)
  • Using an iterator in combination with a given offset
  • Using std::for_each from the algorithm header of the standard C++ library. This is another way which I can recommend (it uses internally an iterator). You can read more about it for example here.

In the following examples I will be using the following vector as a lab rat and explaining the first three methods:

static const int arr[] = {1, 2, 3, 4};
std::vector<int> v(arr, arr+sizeof(arr)/sizeof(arr[0]));

This creates a vector as seen below:

1 2 3 4

First let's look at the [] way of doing things. It works in pretty much the same way as you expect when working with a normal array. You give an index and possibly you access the item you want. I say possibly because the [] operator doesn't check whether the vector actually has that many items. This leads to a silent invalid memory access. Example:

v[10] = 9;

This may or may not lead to an instant crash. Worst case is of course is if it doesn't and you actually get what seems to be a valid value. Similar to arrays this may lead to wasted time in trying to find the reason why for example 1000 lines of code later you get a value of 100 instead of 234, which is somewhat connected to that very location where you retrieve an item from you vector.

A much better way is to use at(...). This will automatically check for out of bounds behaviour and break throwing an std::out_of_range. So in the case when we have

v.at(10) = 9;

We will get:

terminate called after throwing an instance of 'std::out_of_range'
what(): vector::_M_range_check: __n (which is 10) >= this->size() (which is 4)

The third way is similar to the [] operator in the sense you can screw things up. A vector just like an array is a sequence of continuous memory blocks containing data of the same type. This means that you can use your starting address by assigning it to an iterator and then just add an offset to this iterator. The offset simply stands for how many items after the first item you want to traverse:

std::vector<int>::iterator it = v.begin(); // First element of your vector
*(it+0) = 9;  // offest = 0 basically means accessing v.begin()
// Now we have 9 2 3 4 instead of 1 2 3 4
*(it+1) = -1; // offset = 1 means first item of v plus an additional one
// Now we have 9 -1 3 4 instead of 9 2 3 4
// ...

As you can see we can also do

*(it+10) = 9;

which is again an invalid memory access. This is basically the same as using at(0 + offset) but without the out of bounds error checking.

I would advice using at(...) whenever possible not only because it's more readable compared to the iterator access but because of the error checking for invalid index that I have mentioned above for both the iterator with offset combination and the [] operator.

React Error: Target Container is not a DOM Element

Also make sure id set in index.html is same as the one you referring to in index.js

index.html:

<body> 
    <div id="root"></div>
    <script src="/bundle.js"></script>
</body>

index.js:

ReactDOM.render(<App/>,document.getElementById('root'));

Loading custom configuration files

the articles posted by Ricky are very good, but unfortunately they don't answer your question.

To solve your problem you should try this piece of code:

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

If need to access a value within the config you can use the index operator:

config.AppSettings.Settings["test"].Value;

Razor Views not seeing System.Web.Mvc.HtmlHelper

Update for Visual Studio 2017 Users:

If you have just migrated to Visual Studio 2017 and your project is MVC4, make sure you go back into the VS2017 Installer and check the MVC4 option under the "ASP.NET and web development" section. It is an optional component and not checked by default.

This solved my issue

How to import an Excel file into SQL Server?

There are many articles about writing code to import an excel file, but this is a manual/shortcut version:

If you don't need to import your Excel file programmatically using code you can do it very quickly using the menu in SQL Management Studio.

The quickest way to get your Excel file into SQL is by using the import wizard:

  1. Open SSMS (Sql Server Management Studio) and connect to the database where you want to import your file into.
  2. Import Data: in SSMS in Object Explorer under 'Databases' right-click the destination database, select Tasks, Import Data. An import wizard will pop up (you can usually just click 'Next' on the first screen).

enter image description here

  1. The next window is 'Choose a Data Source', select Excel:

    • In the 'Data Source' dropdown list select Microsoft Excel (this option should appear automatically if you have excel installed).

    • Click the 'Browse' button to select the path to the Excel file you want to import.

    • Select the version of the excel file (97-2003 is usually fine for files with a .XLS extension, or use 2007 for newer files with a .XLSX extension)
    • Tick the 'First Row has headers' checkbox if your excel file contains headers.
    • Click next.

enter image description here

  1. On the 'Choose a Destination' screen, select destination database:
    • Select the 'Server name', Authentication (typically your sql username & password) and select a Database as destination. Click Next.

enter image description here

  1. On the 'Specify Table Copy or Query' window:

    • For simplicity just select 'Copy data from one or more tables or views', click Next.
  2. 'Select Source Tables:' choose the worksheet(s) from your Excel file and specify a destination table for each worksheet. If you don't have a table yet the wizard will very kindly create a new table that matches all the columns from your spreadsheet. Click Next.

enter image description here

  1. Click Finish.

How can I handle the warning of file_get_contents() function in PHP?

You could use this script

$url = @file_get_contents("http://www.itreb.info");
if ($url) {
    // if url is true execute this 
    echo $url;
} else {
    // if not exceute this 
    echo "connection error";
}

Function stoi not declared

I managed to fix this problem by adding the following lines to my CMakeLists.txt:

set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS}  -Wall  -O3 -march=native ")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall   -O3 -march=native")

# Check C++11 or C++0x support
include(CheckCXXCompilerFlag)
CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11)
CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X)
if(COMPILER_SUPPORTS_CXX11)
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
   add_definitions(-DCOMPILEDWITHC11)
   message(STATUS "Using flag -std=c++11.")
elseif(COMPILER_SUPPORTS_CXX0X)
   set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x")
   add_definitions(-DCOMPILEDWITHC0X)
   message(STATUS "Using flag -std=c++0x.")
else()
   message(FATAL_ERROR "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.")
endif()

As mentioned by the other fellows, that is the -std=c++11 issue.

How to avoid .pyc files?

I have several test cases in a test suite and before I was running the test suite in the Mac Terminal like this:

python LoginSuite.py

Running the command this way my directory was being populated with .pyc files. I tried the below stated method and it solved the issue:

python -B LoginSuite.py

This method works if you are importing test cases into the test suite and running the suite on the command line.

Oracle: how to INSERT if a row doesn't exist

Assuming you are on 10g, you can also use the MERGE statement. This allows you to insert the row if it doesn't exist and ignore the row if it does exist. People tend to think of MERGE when they want to do an "upsert" (INSERT if the row doesn't exist and UPDATE if the row does exist) but the UPDATE part is optional now so it can also be used here.

SQL> create table foo (
  2    name varchar2(10) primary key,
  3    age  number
  4  );

Table created.

SQL> ed
Wrote file afiedt.buf

  1  merge into foo a
  2    using (select 'johnny' name, null age from dual) b
  3       on (a.name = b.name)
  4   when not matched then
  5    insert( name, age)
  6*    values( b.name, b.age)
SQL> /

1 row merged.

SQL> /

0 rows merged.

SQL> select * from foo;

NAME              AGE
---------- ----------
johnny

Can I extend a class using more than 1 class in PHP?

I have read several articles discouraging inheritance in projects (as opposed to libraries/frameworks), and encouraging to program agaisnt interfaces, no against implementations.
They also advocate OO by composition: if you need the functions in class a and b, make c having members/fields of this type:

class C
{
    private $a, $b;

    public function __construct($x, $y)
    {
        $this->a = new A(42, $x);
        $this->b = new B($y);
    }

    protected function DoSomething()
    {
        $this->a->Act();
        $this->b->Do();
    }
}

HTTP POST with URL query parameters -- good idea or not?

I agree - it's probably safer to use a GET request if you're just passing data in the URL and not in the body. See this similar question for some additional views on the whole POST+GET concept.

Calculating difference between two timestamps in Oracle in milliseconds

I know that this has been exhaustively answered, but I wanted to share my FUNCTION with everyone. It gives you the option to choose if you want your answer to be in days, hours, minutes, seconds, or milliseconds. You can modify it to fit your needs.

CREATE OR REPLACE FUNCTION Return_Elapsed_Time (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
    FUNCTION Core (start_ IN TIMESTAMP, end_ IN TIMESTAMP DEFAULT SYSTIMESTAMP, syntax_ IN NUMBER DEFAULT NULL) RETURN VARCHAR2 IS
        day_ VARCHAR2(7); /* This means this FUNCTION only supports up to 99 days */
        hour_ VARCHAR2(9); /* This means this FUNCTION only supports up to 999 hours, which is over 41 days */
        minute_ VARCHAR2(12); /* This means this FUNCTION only supports up to 9999 minutes, which is over 17 days */
        second_ VARCHAR2(18); /* This means this FUNCTION only supports up to 999999 seconds, which is over 11 days */
        msecond_ VARCHAR2(22); /* This means this FUNCTION only supports up to 999999999 milliseconds, which is over 11 days */
        d1_ NUMBER;
        h1_ NUMBER;
        m1_ NUMBER;
        s1_ NUMBER;
        ms_ NUMBER;
        /* If you choose 1, you only get seconds. If you choose 2, you get minutes and seconds etc. */
        precision_ NUMBER; /* 0 => milliseconds; 1 => seconds; 2 => minutes; 3 => hours; 4 => days */
        format_ VARCHAR2(2) := ', ';
        return_ VARCHAR2(50);
    BEGIN
        IF (syntax_ IS NULL) THEN
            precision_ := 0;
        ELSE
            IF (syntax_ = 0) THEN
                precision_ := 0;
            ELSIF (syntax_ = 1) THEN
                precision_ := 1;
            ELSIF (syntax_ = 2) THEN
                precision_ := 2;
            ELSIF (syntax_ = 3) THEN
                precision_ := 3;
            ELSIF (syntax_ = 4) THEN
                precision_ := 4;
            ELSE 
                precision_ := 0;
            END IF;
        END IF;
        SELECT EXTRACT(DAY FROM (end_ - start_)) INTO d1_ FROM DUAL;
        SELECT EXTRACT(HOUR FROM (end_ - start_)) INTO h1_ FROM DUAL;
        SELECT EXTRACT(MINUTE FROM (end_ - start_)) INTO m1_ FROM DUAL;
        SELECT EXTRACT(SECOND FROM (end_ - start_)) INTO s1_ FROM DUAL;
        IF (precision_ = 4) THEN
            IF (d1_ = 1) THEN
                day_ := ' day';
            ELSE
                day_ := ' days';
            END IF;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := d1_ || day_ || format_ || h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 3) THEN
            h1_ := (d1_ * 24) + h1_;
            IF (h1_ = 1) THEN
                hour_ := ' hour';
            ELSE
                hour_ := ' hours';
            END IF;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := h1_ || hour_ || format_ || m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 2) THEN
            m1_ := (((d1_ * 24) + h1_) * 60) + m1_;
            IF (m1_ = 1) THEN
                minute_ := ' minute';
            ELSE
                minute_ := ' minutes';
            END IF;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := m1_ || minute_ || format_ || s1_ || second_;
            RETURN return_;
        ELSIF (precision_ = 1) THEN
            s1_ := (((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_;
            IF (s1_ = 1) THEN
                second_ := ' second';
            ELSE
                second_ := ' seconds';
            END IF;
            return_ := s1_ || second_;
            RETURN return_;
        ELSE
            ms_ := ((((((d1_ * 24) + h1_) * 60) + m1_) * 60) + s1_) * 1000;
            IF (ms_ = 1) THEN
                msecond_ := ' millisecond';
            ELSE
                msecond_ := ' milliseconds';
            END IF;
            return_ := ms_ || msecond_;
            RETURN return_;
        END IF;
    END Core;
BEGIN
    RETURN(Core(start_, end_, syntax_));
END Return_Elapsed_Time;

For example, if I called this function right now (12.10.2018 11:17:00.00) using Return_Elapsed_Time(TO_TIMESTAMP('12.04.2017 12:00:00.00', 'DD.MM.YYYY HH24:MI:SS.FF'),SYSTIMESTAMP), it should return something like:

47344620000 milliseconds

Is it possible to pass parameters programmatically in a Microsoft Access update query?

You can also use TempVars - note '!' syntax is essential You can also use TempVars - note '!' syntax is essential

How to run function in AngularJS controller on document ready?

Angular has several timepoints to start executing functions. If you seek for something like jQuery's

$(document).ready();

You may find this analog in angular to be very useful:

$scope.$watch('$viewContentLoaded', function(){
    //do something
});

This one is helpful when you want to manipulate the DOM elements. It will start executing only after all te elements are loaded.

UPD: What is said above works when you want to change css properties. However, sometimes it doesn't work when you want to measure the element properties, such as width, height, etc. In this case you may want to try this:

$scope.$watch('$viewContentLoaded', 
    function() { 
        $timeout(function() {
            //do something
        },0);    
});

Replace non-numeric with empty string

I'm sure there's a more efficient way to do it, but I would probably do this:

string getTenDigitNumber(string input)
{    
    StringBuilder sb = new StringBuilder();
    for(int i - 0; i < input.Length; i++)
    {
        int junk;
        if(int.TryParse(input[i], ref junk))
            sb.Append(input[i]);
    }
    return sb.ToString();
}

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

I was moving data directory on a cloned server and having troubles to login as postgres. Resetting postgres password like this worked for me.

root# su postgres
postgres$ psql -U postgres
psql (9.3.6) 
Type "help" for help. 
postgres=#\password 
Enter new password: 
Enter it again: 
postgres=#

Using media breakpoints in Bootstrap 4-alpha

I answered a similar question here

As @Syden said, the mixins will work. Another option is using SASS map-get like this..

@media (min-width: map-get($grid-breakpoints, sm)){
  .something {
    padding: 10px;
   }
}

@media (min-width: map-get($grid-breakpoints, md)){
  .something {
    padding: 20px;
   }
}

http://www.codeply.com/go/0TU586QNlV


Bootstrap 4 Breakpoints demo

UIView touch event in controller

Updating @Chackle's answer for Swift 2.x:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.locationInView(self)
        // do something with your currentPoint
    }
}