Programs & Examples On #Opengl 3

OpenGL 3.0 is, after OpenGL 2.0, the second major release of OpenGL which, apart from some convenience updates, supports and requires a significantly advanced hardware generation (geometry shaders and instancing). Further, OpenGL 3.0 introduced a deprecation model which was meant to gradually eleminate the use of non-contemporary features that do not map well to current hardware, but without breaking existing application compatibility.

jQuery click / toggle between two functions

Use a couple of functions and a boolean. Here's a pattern, not full code:

 var state = false,
     oddONes = function () {...},
     evenOnes = function() {...};

 $("#time").click(function(){
     if(!state){
        evenOnes();
     } else {
        oddOnes();
     }
     state = !state;
  });

Or

  var cases[] = {
      function evenOnes(){...},  // these could even be anonymous functions
      function oddOnes(){...}    // function(){...}
  };

  var idx = 0; // should always be 0 or 1

  $("#time").click(function(idx){cases[idx = ((idx+1)%2)]()}); // corrected

(Note the second is off the top of my head and I mix languages a lot, so the exact syntax isn't guaranteed. Should be close to real Javascript through.)

How to sum up elements of a C++ vector?

Why perform the summation forwards when you can do it backwards? Given:

std::vector<int> v;     // vector to be summed
int sum_of_elements(0); // result of the summation

We can use subscripting, counting backwards:

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v[i-1];

We can use range-checked "subscripting," counting backwards (just in case):

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v.at(i-1);

We can use reverse iterators in a for loop:

for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
    sum_of_elements += *i;

We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):

for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
    sum_of_elements += *(i - 1);

We can use accumulate with reverse iterators:

sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);

We can use for_each with a lambda expression using reverse iterators:

std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });

So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.

How to return value from function which has Observable subscription inside?

In the single-threaded,asynchronous,promise-oriented,reactive-trending world of javascript async/await is the imperative-style programmer's best friend:

(async()=>{

    const store = of("someValue");
    function getValueFromObservable () {
        return store.toPromise();
    }
    console.log(await getValueFromObservable())

})();

And in case store is a sequence of multiple values:

  const aiFrom = require('ix/asynciterable').from;
  (async function() {

     const store = from(["someValue","someOtherValue"]);
     function getValuesFromObservable () {
        return aiFrom(store);
     }
     for await (let num of getValuesFromObservable()) {
       console.log(num);
     }
  })();

How do I set default terminal to terminator?

change Settings Manager >> Preferred Applications >> Utilities

Get yesterday's date using Date

changed from your code :

private String toDate(long timestamp) {
    Date date = new Date (timestamp * 1000 -  24 * 60 * 60 * 1000);
   return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();

}

but you do better using calendar.

Fatal error: Call to undefined function mb_strlen()

For me, this worked in Ubuntu 14.04 and for php5.6:

$ sudo apt-get install php5.6-mbstring

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *. Also, the map method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply is used for.

So, if you must use the above approach, I would write it like this

df["A1"], df["A2"] = zip(*df["a"].apply(calculate))

There's actually no reason to use zip here. You can simply do this:

df["A1"], df["A2"] = calculate(df['a'])

This second method is also much faster on larger DataFrames

df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})

DataFrame created with 300,000 rows

%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60x faster than zip


In general, avoid using apply

Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above

%%timeit
A1, A2 = [], []
for val in df['a']:
    A1.append(val**2)
    A2.append(val**3)

df['A1'] = A1
df['A2'] = A2

298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:

%load_ext cython

%%cython
cpdef power(vals):
    A1, A2 = [], []
    cdef double val
    for val in vals:
        A1.append(val**2)
        A2.append(val**3)

    return A1, A2

%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Directly assigning without apply

You can get even greater speed improvements if you use the direct vectorized operations.

%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.


The simplest speed test with apply

The above example should clearly show how slow apply can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply

s = pd.Series(np.random.rand(10000000))

%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Without apply is 50x faster

%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to interpret "loss" and "accuracy" for a machine learning model

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

Opening port 80 EC2 Amazon web services

Some quick tips:

  1. Disable the inbuilt firewall on your Windows instances.
  2. Use the IP address rather than the DNS entry.
  3. Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
  4. Check that you can actually ping your server. This may also necessitate some Security Group modification.

Renaming column names of a DataFrame in Spark Scala

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

Setting the filter to an OpenFileDialog to allow the typical image formats?

Here's an example of the ImageCodecInfo suggestion (in VB):

   Imports System.Drawing.Imaging
        ...            

        Dim ofd as new OpenFileDialog()
        ofd.Filter = ""
        Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
        Dim sep As String = String.Empty
        For Each c As ImageCodecInfo In codecs
            Dim codecName As String = c.CodecName.Substring(8).Replace("Codec", "Files").Trim()
            ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, codecName, c.FilenameExtension)
            sep = "|"
        Next
        ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, "All Files", "*.*")

And it looks like this:

enter image description here

View's SELECT contains a subquery in the FROM clause

Looks to me as MySQL 3.6 gives the following error while MySQL 3.7 no longer errors out. I am yet to find anything in the documentation regarding this fix.

Decompile an APK, modify it and then recompile it

I know this question is answered still, I would like to pass an information how to get source code from apk with out dexjar.

There is an online decompiler for android apks

  1. Upload apk from local machine
  2. Wait some moments
  3. Download source code in zip format

I don't know how reliable is this.

@darkheir Answer is the manual way to do decompile apk. It helps us to understand different phases in Apk creation.

Once you have source code , follow the step mentioned in the accepted answer

Report so many ads on this links Another online Apk De-compiler @Andrew Rukin : http://www.javadecompilers.com/apk

Still worth. Hats Off to creators.

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

CSS3 has a pseudo-class called :not()

_x000D_
_x000D_
input:not([type='checkbox']) {    
    visibility: hidden;
}
_x000D_
<p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
                                      
<ul>
  <li>text: (<input type="text">)</li>  
  <li>password (<input type="password">)</li>       
  <li>checkbox (<input type="checkbox">)</li> 
 </ul>
_x000D_
_x000D_
_x000D_


Multiple selectors

As Vincent mentioned, it's possible to string multiple :not()s together:

input:not([type='checkbox']):not([type='submit'])

CSS4, which is supported in many of the latest browser releases, allows multiple selectors in a :not()

input:not([type='checkbox'],[type='submit'])

Legacy support

All modern browsers support the CSS3 syntax. At the time this question was asked, we needed a fall-back for IE7 and IE8. One option was to use a polyfill like IE9.js. Another was to exploit the cascade in CSS:

input {
   // styles for most inputs
}   

input[type=checkbox] {
  // revert back to the original style
} 

input.checkbox {
  // for completeness, this would have worked even in IE3!
} 

How to programmatically empty browser cache?

location.reload(true); will hard reload the current page, ignoring the cache.
Cache.delete() can also be used for new chrome, firefox and opera.

undefined reference to `std::ios_base::Init::Init()'

You can resolve this in several ways:

  • Use g++ in stead of gcc: g++ -g -o MatSim MatSim.cpp
  • Add -lstdc++: gcc -g -o MatSim MatSim.cpp -lstdc++
  • Replace <string.h> by <string>

This is a linker problem, not a compiler issue. The same problem is covered in the question iostream linker error – it explains what is going on.

C# equivalent of C++ map<string,double>

Roughly:-

var accounts = new Dictionary<string, double>();

// Initialise to zero...

accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;

// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);

Adding onClick event dynamically using jQuery

Try below approach,

$('#bfCaptchaEntry').on('click', myfunction);

or in case jQuery is not an absolute necessaity then try below,

document.getElementById('bfCaptchaEntry').onclick = myfunction;

However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...

Read more on this post https://stackoverflow.com/a/6348597/297641

Sending files using POST with HttpURLConnection

The solution of Jaydipsinh Zala didn't work for me, I don't know why but it seems to be close to the solution.

So merging this one with the great solution and explanation of Mihai Todor, the result is this class that currently works for me. If it helps someone:

MultipartUtility2V.java

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

public class MultipartUtilityV2 {
    private HttpURLConnection httpConn;
    private DataOutputStream request;
    private final String boundary =  "*****";
    private final String crlf = "\r\n";
    private final String twoHyphens = "--";

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @throws IOException
     */
    public MultipartUtilityV2(String requestURL)
            throws IOException {

        // creates a unique boundary based on time stamp
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);

        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Cache-Control", "no-cache");
        httpConn.setRequestProperty(
                "Content-Type", "multipart/form-data;boundary=" + this.boundary);

        request =  new DataOutputStream(httpConn.getOutputStream());
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value)throws IOException  {
        request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ this.crlf);
        request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.crlf);
        request.writeBytes(this.crlf);
        request.writeBytes(value+ this.crlf);
        request.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile)
            throws IOException {
        String fileName = uploadFile.getName();
        request.writeBytes(this.twoHyphens + this.boundary + this.crlf);
        request.writeBytes("Content-Disposition: form-data; name=\"" +
                fieldName + "\";filename=\"" +
                fileName + "\"" + this.crlf);
        request.writeBytes(this.crlf);

        byte[] bytes = Files.readAllBytes(uploadFile.toPath());
        request.write(bytes);
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        String response ="";

        request.writeBytes(this.crlf);
        request.writeBytes(this.twoHyphens + this.boundary +
                this.twoHyphens + this.crlf);

        request.flush();
        request.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream responseStream = new
                    BufferedInputStream(httpConn.getInputStream());

            BufferedReader responseStreamReader =
                    new BufferedReader(new InputStreamReader(responseStream));

            String line = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = responseStreamReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            responseStreamReader.close();

            response = stringBuilder.toString();
            httpConn.disconnect();
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

message box in jquery

If you don't wont use jquery.ui(that is highly recommended), you can take a look at Block.UI plugin.

Entity Framework vs LINQ to SQL

I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.

This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.

Typescript export vs. default export

Default Export (export default)

// MyClass.ts -- using default export
export default class MyClass { /* ... */ }

The main difference is that you can only have one default export per file and you import it like so:

import MyClass from "./MyClass";

You can give it any name you like. For example this works fine:

import MyClassAlias from "./MyClass";

Named Export (export)

// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }

When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:

import { MyClass } from "./MyClass";

Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.

Or say your file exported multiple classes, then you could import both like so:

import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass

Or you could give either of them a different name in this file:

import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias

Or you could import everything that's exported by using * as:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here

Which to use?

In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.

It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.

Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.

That said, find what you prefer! You could use one, the other, or both at the same time.

Additional Points

A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:

import { default as MyClass } from "./MyClass";

And take note these other ways to import exist: 

import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

How to write a confusion matrix in Python?

Scikit-learn (which I recommend using anyways) has it included in the metrics module:

>>> from sklearn.metrics import confusion_matrix
>>> y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2]
>>> y_pred = [0, 0, 0, 0, 1, 1, 0, 2, 2]
>>> confusion_matrix(y_true, y_pred)
array([[3, 0, 0],
       [1, 1, 1],
       [1, 1, 1]])

Why does integer division in C# return an integer and not a float?

It's just a basic operation.

Remember when you learned to divide. In the beginning we solved 9/6 = 1 with remainder 3.

9 / 6 == 1  //true
9 % 6 == 3 // true

The /-operator in combination with the %-operator are used to retrieve those values.

Why is this rsync connection unexpectedly closed on Windows?

i get the solution. i've using cygwin and this is the problem the rsync command for Windows work only in windows shell and works in the windows powershell.

A few times it has happened the same error between two linux boxes. and appears to be by incompatible versions of rsync

How do I check form validity with angularjs?

form

  • directive in module ng Directive that instantiates FormController.

If the name attribute is specified, the form controller is published onto the current scope under this name.

Alias: ngForm

In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of elements, so Angular provides the ngForm directive which behaves identically to but can be nested. This allows you to have nested forms, which is very useful when using Angular validation directives in forms that are dynamically generated using the ngRepeat directive. Since you cannot dynamically generate the name attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an ngForm directive and nest these in an outer form element.

CSS classes

ng-valid is set if the form is valid.

ng-invalid is set if the form is invalid.

ng-pristine is set if the form is pristine.

ng-dirty is set if the form is dirty.

ng-submitted is set if the form was submitted.

Keep in mind that ngAnimate can detect each of these classes when added and removed.

Submitting a form and preventing the default action

Since the role of forms in client-side Angular applications is different than in classical roundtrip apps, it is desirable for the browser not to translate the form submission into a full page reload that sends the data to the server. Instead some javascript logic should be triggered to handle the form submission in an application-specific way.

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You can use one of the following two ways to specify what javascript method should be called when a form is submitted:

ngSubmit directive on the form element

ngClick directive on the first button or input field of type submit (input[type=submit])

To prevent double execution of the handler, use only one of the ngSubmit or ngClick directives.

This is because of the following form submission rules in the HTML specification:

If a form has only one input field then hitting enter in this field triggers form submit (ngSubmit) if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter doesn't trigger submit if a form has one or more input fields and one or more buttons or input[type=submit] then hitting enter in any of the input fields will trigger the click handler on the first button or input[type=submit] (ngClick) and a submit handler on the enclosing form (ngSubmit).

Any pending ngModelOptions changes will take place immediately when an enclosing form is submitted. Note that ngClick events will occur before the model is updated.

Use ngSubmit to have access to the updated model.

app.js:

angular.module('formExample', [])
  .controller('FormController', ['$scope', function($scope) {
    $scope.userType = 'guest';
  }]);

Form:

<form name="myForm" ng-controller="FormController" class="my-form">
  userType: <input name="input" ng-model="userType" required>
  <span class="error" ng-show="myForm.input.$error.required">Required!</span>
  userType = {{userType}}
  myForm.input.$valid = {{myForm.input.$valid}}
  myForm.input.$error = {{myForm.input.$error}}
  myForm.$valid = {{myForm.$valid}}
  myForm.$error.required = {{!!myForm.$error.required}}
 </form>

Source: AngularJS: API: form

python selenium click on button

try this:

download firefox, add the plugin "firebug" and "firepath"; after install them go to your webpage, start firebug and find the xpath of the element, it unique in the page so you can't make any mistake.

See picture: instruction

browser.find_element_by_xpath('just copy and paste the Xpath').click()

Pandas get the most frequent values of a column

Simply use this..

dataframe['name'].value_counts().nlargest(n)

The functions for frequencies largest and smallest are:

  • nlargest() for mostfrequent 'n' values
  • nsmallest() for least frequent 'n' values

Failure [INSTALL_FAILED_INVALID_APK]

Just remove old APK android/app/build/outputs/apk/debug/app-debug.apk in the folder. that's all. enjoy your coding...

Checking version of angular-cli that's installed?

Simple run the following commands:

ng --version 

OR

 ng -v

Output on terminal:

      / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
            |___/


Angular CLI: 6.0.8
Node: 10.15.0
OS: linux x64 

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?

Try a software called Access to MySQL.

Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.

  • Wizard interface.
  • Transfer data directly from one server to another.
  • Create a dump file.
  • Select tables to transfer.
  • Select fields to transfer.
  • Transfer password protected databases.
  • Supports both shared security and user-level security.
  • Optional transfer of indexes.
  • Optional transfer of records.
  • Optional transfer of default values in field definitions.
  • Identifies and transfers auto number field types.
  • Command line interface.
  • Easy install, uninstall and upgrade.

See the aforementioned link for a step-by-step tutorial with screenshots.

PHP mkdir: Permission denied problem

I know this is an old thread, but it needs a better answer. You shouldn't need to set the permissions to 777, that is a security problem as it gives read and write access to the world. It may be that your apache user does not have read/write permissions on the directory.

Here's what you do in Ubuntu

  1. Make sure all files are owned by the Apache group and user. In Ubuntu it is the www-data group and user

    chown -R www-data:www-data /path/to/webserver/www

  2. Next enabled all members of the www-data group to read and write files

    chmod -R g+rw /path/to/webserver/www

The php mkdir() function should now work without returning errors

How to send a POST request using volley with string body?

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("Rest response",response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("Rest response",error.toString());
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String,String>();
            params.put("name","xyz");
            return params;
        }

        @Override
        public Map<String,String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String,String>();
            params.put("content-type","application/fesf");
            return params;
        }

    };

    requestQueue.add(stringRequest);

Can I convert long to int?

Sometimes you're not actually interested in the actual value, but in its usage as checksum/hashcode. In this case, the built-in method GetHashCode() is a good choice:

int checkSumAsInt32 = checkSumAsIn64.GetHashCode();

Marker content (infoWindow) Google Maps

We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:

Create a new function with your information for the infoWindow in it:

function addInfoWindow(marker, message) {

            var infoWindow = new google.maps.InfoWindow({
                content: message
            });

            google.maps.event.addListener(marker, 'click', function () {
                infoWindow.open(map, marker);
            });
        }

Then call the function with the array ID and the marker you want to create:

addInfoWindow(marker, hotels[i][3]);

How to make remote REST call inside Node.js? any CURL?

If you have Node.js 4.4+, take a look at reqclient, it allows you to make calls and log the requests in cURL style, so you can easily check and reproduce the calls outside the application.

Returns Promise objects instead of pass simple callbacks, so you can handle the result in a more "fashion" way, chain the result easily, and handle errors in a standard way. Also removes a lot of boilerplate configurations on each request: base URL, time out, content type format, default headers, parameters and query binding in the URL, and basic cache features.

This is an example of how to initialize it, make a call and log the operation with curl style:

var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
    baseUrl:"http://baseurl.com/api/", debugRequest:true, debugResponse:true});
client.post("client/orders", {"client": 1234, "ref_id": "A987"},{"x-token": "AFF01XX"});

This will log in the console...

[Requesting client/orders]-> -X POST http://baseurl.com/api/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json

And when the response is returned ...

[Response   client/orders]<- Status 200 - {"orderId": 1320934}

This is an example of how to handle the response with the promise object:

client.get("reports/clients")
  .then(function(response) {
    // Do something with the result
  }).catch(console.error);  // In case of error ...

Of course, it can be installed with: npm install reqclient.

C: printf a float value

You can do it like this:

printf("%.6f", myFloat);

6 represents the number of digits after the decimal separator.

How can I check if an array contains a specific value in php?

Use the in_array() function.

$array = array('kitchen', 'bedroom', 'living_room', 'dining_room');

if (in_array('kitchen', $array)) {
    echo 'this array contains kitchen';
}

how to avoid extra blank page at end while printing?

.print:last-child{
    page-break-after: avoid;
    page-break-inside: avoid;
    margin-bottom: 0px;
}

This worked for me.

How to convert datatype:object to float64 in python?

I had this problem in a DataFrame (df) created from an Excel-sheet with several internal header rows.

After cleaning out the internal header rows from df, the columns' values were of "non-null object" type (DataFrame.info()).

This code converted all numerical values of multiple columns to int64 and float64 in one go:

for i in range(0, len(df.columns)):
    df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
    # errors='ignore' lets strings remain as 'non-null objects'

If table exists drop table then create it, if it does not exist just create it

Just use DROP TABLE IF EXISTS:

DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

Try searching the MySQL documentation first if you have any other problems.

Can pandas automatically recognize dates?

Perhaps the pandas interface has changed since @Rutger answered, but in the version I'm using (0.15.2), the date_parser function receives a list of dates instead of a single value. In this case, his code should be updated like so:

dateparse = lambda dates: [pd.datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dates]

df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)

How to get DATE from DATETIME Column in SQL?

use the following

select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10),GETDATE(),111)

or the following

select sum(transaction_amount) from TransactionMaste
where Card_No = '123' and transaction_date = CONVERT(VARCHAR(10), GETDATE(), 120)

How to format a DateTime in PowerShell

A simple and nice way is:

$time = (Get-Date).ToString("yyyy:MM:dd")

Is there a Visual Basic 6 decompiler?

For the final, compiled code of your application, the short answer is “no”. Different tools are able to extract different information from the code (e.g. the forms setups) and there are P code decompilers (see Edgar's excellent link for such tools). However, up to this day, there is no decompiler for native code. I'm not aware of anything similar for other high-level languages either.

ValueError: unsupported format character while forming strings

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")


A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)

how to make twitter bootstrap submenu to open on the left side?

I have created a javascript function that looks if he has enough space on the right side. If it has he will show it on the right side, else he will display it on the left side

Tested in:

  • Firefox (mac)
  • Chorme (mac)
  • Safari (mac)

Javascript:

$(document).ready(function(){
    //little fix for the poisition.
    var newPos     = $(".fixed-menuprofile .dropdown-submenu").offset().left - $(this).width();
    $(".fixed-menuprofile .dropdown-submenu").find('ul').offset({ "left": newPos });

    $(".fixed-menu .dropdown-submenu").mouseover(function() {
        var submenuPos = $(this).offset().left + 325;
        var windowPos  = $(window).width();
        var oldPos     = $(this).offset().left + $(this).width();
        var newPos     = $(this).offset().left - $(this).width();

        if( submenuPos > windowPos ){
            $(this).find('ul').offset({ "left": newPos });
        } else {
            $(this).find('ul').offset({ "left": oldPos });
        }
    });
});

because I don't want to add this fix on every menu items I created a new class on it. place the fixed-menu on the ul:

<ul class="dropdown-menu fixed-menu">

I hope this works out for you.

ps. little bug in safari and chrome, first hover will place it to mutch to the left will update this post if I fixed it.

How to access ssis package variables inside script component

I had the same problem as the OP except I remembered to declare the ReadOnlyVariables.

After some playing around, I discovered it was the name of my variable that was the issue. "File_Path" in SSIS somehow got converted to "FilePath". C# does not play nicely with underscores in variable names.

So to access the variable, I type

string fp = Variables.FilePath;

In the PreExecute() method of the Script Component.

Install a Python package into a different directory using pip?

Installing a Python package often only includes some pure Python files. If the package includes data, scripts and or executables, these are installed in different directories from the pure Python files.

Assuming your package has no data/scripts/executables, and that you want your Python files to go into /python/packages/package_name (and not some subdirectory a few levels below /python/packages as when using --prefix), you can use the one time command:

pip install --install-option="--install-purelib=/python/packages" package_name

If you want all (or most) of your packages to go there, you can edit your ~/.pip/pip.conf to include:

[install]
install-option=--install-purelib=/python/packages

That way you can't forget about having to specify it again and again.

Any excecutables/data/scripts included in the package will still go to their default places unless you specify addition install options (--prefix/--install-data/--install-scripts, etc., for details look at the custom installation options).

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

"could not find stored procedure"

make sure that your schema name is in the connection string?

How do I create a MessageBox in C#?

I got the same error 'System.Windows.Forms.MessageBox' is a 'type' but is used like a 'variable', even if using:

MessageBox.Show("Hello, World!");

I guess my initial attempts with invalid syntax caused some kind of bug and I ended up fixing it by adding a space between "MessageBox.Show" and the brackets ():

MessageBox.Show ("Hello, World!");

Now using the original syntax without the extra space works again:

MessageBox.Show("Hello, World!");

How to remove from a map while iterating it?

Assuming C++11, here is a one-liner loop body, if this is consistent with your programming style:

using Map = std::map<K,V>;
Map map;

// Erase members that satisfy needs_removing(itr)
for (Map::const_iterator itr = map.cbegin() ; itr != map.cend() ; )
  itr = needs_removing(itr) ? map.erase(itr) : std::next(itr);

A couple of other minor style changes:

  • Show declared type (Map::const_iterator) when possible/convenient, over using auto.
  • Use using for template types, to make ancillary types (Map::const_iterator) easier to read/maintain.

Select info from table where row has max date

SELECT group, date, checks
  FROM table 
  WHERE checks > 0
  GROUP BY group HAVING date = max(date) 

should work.

Revert to Eclipse default settings

go to windows>preferences>Java>Editor>Syntax Coloring go all the way down and click on Restore Defaults & Apply and Close

VIM Disable Automatic Newline At End Of File

I've implemented Blixtor's suggestions with Perl and Python post-processing, either running inside Vim (if it is compiled with such language support), or via an external Perl script. It's available as the PreserveNoEOL plugin on vim.org.

How to copy data from one table to another new table in MySQL?

the above query only works if we have created clients table with matching columns of the customer

INSERT INTO clients(c_id,name,address)SELECT c_id,name,address FROM customer

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

It may be obvious, but it still was surprising to me, that SET NAMES utf8 is not compatible with utf8mb4 encoding. So for some apps changing table/column encoding was not enough. I had to change encoding in app configuration.

Redmine (ruby, ROR)

In config/database.yml:

production:
  adapter: mysql2
  database: redmine
  host: localhost
  username: redmine
  password: passowrd
  encoding: utf8mb4

Custom Yii application (PHP)

In config/db.php:

return [
    'class' => yii\db\Connection::class,
    'dsn' => 'mysql:host=localhost;dbname=yii',
    'username' => 'yii',
    'password' => 'password',
    'charset' => 'utf8mb4',
],

If you have utf8mb4 as a column/table encoding and still getting errors like this, make sure that you have configured correct charset for DB connection in your application.

PHP - find entry by object property from an array of objects

class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

Using it the way you wanted would be something like:

ArrayUtils::objArraySearch($array,'ID',$v);

PHP GuzzleHttp. How to make a post request with params?

Try this

$client = new \GuzzleHttp\Client();
$client->post(
    'http://www.example.com/user/create',
    array(
        'form_params' => array(
            'email' => '[email protected]',
            'name' => 'Test user',
            'password' => 'testpassword'
        )
    )
);

Error 1053 the service did not respond to the start or control request in a timely fashion

To debug the startup of your service, add the following to the top of the OnStart() method of your service:

 while(!System.Diagnostics.Debugger.IsAttached) Thread.Sleep(100);

This will stall the service until you manually attach the Visual Studio Debugger using Debug -> Attach to Process...

Note: In general, if you need a user to interact with your service, it is better to split the GUI components into a separate Windows application that runs when the user logs in. You then use something like named pipes or some other form of IPC to establish communication between the GUI app and your service. This is in fact the only way that this is possible in Windows Vista.

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

What is JNDI? What is its basic use? When is it used?

I will use one example to explain how JNDI can be used to configure database without any application developer knowing username and password of the database.

1) We have configured the data source in JBoss server's standalone-full.xml. Additionally, we can configure pool details also.

 <datasource jta="false" jndi-name="java:/DEV.DS" pool-name="DEV" enabled="true" use-ccm="false">
                <connection-url>jdbc:oracle:thin:@<IP>:1521:DEV</connection-url>
                <driver-class>oracle.jdbc.OracleDriver</driver-class>
                <driver>oracle</driver>
                <security>
                    <user-name>usname</user-name>
                    <password>pass</password>
                    </security>
                    <security>

 <security-domain>encryptedSecurityDomain</security-domain>
                    </security>

                <validation>
                    <validate-on-match>false</validate-on-match>
                    <background-validation>false</background-validation>
                    <background-validation-millis>1</background-validation-millis>
                </validation>
                <statement>
                    <prepared-statement-cache-size>0</prepared-statement-cache-size>
                    <share-prepared-statements>false</share-prepared-statements>
                    <pool>
                        <min-pool-size>5</min-pool-size>
                        <max-pool-size>10</max-pool-size>
                    </pool>
                </statement>
            </datasource>

enter image description here

Now, this jndi-name and its associated datasource object will be available for our application.application.

2) We can retrieve this datasource object using JndiDataSourceLookup class.

enter image description here

Spring will instantiate the datasource bean, after we provide the jndi-name.

Now, we can change the pool size, user name or password as per our environment or requirement, but it will not impact the application.

Note : encryptedSecurityDomain, we need to configure it separately in JBoss server like

<security-domain name="encryptedSecurityDomain" cache-type="default">
                    <authentication>
                        <login-module code="org.picketbox.datasource.security.SecureIdentityLoginModule" flag="required">
                            <module-option name="username" value="<usernamefordb>"/>
                            <module-option name="password" value="894c8a6aegc8d028ce169c596d67afd0"/>
                        </login-module>
                    </authentication>
                </security-domain>

This is one of the use cases. Hope it clarifies.

Spring security CORS Filter

Ok, after over 2 days of searching we finally fixed the problem. We deleted all our filter and configurations and instead used this 5 lines of code in the application class.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        final ApplicationContext ctx = SpringApplication.run(Application.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:3000");
            }
        };
    }
}

Google Maps API v3: How do I dynamically change the marker icon?

You can also use a circle as a marker icon, for example:

var oMarker = new google.maps.Marker({
    position: latLng,
    sName: "Marker Name",
    map: map,
    icon: {
        path: google.maps.SymbolPath.CIRCLE,
        scale: 8.5,
        fillColor: "#F00",
        fillOpacity: 0.4,
        strokeWeight: 0.4
    },
});

and then, if you want to change the marker dynamically (like on mouseover), you can, for example:

oMarker.setIcon({
            path: google.maps.SymbolPath.CIRCLE,
            scale: 10,
            fillColor: "#00F",
            fillOpacity: 0.8,
            strokeWeight: 1
        })

How to check if a String is numeric in Java

Do not use Exceptions to validate your values. Use Util libs instead like apache NumberUtils:

NumberUtils.isNumber(myStringValue);

Edit:

Please notice that, if your string starts with an 0, NumberUtils will interpret your value as hexadecimal.

NumberUtils.isNumber("07") //true
NumberUtils.isNumber("08") //false

Unable to run 'adb root' on a rooted Android phone

I finally found out how to do this! Basically you need to run adb shell first and then while you're in the shell run su, which will switch the shell to run as root!

$: adb shell
$: su

The one problem I still have is that sqlite3 is not installed so the command is not recognized.

How do I add one month to current date in Java?

If you need a one-liner (i.e. for Jasper Reports formula) and don't mind if the adjustment is not exactly one month (i.e "30 days" is enough):

new Date($F{invoicedate}.getTime() + 30L * 24L * 60L * 60L * 1000L)

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

event.preventDefault() function not working in IE

in IE, you can use

event.returnValue = false;

to achieve the same result.

And in order not to get an error, you can test for the existence of preventDefault:

if(event.preventDefault) event.preventDefault();

You can combine the two with:

event.preventDefault ? event.preventDefault() : (event.returnValue = false);

How to migrate GIT repository from one server to a new one

Copy it over. It's really that simple. :)

On the client side, just edit .git/config in the client's local repo to point your remotes to the new URL as necessary.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
    myDict[k] = A.get(k, 0)+B.get(k, 0)

jQuery - Trigger event when an element is removed from the DOM

You can bind to the DOMNodeRemoved event (part of DOM Level 3 WC3 spec).

Works in IE9, latest releases of Firefox and Chrome.

Example:

$(document).bind("DOMNodeRemoved", function(e)
{
    alert("Removed: " + e.target.nodeName);
});

You can also get notification when elements are inserting by binding to DOMNodeInserted

mysql query order by multiple items

SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;

convert htaccess to nginx

Use this: http://winginx.com/htaccess

Online converter, nice way and time saver ;)

Create session factory in Hibernate 4

The following expresses the experience I had with hibernate 4.0.0.Final.

The javadoc (distributed under LGPL license) of org.hibernate.cfg.Configuration class states that:

NOTE : This will be replaced by use of ServiceRegistryBuilder and org.hibernate.metamodel.MetadataSources instead after the 4.0 release at which point this class will become deprecated and scheduled for removal in 5.0. See HHH-6183, HHH-2578 and HHH-6586 for details

After looking at issue 2578, i used something like this:

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addResource("some_mapping.hbm.xml")
SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory();

For it to start reading configuration, i had to modify my hibernate 3.2.6 configuration and mapping files to use xmlns="http://www.hibernate.org/xsd/hibernate-configuration" and xmlns="http://www.hibernate.org/xsd/hibernate-mapping" and also remove the dtd specifications.

I couldn't find a way for it to inspect mappings defined in hibernate.cfg.xml and hibernate. prefix for hibernate-related properties in hibernate.cfg.xml is no longer optional.

This might work for some.

I, for one, ran into some error because mapping files contained <cache usage="read-write" /> and ended up using deprecated Configuration way:

Configuration configuration = new Configuration().configure();
SessionFactoryImpl sessionFactory = (SessionFactoryImpl) configuration.buildSessionFactory();
EventListenerRegistry listenerRegistry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
SolrIndexEventListener indexListener = new SolrIndexEventListener(); // a SaveOrUpdateEventListener i wanted to attach
listenerRegistry.appendListeners(EventType.SAVE_UPDATE, indexListener);

I had to programatically append event listeners because Configuration no longer looks for them in hibernate.cfg.xml

Change Select List Option background colour on hover

I realise this is an older question, but I recently came across this need and came up with the following solution using jQuery and CSS:

jQuery('select[name*="lstDestinations"] option').hover(
        function() {
            jQuery(this).addClass('highlight');
        }, function() {
            jQuery(this).removeClass('highlight');
        }
    );

and the css:

.highlight {
    background-color:#333;
    cursor:pointer;
}

Perhaps this helps someone else.

What is an API key?

What "exactly" an API key is used for depends very much on who issues it, and what services it's being used for. By and large, however, an API key is the name given to some form of secret token which is submitted alongside web service (or similar) requests in order to identify the origin of the request. The key may be included in some digest of the request content to further verify the origin and to prevent tampering with the values.

Typically, if you can identify the source of a request positively, it acts as a form of authentication, which can lead to access control. For example, you can restrict access to certain API actions based on who's performing the request. For companies which make money from selling such services, it's also a way of tracking who's using the thing for billing purposes. Further still, by blocking a key, you can partially prevent abuse in the case of too-high request volumes.

In general, if you have both a public and a private API key, then it suggests that the keys are themselves a traditional public/private key pair used in some form of asymmetric cryptography, or related, digital signing. These are more secure techniques for positively identifying the source of a request, and additionally, for protecting the request's content from snooping (in addition to tampering).

Get width/height of SVG element

This is the consistent cross-browser way I found:

var heightComponents = ['height', 'paddingTop', 'paddingBottom', 'borderTopWidth', 'borderBottomWidth'],
    widthComponents = ['width', 'paddingLeft', 'paddingRight', 'borderLeftWidth', 'borderRightWidth'];

var svgCalculateSize = function (el) {

    var gCS = window.getComputedStyle(el), // using gCS because IE8- has no support for svg anyway
        bounds = {
            width: 0,
            height: 0
        };

    heightComponents.forEach(function (css) { 
        bounds.height += parseFloat(gCS[css]);
    });
    widthComponents.forEach(function (css) {
        bounds.width += parseFloat(gCS[css]);
    });
    return bounds;
};

How to increase heap size of an android application?

You can use android:largeHeap="true" to request a larger heap size, but this will not work on any pre Honeycomb devices. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above.

The only way to have as large a limit as possible is to do memory intensive tasks via the NDK, as the NDK does not impose memory limits like the SDK.

Alternatively, you could only load the part of the model that is currently in view, and load the rest as you need it, while removing the unused parts from memory. However, this may not be possible, depending on your app.

SQL: Alias Column Name for Use in CASE Statement

I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.

With localView1 as (
 select c1,
        c2,
        c3,
        c4,
        ((c2-c4)*(3))+c1 as "complex"
   from realTable1) 
   , localView2 as (
 select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
        complex * complex as formula2    
   from localView1)
select *
from localView2

How to get TimeZone from android mobile?

I needed the offset that not only included day light savings time but as a numerial. Here is the code that I used in case someone is looking for an example.

I get a response of "3.5" (3:30') which is what I would expect in Tehran , Iran in winter and "4.5" (4:30') for summer .

I also needed it as a string so I could post it to a server so you may not need the last line.

for getting currect time zone :

TimeZone tz = TimeZone.getDefault();
Date now = new Date();
//Import part : x.0 for double number
double offsetFromUtc = tz.getOffset(now.getTime()) / 3600000.0;
String m2tTimeZoneIs = Double.parseDouble(offsetFromUtc);

Javascript/jQuery: Set Values (Selection) in a multiple Select

Basically do a values.split(',') and then loop through the resulting array and set the Select.

td widths, not working?

 <table style="table-layout:fixed;">

This will force the styled width <td>. If the text overfills it, it will overlap the other <td> text. So try using media queries.

jackson deserialization json to java-objects

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

Parse v. TryParse

The TryParse method allows you to test whether something is parseable. If you try Parse as in the first instance with an invalid int, you'll get an exception while in the TryParse, it returns a boolean letting you know whether the parse succeeded or not.

As a footnote, passing in null to most TryParse methods will throw an exception.

RE error: illegal byte sequence on Mac OS X

A sample command that exhibits the symptom: sed 's/./@/' <<<$'\xfc' fails, because byte 0xfc is not a valid UTF-8 char.
Note that, by contrast, GNU sed (Linux, but also installable on macOS) simply passes the invalid byte through, without reporting an error.

Using the formerly accepted answer is an option if you don't mind losing support for your true locale (if you're on a US system and you never need to deal with foreign characters, that may be fine.)

However, the same effect can be had ad-hoc for a single command only:

LC_ALL=C sed -i "" 's|"iphoneos-cross","llvm-gcc:-O3|"iphoneos-cross","clang:-Os|g' Configure

Note: What matters is an effective LC_CTYPE setting of C, so LC_CTYPE=C sed ... would normally also work, but if LC_ALL happens to be set (to something other than C), it will override individual LC_*-category variables such as LC_CTYPE. Thus, the most robust approach is to set LC_ALL.

However, (effectively) setting LC_CTYPE to C treats strings as if each byte were its own character (no interpretation based on encoding rules is performed), with no regard for the - multibyte-on-demand - UTF-8 encoding that OS X employs by default, where foreign characters have multibyte encodings.

In a nutshell: setting LC_CTYPE to C causes the shell and utilities to only recognize basic English letters as letters (the ones in the 7-bit ASCII range), so that foreign chars. will not be treated as letters, causing, for instance, upper-/lowercase conversions to fail.

Again, this may be fine if you needn't match multibyte-encoded characters such as é, and simply want to pass such characters through.

If this is insufficient and/or you want to understand the cause of the original error (including determining what input bytes caused the problem) and perform encoding conversions on demand, read on below.


The problem is that the input file's encoding does not match the shell's.
More specifically, the input file contains characters encoded in a way that is not valid in UTF-8 (as @Klas Lindbäck stated in a comment) - that's what the sed error message is trying to say by invalid byte sequence.

Most likely, your input file uses a single-byte 8-bit encoding such as ISO-8859-1, frequently used to encode "Western European" languages.

Example:

The accented letter à has Unicode codepoint 0xE0 (224) - the same as in ISO-8859-1. However, due to the nature of UTF-8 encoding, this single codepoint is represented as 2 bytes - 0xC3 0xA0, whereas trying to pass the single byte 0xE0 is invalid under UTF-8.

Here's a demonstration of the problem using the string voilà encoded as ISO-8859-1, with the à represented as one byte (via an ANSI-C-quoted bash string ($'...') that uses \x{e0} to create the byte):

Note that the sed command is effectively a no-op that simply passes the input through, but we need it to provoke the error:

  # -> 'illegal byte sequence': byte 0xE0 is not a valid char.
sed 's/.*/&/' <<<$'voil\x{e0}'

To simply ignore the problem, the above LCTYPE=C approach can be used:

  # No error, bytes are passed through ('á' will render as '?', though).
LC_CTYPE=C sed 's/.*/&/' <<<$'voil\x{e0}'

If you want to determine which parts of the input cause the problem, try the following:

  # Convert bytes in the 8-bit range (high bit set) to hex. representation.
  # -> 'voil\x{e0}'
iconv -f ASCII --byte-subst='\x{%02x}' <<<$'voil\x{e0}'

The output will show you all bytes that have the high bit set (bytes that exceed the 7-bit ASCII range) in hexadecimal form. (Note, however, that that also includes correctly encoded UTF-8 multibyte sequences - a more sophisticated approach would be needed to specifically identify invalid-in-UTF-8 bytes.)


Performing encoding conversions on demand:

Standard utility iconv can be used to convert to (-t) and/or from (-f) encodings; iconv -l lists all supported ones.

Examples:

Convert FROM ISO-8859-1 to the encoding in effect in the shell (based on LC_CTYPE, which is UTF-8-based by default), building on the above example:

  # Converts to UTF-8; output renders correctly as 'voilà'
sed 's/.*/&/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

Note that this conversion allows you to properly match foreign characters:

  # Correctly matches 'à' and replaces it with 'ü': -> 'voilü'
sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')"

To convert the input BACK to ISO-8859-1 after processing, simply pipe the result to another iconv command:

sed 's/à/ü/' <<<"$(iconv -f ISO-8859-1 <<<$'voil\x{e0}')" | iconv -t ISO-8859-1

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

What is a superfast way to read large files line-by-line in VBA?

With that code you load the file in memory (as a big string) and then you read that string line by line.

By using Mid$() and InStr() you actually read the "file" twice but since it's in memory, there is no problem.
I don't know if VB's String has a length limit (probably not) but if the text files are hundreds of megabyte in size it's likely to see a performance drop, due to virtual memory usage.

How to find elements by class

This worked for me:

for div in mydivs:
    try:
        clazz = div["class"]
    except KeyError:
        clazz = ""
    if (clazz == "stylelistrow"):
        print div

Example on ToggleButton

Move this

 btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
     editString = ed.getText().toString();

inside onClick

Also you change the state of the toogle button whether its 0 or 1

http://developer.android.com/guide/topics/ui/controls/togglebutton.html

Example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="20dp"
        android:text="Button" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="26dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="51dp"
        android:text="Switch" />

    <ToggleButton
        android:id="@+id/togglebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/switch1"
        android:layout_marginTop="58dp"
        android:onClick="onToggleClicked"
        android:textOff="Vibrate off"
        android:textOn="Vibrate on" />

</RelativeLayout>

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

    EditText ed;
    Switch sb;
    ToggleButton tb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ed = (EditText) findViewById(R.id.editText1);
        Button b = (Button) findViewById(R.id.button1);
        sb = (Switch)findViewById(R.id.switch1);
        tb = (ToggleButton)findViewById(R.id.togglebutton);
        b.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        String s = ed.getText().toString();
         if(s.equals("1")){

             tb.setText("TOGGLE ON");
             tb.setActivated(true);
             sb.setChecked(true);

         }
         else if(s.equals("0")){

             tb.setText("TOGGLE OFF");
             tb.setActivated(false);
             sb.setChecked(false);

    }

    }
     }

Snaps

enter image description here

enter image description here

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

Left Outer Join using + sign in Oracle 11g

LEFT OUTER JOIN

SELECT * FROM A, B WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT * FROM A, B WHERE A.column (+)= B.column

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can check that theHref is defined by checking against undefined.

if (undefined !== theHref && theHref.length) {
    // `theHref` is not undefined and has truthy property _length_
    // do stuff
} else {
    // do other stuff
}

If you want to also protect yourself against falsey values like null then check theHref is truthy, which is a little shorter

if (theHref && theHref.length) {
    // `theHref` is truthy and has truthy property _length_
}

How does Google reCAPTCHA v2 work behind the scenes?

May I present my guess, since this is not a open technology.

Google says it's about combing information from before, during, after to distinguish human from robot. But I am more interested about that final click on the check box.

Say, the POST data (solved CAPTCHA) has a field called fingerprint, a string calculated from user behavior. I think there may be a field about that check box location. I guess this check box is in a coordinate system randomly generated by Google back-end and encrypted by the public key of my site. So, a robot may "guess/calculate" a location about this box, but when site owner makes the GET query with private key to verify user identity, Google will decrypt the coordinate system and say if the user click on the right place. So, only one possible right click(with some offsets, it's a square box) location in this random coordinate system owned by only Google and site owners.

How do I exit from a function?

Use the return keyword.

return; //exit this event

How to do a https request with bad certificate?

Security note: Disabling security checks is dangerous and should be avoided

You can disable security checks globally for all requests of the default client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
    _, err := http.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

You can disable security check for a client:

package main

import (
    "fmt"
    "net/http"
    "crypto/tls"
)

func main() {
    tr := &http.Transport{
        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
    }
    client := &http.Client{Transport: tr}
    _, err := client.Get("https://golang.org/")
    if err != nil {
        fmt.Println(err)
    }
}

Observable.of is not a function

If you are using Angular 6 /7

import { of } from 'rxjs';

And then instead of calling

Observable.of(res);

just use

of(res);

Android - how to make a scrollable constraintlayout?

TO make a scrollable layout, the layout is correct. It will not be scrollable until there is reason to scroll(just like in any other layout). So add enough content and it will be scrollable, just like with any layout(Linear, Relative, etc). However, you cannot scroll properly in Blueprint or design-mode when designing with ConstraintLayout and ScrollView.

Meaning:

You can make a scrollable ConstraintLayout, but it will not scroll properly in the editor due to a bug/scenario that wasn't considered. But even though scrolling doesn't work in the editor, it works on devices. (I have made several scrolling COnstraintLayouts, so I have tested it)

Note

Regarding your code. The ScrollView is missing a closing tag, I don't know if it is the case in the file or if it is a copy-paste miss, but you may want to look at it.

Maximum number of records in a MySQL database table

The greatest value of an integer has little to do with the maximum number of rows you can store in a table.

It's true that if you use an int or bigint as your primary key, you can only have as many rows as the number of unique values in the data type of your primary key, but you don't have to make your primary key an integer, you could make it a CHAR(100). You could also declare the primary key over more than one column.

There are other constraints on table size besides number of rows. For instance you could use an operating system that has a file size limitation. Or you could have a 300GB hard drive that can store only 300 million rows if each row is 1KB in size.

The limits of database size is really high:

http://dev.mysql.com/doc/refman/5.1/en/source-configuration-options.html

The MyISAM storage engine supports 232 rows per table, but you can build MySQL with the --with-big-tables option to make it support up to 264 rows per table.

http://dev.mysql.com/doc/refman/5.1/en/innodb-restrictions.html

The InnoDB storage engine has an internal 6-byte row ID per table, so there are a maximum number of rows equal to 248 or 281,474,976,710,656.

An InnoDB tablespace also has a limit on table size of 64 terabytes. How many rows fits into this depends on the size of each row.

The 64TB limit assumes the default page size of 16KB. You can increase the page size, and therefore increase the tablespace up to 256TB. But I think you'd find other performance factors make this inadvisable long before you grow a table to that size.

How to hide only the Close (x) button?

Well, you can hide it, by removing the entire system menu:

private const int WS_SYSMENU = 0x80000;
protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.Style &= ~WS_SYSMENU;
        return cp;
    }
}

Of course, doing so removes the minimize and maximize buttons.

If you keep the system menu but remove the close item then the close button remains but is disabled.

The final alternative is to paint the non-client area yourself. That's pretty hard to get right.

What is the difference between the dot (.) operator and -> in C++?

It's simple, whenever you see

 x->y

know it is the same as

 (*x).y

how to resolve DTS_E_OLEDBERROR. in ssis

I would start by turning off TCP offloading. There have been a few things that cause intermittent connectivity issues and this is the one that is usually the culprit.

Note: I have seen this setting cause problems on Win Server 2003 and Win Server 2008

http://blogs.msdn.com/b/mssqlisv/archive/2008/05/27/sql-server-intermittent-connectivity-issue.aspx

http://technet.microsoft.com/en-us/library/gg162682(v=ws.10).aspx

http://blogs.msdn.com/b/psssql/archive/2008/10/01/windows-scalable-networking-pack-possible-performance-and-concurrency-impacts-to-sql-server-workloads.aspx

How do I set a JLabel's background color?

Use

label.setOpaque(true);

Otherwise the background is not painted, since the default of opaque is false for JLabel.

From the JavaDocs:

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

For more information, read the Java Tutorial How to Use Labels.

Can I remove the URL from my print css, so the web address doesn't print?

I am not sure but the URL is added by a browser when you want to print. It is not part of the page so can not be affected by CSS. Maybe there is a way but it will be browser dependent.

Java, return if trimmed String in List contains String

With Java 8 Stream API:

List<String> myList = Arrays.asList("  A", "B  ", "  C  ");
return myList.stream().anyMatch(str -> str.trim().equals("B"));

What is the reason for the error message "System cannot find the path specified"?

You just need to:

Step 1: Go home directory of C:\ with typing cd.. (2 times)

Step 2: It appears now C:\>

Step 3: Type dir Windows\System32\run

That's all, it shows complete files & folder details inside target folder.

enter image description here

Details: I used Windows\System32\com folder as example, you should type your own folder name etc. Windows\System32\run

How to calculate cumulative normal distribution?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the cumulative distribution function (cdf - probability that a random sample X will be less than or equal to x) for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=0, sigma=1).cdf(1.96)
# 0.9750021048517796

Which can be simplified for the standard normal distribution (mu = 0 and sigma = 1):

NormalDist().cdf(1.96)
# 0.9750021048517796

NormalDist().cdf(-1.96)
# 0.024997895148220428

How to sort a list of strings numerically?

may be not the best python, but for string lists like ['1','1.0','2.0','2', '1.1', '1.10', '1.11', '1.2','7','3','5']with the expected target ['1', '1.0', '1.1', '1.2', '1.10', '1.11', '2', '2.0', '3', '5', '7'] helped me...

unsortedList = ['1','1.0','2.0','2', '1.1', '1.10', '1.11', '1.2','7','3','5']
sortedList = []
sortDict = {}
sortVal = []
#set zero correct (integer): examp: 1.000 will be 1 and breaks the order
zero = "000"
for i in sorted(unsortedList):
  x = i.split(".")
  if x[0] in sortDict:
    if len(x) > 1:
        sortVal.append(x[1])
    else:
        sortVal.append(zero)
    sortDict[x[0]] = sorted(sortVal, key = int)
  else:
    sortVal = []
    if len(x) > 1:
        sortVal.append(x[1])
    else:
        sortVal.append(zero)
    sortDict[x[0]] = sortVal
for key in sortDict:
  for val in sortDict[key]:
    if val == zero:
       sortedList.append(str(key))
    else:
       sortedList.append(str(key) + "." + str(val))
print(sortedList)

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Add services.AddSingleton(); in your ConfigureServices method of Startup.cs file of your project.

public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages();
        // To register interface with its concrite type
        services.AddSingleton<IEmployee, EmployeesMockup>();
    }

For More details please visit this URL : https://www.youtube.com/watch?v=aMjiiWtfj2M

for All methods (i.e. AddSingleton vs AddScoped vs AddTransient) Please visit this URL: https://www.youtube.com/watch?v=v6Nr7Zman_Y&list=PL6n9fhu94yhVkdrusLaQsfERmL_Jh4XmU&index=44)

CSS3 selector :first-of-type with class name?

No, it's not possible using just one selector. The :first-of-type pseudo-class selects the first element of its type (div, p, etc). Using a class selector (or a type selector) with that pseudo-class means to select an element if it has the given class (or is of the given type) and is the first of its type among its siblings.

Unfortunately, CSS doesn't provide a :first-of-class selector that only chooses the first occurrence of a class. As a workaround, you can use something like this:

.myclass1 { color: red; }
.myclass1 ~ .myclass1 { color: /* default, or inherited from parent div */; }

Explanations and illustrations for the workaround are given here and here.

GCD to perform task in main thread

No you don't need to check if you're in the main thread. Here is how you can do this in Swift:

runThisInMainThread { () -> Void in
    runThisInMainThread { () -> Void in
        // No problem
    }
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

Sorting data based on second column of a file

Use sort.

sort ... -k 2,2 ...

css3 transition animation on load?

You could use custom css classes (className) instead of the css tag too. No need for an external package.

import React, { useState, useEffect } from 'react';
import { css } from '@emotion/css'

const Hello = (props) => {
    const [loaded, setLoaded] = useState(false);

    useEffect(() => {
        // For load
        setTimeout(function () {
            setLoaded(true);
        }, 50); // Browser needs some time to change to unload state/style

        // For unload
        return () => {
            setLoaded(false);
        };
    }, [props.someTrigger]); // Set your trigger

    return (
        <div
            css={[
                css`
                    opacity: 0;
                    transition: opacity 0s;
                `,
                loaded &&
                    css`
                        transition: opacity 2s;
                        opacity: 1;
                    `,
            ]}
        >
            hello
        </div>
    );
};

Alternative to iFrames with HTML5

I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.

Changes to the parent site are picked up every 5 minutes.

var iframeReplacement = require('node-iframe-replacement');

// add iframe replacement to express as middleware (adds res.merge method) 
app.use(iframeReplacement);

// create a regular express route 
app.get('/', function(req, res){

    // respond to this request with our fake-news content embedded within the BBC News home page 
    res.merge('fake-news', {
        // external url to fetch 
       sourceUrl: 'http://www.bbc.co.uk/news',
       // css selector to inject our content into 
       sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
       // pass a function here to intercept the source html prior to merging 
       transform: null
    });
});

The source contains a working example of injecting content into the BBC News home page.

jQuery select box validation

To put a require rule on a select list you just need an option with an empty value

<option value="">Year</option>

then just applying required on its own is enough

<script>
    $(function () {
        $("form").validate();
    });
</script>

with form

<form>
<select name="year" id="year" class="required">
    <option value="">Year</option>
    <option value="1">1919</option>
    <option value="2">1920</option>
    <option value="3">1921</option>
    <option value="4">1922</option>
</select>
<input type="submit" />
</form>

fiddle is here

Get the current first responder without using a private API

Just it case here is Swift version of awesome Jakob Egger's approach:

import UIKit

private weak var currentFirstResponder: UIResponder?

extension UIResponder {

    static func firstResponder() -> UIResponder? {
        currentFirstResponder = nil
        UIApplication.sharedApplication().sendAction(#selector(self.findFirstResponder(_:)), to: nil, from: nil, forEvent: nil)
        return currentFirstResponder
    }

    func findFirstResponder(sender: AnyObject) {
        currentFirstResponder = self
    }

}

How does OkHttp get Json string?

Below code is for getting data from online server using GET method and okHTTP library for android kotlin...

Log.e("Main",response.body!!.string())

in above line !! is the thing using which you can get the json from response body

val client = OkHttpClient()
            val request: Request = Request.Builder()
                .get()
                .url("http://172.16.10.126:8789/test/path/jsonpage")
                .addHeader("", "")
                .addHeader("", "")
                .build()
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    // Handle this
                    Log.e("Main","Try again latter!!!")
                }

                override fun onResponse(call: Call, response: Response) {
                    // Handle this
                    Log.e("Main",response.body!!.string())
                }
            })

git push: permission denied (public key)

This worked for me. Simplest solution by far.

If you are using GitHub for Windows and getting this error, the problem might be that you are trying to run the command in the wrong shell or mode. If you are trying to do git push origin master in the regular command prompt or PowerShell, this is the problem.

You need to do it in a git shell. Simply open Github for Windows, right click, and select "Open Shell Here". It looks like a regular PowerShell window, but it's not, which makes it really confusing for newbies to git, like myself.

I hope others find this useful.

DISTINCT clause with WHERE

If you have a unique column in your table (e.g. tableid) then try this.

SELECT EMAIL FROM TABLE WHERE TABLEID IN 
(SELECT MAX(TABLEID), EMAIL FROM TABLE GROUP BY EMAIL)

How to uninstall with msiexec using product id guid without .msi file present

you need /q at the end

MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q

Spring Security redirect to previous page after successful login

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}

Python: Differentiating between row and column vectors

I think you can use ndmin option of numpy.array. Keeping it to 2 says that it will be a (4,1) and transpose will be (1,4).

>>> a = np.array([12, 3, 4, 5], ndmin=2)
>>> print a.shape
>>> (1,4)
>>> print a.T.shape
>>> (4,1)

Error: [$injector:unpr] Unknown provider: $routeProvider

It looks like you forgot to include the ngRoute module in your dependency for myApp.

In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.

'use strict';

angular.module('myApp', ['ngRoute']).
    config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);

How to replace a character from a String in SQL?

Use the REPLACE function.

eg: SELECT REPLACE ('t?es?t', '?', 'w');

Source

How do I add a ToolTip to a control?

Here is your article for doing it with code

private void Form1_Load(object sender, System.EventArgs e)
{
     // Create the ToolTip and associate with the Form container.
     ToolTip toolTip1 = new ToolTip();

     // Set up the delays for the ToolTip.
     toolTip1.AutoPopDelay = 5000;
     toolTip1.InitialDelay = 1000;
     toolTip1.ReshowDelay = 500;
     // Force the ToolTip text to be displayed whether or not the form is active.
     toolTip1.ShowAlways = true;

     // Set up the ToolTip text for the Button and Checkbox.
     toolTip1.SetToolTip(this.button1, "My button1");
     toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

SQL "between" not inclusive

cast(created_at as date)

That will work only in 2008 and newer versions of SQL Server

If you are using older version then use

convert(varchar, created_at, 101)

How do I clone a job in Jenkins?

Jenkins 2.9

  1. Jenkins > New Item

    Jenkins New Item

  2. Enter an item name - E.g. "MY_CLONE"

    Enter an item name

  3. Specify the source (Copy from) job > OK

    When you start typing the name, the existing values will be found. Notice that this is case sensitive.

    Copy from OK

  4. Click on Save if you want to keep the default values.

  5. Now both jobs are available in the same location:

    View jobs

Make just one slide different size in Powerpoint

true, this option is not available in any version of MS ppt.Now the solution is that You put your different sized slide in other file and put a hyperlink in first file.

How to hide output of subprocess in Python 2.7

As of Python3 you no longer need to open devnull and can call subprocess.DEVNULL.

Your code would be updated as such:

import subprocess
text = 'Hello World.'
print(text)
subprocess.call(['espeak', text], stderr=subprocess.DEVNULL)

Get a list of dates between two dates

Create a stored procedure which takes two parameters a_begin and a_end. Create a temporary table within it called t, declare a variable d, assign a_begin to d, and run a WHILE loop INSERTing d into t and calling ADDDATE function to increment the value d. Finally SELECT * FROM t.

Adjust UILabel height depending on the text

And for those that are migrating to iOS 8, here is a class extension for Swift:

extension UILabel {

    func autoresize() {
        if let textNSString: NSString = self.text {
            let rect = textNSString.boundingRectWithSize(CGSizeMake(self.frame.size.width, CGFloat.max),
                options: NSStringDrawingOptions.UsesLineFragmentOrigin,
                attributes: [NSFontAttributeName: self.font],
                context: nil)
            self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, rect.height)
        }
    }

}

Decimal separator comma (',') with numberDecimal inputType in EditText

A workaround (until Google fix this bug) is to use an EditText with android:inputType="numberDecimal" and android:digits="0123456789.,".

Then add a TextChangedListener to the EditText with the following afterTextChanged:

public void afterTextChanged(Editable s) {
    double doubleValue = 0;
    if (s != null) {
        try {
            doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
        } catch (NumberFormatException e) {
            //Error
        }
    }
    //Do something with doubleValue
}

adb devices command not working

I fixed this issue on my debian GNU/Linux system by overiding system rules that way :

mv  /etc/udev/rules.d/51-android.rules /etc/udev/rules.d/99-android.rules

I used contents from files linked at : http://rootzwiki.com/topic/258-udev-rules-for-any-device-no-more-starting-adb-with-sudo/

jquery beforeunload when closing (not leaving) the page?

As indicated here https://stackoverflow.com/a/1632004/330867, you can implement it by "filtering" what is originating the exit of this page.

As mentionned in the comments, here's a new version of the code in the other question, which also include the ajax request you make in your question :

var canExit = true;

// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.

function checkCart() {
  canExit = false;
  $.ajax({
    url : 'index.php?route=module/cart/check',
    type : 'POST',
    dataType : 'json',
    success : function (result) {
       if (result) {
        canExit = true;
       }
    }
  })
}

$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
    if (canExit) return null; // null will allow exit without a question
    // Else, just return the message you want to display
    return "Do you really want to close?";
});

Important: You shouldn't have a global variable defined (here canExit), this is here for simpler version.

Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : How can I override the OnBeforeUnload dialog and replace it with my own?

Filtering a spark dataframe based on date

Don't use this as suggested in other answers

.filter(f.col("dateColumn") < f.lit('2017-11-01'))

But use this instead

.filter(f.col("dateColumn") < f.unix_timestamp(f.lit('2017-11-01 00:00:00')).cast('timestamp'))

This will use the TimestampType instead of the StringType, which will be more performant in some cases. For example Parquet predicate pushdown will only work with the latter.

Java Read Large Text File With 70million line of text

1) I am sure there is no difference speedwise, both use FileInputStream internally and buffering

2) You can take measurements and see for yourself

3) Though there's no performance benefits I like the 1.7 approach

try (BufferedReader br = Files.newBufferedReader(Paths.get("test.txt"), StandardCharsets.UTF_8)) {
    for (String line = null; (line = br.readLine()) != null;) {
        //
    }
}

4) Scanner based version

    try (Scanner sc = new Scanner(new File("test.txt"), "UTF-8")) {
        while (sc.hasNextLine()) {
            String line = sc.nextLine();
        }
        // note that Scanner suppresses exceptions
        if (sc.ioException() != null) {
            throw sc.ioException();
        }
    }

5) This may be faster than the rest

try (SeekableByteChannel ch = Files.newByteChannel(Paths.get("test.txt"))) {
    ByteBuffer bb = ByteBuffer.allocateDirect(1000);
    for(;;) {
        StringBuilder line = new StringBuilder();
        int n = ch.read(bb);
        // add chars to line
        // ...
    }
}

it requires a bit of coding but it can be really faster because of ByteBuffer.allocateDirect. It allows OS to read bytes from file to ByteBuffer directly, without copying

6) Parallel processing would definitely increase speed. Make a big byte buffer, run several tasks that read bytes from file into that buffer in parallel, when ready find first end of line, make a String, find next...

Setting width as a percentage using jQuery

Using the width function:

$('div#somediv').width('70%');

will turn:

<div id="somediv" />

into:

<div id="somediv" style="width: 70%;"/>

Requested registry access is not allowed

If you don't need admin privs for the entire app, or only for a few infrequent changes you can do the changes in a new process and launch it using:

Process.StartInfo.UseShellExecute = true;
Process.StartInfo.Verb = "runas";

which will run the process as admin to do whatever you need with the registry, but return to your app with the normal priviledges. This way it doesn't prompt the user with a UAC dialog every time it launches.

How do I properly 'printf' an integer and a string in C?

Try this code my friend...

#include<stdio.h>
int main(){
   char *s1, *s2;
   char str[10];

   printf("type a string: ");
   scanf("%s", str);

   s1 = &str[0];
   s2 = &str[2];

   printf("%c\n", *s1);   //use %c instead of %s and *s1 which is the content of position 1
   printf("%c\n", *s2);   //use %c instead of %s and *s3 which is the content of position 1

   return 0;
}

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

You could simply use

return

which does exactly the same as

return None

Your function will also return None if execution reaches the end of the function body without hitting a return statement. Returning nothing is the same as returning None in Python.

How do I pause my shell script for a second before continuing?

Run multiple sleeps and commands

sleep 5 && cd /var/www/html && git pull && sleep 3 && cd ..

This will wait for 5 seconds before executing the first script, then will sleep again for 3 seconds before it changes directory again.

Datatable to html Table

Since I didn't see this in any of the other answers, and since it's more efficient (in lines of code and in speed), here's a solution in VB.NET using a stringbuilder and lambda functions with String.Join instead of For loops for the columns.

Dim sb As New StringBuilder
sb.Append("<table>")
sb.Append("<tr>" & String.Join("", dt.Columns.OfType(Of DataColumn)().Select(Function(x) "<th>" & x.ColumnName & "</th>").ToArray()) & "</tr>")
For Each row As DataRow In dt.Rows
    sb.Append("<tr>" & String.Join("", row.ItemArray.Select(Function(f) "<td>" & f.ToString() & "</td>")) & "</tr>")
Next
sb.Append("</table>")

You can add your own styles to this pretty easily.

Android Facebook style slide

I found a simplest way for it and its working. Use simple Navigation drawer and call drawer.setdrawerListner() and use mainView.setX() method in on drawerSlide method below or copy my code.

xml file

 <android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000" >

<RelativeLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff">

  <ImageView
      android:layout_width="40dp"
      android:layout_height="40dp"
      android:id="@+id/menu"
      android:layout_alignParentTop="true"
      android:layout_alignParentLeft="true"
      android:layout_marginTop="10dp"
      android:layout_marginLeft="10dp"
      android:src="@drawable/black_line"
      />
</RelativeLayout>


<RelativeLayout
    android:id="@+id/left_drawer"
    android:layout_width="200dp"
    android:background="#181D21"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    >
    </RelativeLayout>
 </android.support.v4.widget.DrawerLayout>

java file

   public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
RelativeLayout mainView;
ImageView menu;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    menu=(ImageView)findViewById(R.id.menu);
    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mainView=(RelativeLayout)findViewById(R.id.content_frame);

    menu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            drawerLayout.openDrawer(Gravity.LEFT);
        }
    });

    drawerLayout.setDrawerListener(new DrawerLayout.DrawerListener() {
        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            mainView.setX(slideOffset * 300);
        }

        @Override
        public void onDrawerOpened(View drawerView) {

        }

        @Override
        public void onDrawerClosed(View drawerView) {

        }

        @Override
        public void onDrawerStateChanged(int newState) {

        }
    });
 }
}

enter image description here

Thank You

Auto-loading lib files in Rails 4

Though this does not directly answer the question, but I think it is a good alternative to avoid the question altogether.

To avoid all the autoload_paths or eager_load_paths hassle, create a "lib" or a "misc" directory under "app" directory. Place codes as you would normally do in there, and Rails will load files just like how it will load (and reload) model files.

implements Closeable or implements AutoCloseable

Closeable extends AutoCloseable, and is specifically dedicated to IO streams: it throws IOException instead of Exception, and is idempotent, whereas AutoCloseable doesn't provide this guarantee.

This is all explained in the javadoc of both interfaces.

Implementing AutoCloseable (or Closeable) allows a class to be used as a resource of the try-with-resources construct introduced in Java 7, which allows closing such resources automatically at the end of a block, without having to add a finally block which closes the resource explicitely.

Your class doesn't represent a closeable resource, and there's absolutely no point in implementing this interface: an IOTest can't be closed. It shouldn't even be possible to instantiate it, since it doesn't have any instance method. Remember that implementing an interface means that there is a is-a relationship between the class and the interface. You have no such relationship here.

Python speed testing - Time Difference - milliseconds

Arrow: Better dates & times for Python

import arrow
start_time = arrow.utcnow()
end_time = arrow.utcnow()
(end_time - start_time).total_seconds()  # senconds
(end_time - start_time).total_seconds() * 1000  # milliseconds

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs

lvalue required as left operand of assignment

You need to compare, not assign:

if (strcmp("hello", "hello") == 0)
                             ^

Because you want to check if the result of strcmp("hello", "hello") equals to 0.

About the error:

lvalue required as left operand of assignment

lvalue means an assignable value (variable), and in assignment the left value to the = has to be lvalue (pretty clear).

Both function results and constants are not assignable (rvalues), so they are rvalues. so the order doesn't matter and if you forget to use == you will get this error. (edit:)I consider it a good practice in comparison to put the constant in the left side, so if you write = instead of ==, you will get a compilation error. for example:

int a = 5;
if (a = 0) // Always evaluated as false, no error.
{
    //...
}

vs.

int a = 5;
if (0 = a) // Generates compilation error, you cannot assign a to 0 (rvalue)
{
    //...
}

(see first answer to this question: https://stackoverflow.com/questions/2349378/new-programming-jargon-you-coined)

making matplotlib scatter plots from dataframes in Python's pandas

There is little to be added to Garrett's great answer, but pandas also has a scatter method. Using that, it's as easy as

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
df.plot.scatter('col1', 'col2', df['col3'])

plotting sizes in col3 to col1-col2

Variable number of arguments in C++?

int fun(int n_args, ...) {
   int *p = &n_args; 
   int s = sizeof(int);
   p += s + s - 1;
   for(int i = 0; i < n_args; i++) {
     printf("A1 %d!\n", *p);
     p += 2;
   }
}

Plain version

Solve Cross Origin Resource Sharing with Flask

Well, I faced the same issue. For new users who may land at this page. Just follow their official documentation.

Install flask-cors

pip install -U flask-cors

then after app initialization, initialize flask-cors with default arguments:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
   return "Hello, cross-origin-world!"

accepting HTTPS connections with self-signed certificates

If you have a custom/self-signed certificate on server that is not there on device, you can use the below class to load it and use it on client side in Android:

Place the certificate *.crt file in /res/raw so that it is available from R.raw.*

Use below class to obtain an HTTPClient or HttpsURLConnection which will have a socket factory using that certificate :

package com.example.customssl;

import android.content.Context;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

public class CustomCAHttpsProvider {

    /**
     * Creates a {@link org.apache.http.client.HttpClient} which is configured to work with a custom authority
     * certificate.
     *
     * @param context       Application Context
     * @param certRawResId  R.raw.id of certificate file (*.crt). Should be stored in /res/raw.
     * @param allowAllHosts If true then client will not check server against host names of certificate.
     * @return Http Client.
     * @throws Exception If there is an error initializing the client.
     */
    public static HttpClient getHttpClient(Context context, int certRawResId, boolean allowAllHosts) throws Exception {


        // build key store with ca certificate
        KeyStore keyStore = buildKeyStore(context, certRawResId);

        // init ssl socket factory with key store
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(keyStore);

        // skip hostname security check if specified
        if (allowAllHosts) {
            sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
        }

        // basic http params for client
        HttpParams params = new BasicHttpParams();

        // normal scheme registry with our ssl socket factory for "https"
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));

        // create connection manager
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

        // create http client
        return new DefaultHttpClient(cm, params);
    }

    /**
     * Creates a {@link javax.net.ssl.HttpsURLConnection} which is configured to work with a custom authority
     * certificate.
     *
     * @param urlString     remote url string.
     * @param context       Application Context
     * @param certRawResId  R.raw.id of certificate file (*.crt). Should be stored in /res/raw.
     * @param allowAllHosts If true then client will not check server against host names of certificate.
     * @return Http url connection.
     * @throws Exception If there is an error initializing the connection.
     */
    public static HttpsURLConnection getHttpsUrlConnection(String urlString, Context context, int certRawResId,
                                                           boolean allowAllHosts) throws Exception {

        // build key store with ca certificate
        KeyStore keyStore = buildKeyStore(context, certRawResId);

        // Create a TrustManager that trusts the CAs in our KeyStore
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        // Create an SSLContext that uses our TrustManager
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);

        // Create a connection from url
        URL url = new URL(urlString);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());

        // skip hostname security check if specified
        if (allowAllHosts) {
            urlConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
        }

        return urlConnection;
    }

    private static KeyStore buildKeyStore(Context context, int certRawResId) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException {
        // init a default key store
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);

        // read and add certificate authority
        Certificate cert = readCert(context, certRawResId);
        keyStore.setCertificateEntry("ca", cert);

        return keyStore;
    }

    private static Certificate readCert(Context context, int certResourceId) throws CertificateException, IOException {

        // read certificate resource
        InputStream caInput = context.getResources().openRawResource(certResourceId);

        Certificate ca;
        try {
            // generate a certificate
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ca = cf.generateCertificate(caInput);
        } finally {
            caInput.close();
        }

        return ca;
    }

}

Key points:

  1. Certificate objects are generated from .crt files.
  2. A default KeyStore is created.
  3. keyStore.setCertificateEntry("ca", cert) is adding certificate to key store under alias "ca". You modify the code to add more certificates (intermediate CA etc).
  4. Main objective is to generate a SSLSocketFactory which can then be used by HTTPClient or HttpsURLConnection.
  5. SSLSocketFactory can be configured further, for example to skip host name verification etc.

More information at : http://developer.android.com/training/articles/security-ssl.html

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

This is caused by non-matching Spring Boot dependencies. Check your classpath to find the offending resources. You have explicitly included version 1.1.8.RELEASE, but you have also included 3 other projects. Those likely contain different Spring Boot versions, leading to this error.

How does C compute sin() and other math functions?

For sin specifically, using Taylor expansion would give you:

sin(x) := x - x^3/3! + x^5/5! - x^7/7! + ... (1)

you would keep adding terms until either the difference between them is lower than an accepted tolerance level or just for a finite amount of steps (faster, but less precise). An example would be something like:

float sin(float x)
{
  float res=0, pow=x, fact=1;
  for(int i=0; i<5; ++i)
  {
    res+=pow/fact;
    pow*=-1*x*x;
    fact*=(2*(i+1))*(2*(i+1)+1);
  }

  return res;
}

Note: (1) works because of the aproximation sin(x)=x for small angles. For bigger angles you need to calculate more and more terms to get acceptable results. You can use a while argument and continue for a certain accuracy:

double sin (double x){
    int i = 1;
    double cur = x;
    double acc = 1;
    double fact= 1;
    double pow = x;
    while (fabs(acc) > .00000001 &&   i < 100){
        fact *= ((2*i)*(2*i+1));
        pow *= -1 * x*x; 
        acc =  pow / fact;
        cur += acc;
        i++;
    }
    return cur;

}

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled

It seems to me that your Hibernate libraries are not found (NoClassDefFoundError: org/hibernate/boot/archive/scan/spi/ScanEnvironment as you can see above).

Try checking to see if Hibernate core is put in as dependency:

<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-core</artifactId>
  <version>5.0.11.Final</version>
  <scope>compile</scope>
</dependency>

Browser/HTML Force download of image from src="data:image/jpeg;base64..."

I guess an img tag is needed as a child of an a tag, the following way:

<a download="YourFileName.jpeg" href="data:image/jpeg;base64,iVBO...CYII=">
    <img src="data:image/jpeg;base64,iVBO...CYII="></img>
</a>

or

<a download="YourFileName.jpeg" href="/path/to/OtherFile.jpg">
    <img src="/path/to/OtherFile.jpg"></img>
</a>

Only using the a tag as explained in #15 didn't worked for me with the latest version of Firefox and Chrome, but putting the same image data in both a.href and img.src tags worked for me.

From JavaScript it could be generated like this:

var data = canvas.toDataURL("image/jpeg");

var img = document.createElement('img');
img.src = data;

var a = document.createElement('a');
a.setAttribute("download", "YourFileName.jpeg");
a.setAttribute("href", data);
a.appendChild(img);

var w = open();
w.document.title = 'Export Image';
w.document.body.innerHTML = 'Left-click on the image to save it.';
w.document.body.appendChild(a);

OpenSSL and error in reading openssl.conf file

I know this is old -- but thought others that happen on this (and use Visual Studio) might benefit. I read this on another post that I can't seem to find.

Open your config in notepad++ and make sure it's Encoding is UTF-8 (i.e., not UTF-8-BOM*).

This would have save me a lot of searching/trial'n'errors...

Obtain smallest value from array in Javascript?

Imagine you have this array:

var arr = [1, 2, 3];

ES6 way:

var min = Math.min(...arr); //min=1

ES5 way:

var min = Math.min.apply(null, arr); //min=1

If you using D3.js, there is a handy function which does the same, but will ignore undefined values and also check the natural order:

d3.max(array[, accessor])

Returns the maximum value in the given array using natural order. If the array is empty, returns undefined. An optional accessor function may be specified, which is equivalent to calling array.map(accessor) before computing the maximum value.

Unlike the built-in Math.max, this method ignores undefined values; this is useful for ignoring missing data. In addition, elements are compared using natural order rather than numeric order. For example, the maximum of the strings [“20”, “3”] is “3”, while the maximum of the numbers [20, 3] is 20.

And this is the source code for D3 v4:

export default function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  return max;
}

Importing PNG files into Numpy?

According to the doc, scipy.misc.imread is deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead.

Example:

import imageio

im = imageio.imread('my_image.png')
print(im.shape)

You can also use imageio to load from fancy sources:

im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

Edit:

To load all of the *.png files in a specific folder, you could use the glob package:

import imageio
import glob

for im_path in glob.glob("path/to/folder/*.png"):
     im = imageio.imread(im_path)
     print(im.shape)
     # do whatever with the image here

AngularJS - How to use $routeParams in generating the templateUrl?

templateUrl can be use as function with returning generated URL. We can manipulate url with passing argument which takes routeParams.

See the example.

.when('/:screenName/list',{
    templateUrl: function(params){
         return params.screenName +'/listUI'
    }
})

Hope this help.

How to copy file from one location to another location?

Using Stream

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

Using Channel

private static void copyFileUsingChannel(File source, File dest) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
       }
}

Using Apache Commons IO lib:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}

Using Java SE 7 Files class:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

Or try Googles Guava :

https://github.com/google/guava

docs: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html

Compare time:

    File source = new File("/Users/sidikov/tmp/source.avi");
    File dest = new File("/Users/sidikov/tmp/dest.avi");


    //copy file conventional way using Stream
    long start = System.nanoTime();
    copyFileUsingStream(source, dest);
    System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
     
    //copy files using java.nio FileChannel
    source = new File("/Users/sidikov/tmp/sourceChannel.avi");
    dest = new File("/Users/sidikov/tmp/destChannel.avi");
    start = System.nanoTime();
    copyFileUsingChannel(source, dest);
    System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
     
    //copy files using apache commons io
    source = new File("/Users/sidikov/tmp/sourceApache.avi");
    dest = new File("/Users/sidikov/tmp/destApache.avi");
    start = System.nanoTime();
    copyFileUsingApacheCommonsIO(source, dest);
    System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
     
    //using Java 7 Files class
    source = new File("/Users/sidikov/tmp/sourceJava7.avi");
    dest = new File("/Users/sidikov/tmp/destJava7.avi");
    start = System.nanoTime();
    copyFileUsingJava7Files(source, dest);
    System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));

Auto refresh code in HTML using meta tags

The quotes you use are the issue:

<meta http-equiv=”refresh” content=”5" >

You should use the "

<meta http-equiv="refresh" content="5">

Should I write script in the body or the head of the html?

W3Schools have a nice article on this subject.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in functions.

Put your functions in the head section, this way they are all in one place, and they do not interfere with page content.

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page content, it should be placed in the body section.

PHP Parse error: syntax error, unexpected T_PUBLIC

You can remove public keyword from your functions, because, you have to define a class in order to declare public, private or protected function

Styling Google Maps InfoWindow

I used the following code to apply some external CSS:

boxText = document.createElement("html");
boxText.innerHTML = "<head><link rel='stylesheet' href='style.css'/></head><body>[some html]<body>";

infowindow.setContent(boxText);
infowindow.open(map, marker);

grep --ignore-case --only

If your grep -i does not work then try using tr command to convert the the output of your file to lower case and then pipe it into standard grep with whatever you are looking for. (it sounds complicated but the actual command which I have provided for you is not !).

Notice the tr command does not change the content of your original file, it just converts it just before it feeds it into grep.

1.here is how you can do this on a file

tr '[:upper:]' '[:lower:]' <your_file.txt|grep what_ever_you_are_searching_in_lower_case

2.or in your case if you are just echoing something

echo "ABC"|tr '[:upper:]' '[:lower:]' | grep abc

Run php script as daemon process

If you can - grab a copy of Advanced Programming in the UNIX Environment. The entire chapter 13 is devoted to daemon programming. Examples are in C, but all the function you need have wrappers in PHP (basically the pcntl and posix extensions).

In a few words - writing a daemon (this is posible only on *nix based OS-es - Windows uses services) is like this:

  1. Call umask(0) to prevent permission issues.
  2. fork() and have the parent exit.
  3. Call setsid().
  4. Setup signal processing of SIGHUP (usually this is ignored or used to signal the daemon to reload its configuration) and SIGTERM (to tell the process to exit gracefully).
  5. fork() again and have the parent exit.
  6. Change the current working dir with chdir().
  7. fclose() stdin, stdout and stderr and don't write to them. The corrrect way is to redirect those to either /dev/null or a file, but I couldn't find a way to do it in PHP. It is possible when you launch the daemon to redirect them using the shell (you'll have to find out yourself how to do that, I don't know :).
  8. Do your work!

Also, since you are using PHP, be careful for cyclic references, since the PHP garbage collector, prior to PHP 5.3, has no way of collecting those references and the process will memory leak, until it eventually crashes.

What is the maximum length of a String in PHP?

http://php.net/manual/en/language.types.string.php says:

Note: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum)

In PHP 5.x, strings were limited to 231-1 bytes, because internal code recorded the length in a signed 32-bit integer.


You can slurp in the contents of an entire file, for instance using file_get_contents()

However, a PHP script has a limit on the total memory it can allocate for all variables in a given script execution, so this effectively places a limit on the length of a single string variable too.

This limit is the memory_limit directive in the php.ini configuration file. The memory limit defaults to 128MB in PHP 5.2, and 8MB in earlier releases.

If you don't specify a memory limit in your php.ini file, it uses the default, which is compiled into the PHP binary. In theory you can modify the source and rebuild PHP to change this default value.

If you specify -1 as the memory limit in your php.ini file, it stop checking and permits your script to use as much memory as the operating system will allocate. This is still a practical limit, but depends on system resources and architecture.


Re comment from @c2:

Here's a test:

<?php

// limit memory usage to 1MB 
ini_set('memory_limit', 1024*1024);

// initially, PHP seems to allocate 768KB for basic operation
printf("memory: %d\n",  memory_get_usage(true));

$str = str_repeat('a',  255*1024);
echo "Allocated string of 255KB\n";

// now we have allocated all of the 1MB of memory allowed
printf("memory: %d\n",  memory_get_usage(true));

// going over the limit causes a fatal error, so no output follows
$str = str_repeat('a',  256*1024);
echo "Allocated string of 256KB\n";
printf("memory: %d\n",  memory_get_usage(true));

Spring Boot JPA - configuring auto reconnect

I have similar problem. Spring 4 and Tomcat 8. I solve the problem with Spring configuration

<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
    <property name="initialSize" value="10" />
    <property name="maxActive" value="25" />
    <property name="maxIdle" value="20" />
    <property name="minIdle" value="10" />
     ...
    <property name="testOnBorrow" value="true" />
    <property name="validationQuery" value="SELECT 1" />
 </bean>

I have tested. It works well! This two line does everything in order to reconnect to database:

<property name="testOnBorrow" value="true" />
<property name="validationQuery" value="SELECT 1" />

How to give ASP.NET access to a private key in a certificate in the certificate store?

Complementing the answers this is a guide to find the private key of the certificate and add the permissions.

This is the guide to get FindPrivateKey.exe found in the guide for find the private key of the certificate.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

FileNotFoundError: [Errno 2] No such file or directory

You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.

Try using the exact, or absolute, path.

How to select clear table contents without destroying the table?

I use this code to remove my data but leave the formulas in the top row. It also removes all rows except for the top row and scrolls the page up to the top.

Sub CleanTheTable()
    Application.ScreenUpdating = False
    Sheets("Data").Select
    ActiveSheet.ListObjects("TestTable").HeaderRowRange.Select
    'Remove the filters if one exists.
    If ActiveSheet.FilterMode Then
    Selection.AutoFilter
    End If
    'Clear all lines but the first one in the table leaving formulas for the next go round.
    With Worksheets("Data").ListObjects("TestTable")
    .Range.AutoFilter
    On Error Resume Next
    .DataBodyRange.Offset(1).Resize(.DataBodyRange.Rows.Count - 1, .DataBodyRange.Columns.Count).Rows.Delete
    .DataBodyRange.Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
    ActiveWindow.SmallScroll Down:=-10000

    End With
Application.ScreenUpdating = True
End Sub

How to generate random positive and negative numbers in Java

([my double-compatible primitive type here])(Math.random() * [my max value here] * (Math.random() > 0.5 ? 1 : -1))

example:

// need a random number between -500 and +500
long myRandomLong = (long)(Math.random() * 500 * (Math.random() > 0.5 ? 1 : -1));

Best way to test for a variable's existence in PHP; isset() is clearly broken

If the variable you are checking would be in the global scope you could do:

array_key_exists('v', $GLOBALS) 

Round a divided number in Bash

If you have integer division of positive numbers which rounds toward zero, then you can add one less than the divisor to the dividend to make it round up.

That is to say, replace X / Y with (X + Y - 1) / Y.

Proof:

  • Case 1: X = k * Y (X is integer multiple of Y): In this case, we have (k * Y + Y - 1) / Y, which splits into (k * Y) / Y + (Y - 1) / Y. The (Y - 1)/Y part rounds to zero, and we are left with a quotient of k. This is exactly what we want: when the inputs are divisible, we want the adjusted calculation to still produce the correct exact quotient.

  • Case 2: X = k * Y + m where 0 < m < Y (X is not a multiple of Y). In this case we have a numerator of k * Y + m + Y - 1, or k * Y + Y + m - 1, and we can write the division out as (k * Y)/Y + Y/Y + (m - 1)/Y. Since 0 < m < Y, 0 <= m - 1 < Y - 1, and so the last term (m - 1)/Y goes to zero. We are left with (k * Y)/Y + Y/Y which work out to k + 1. This shows that the behavior rounds up. If we have an X which is a k multiple of Y, if we add just 1 to it, the division rounds up to k + 1.

But this rounding is extremely opposite; all inexact divisions go away from zero. How about something in between?

That can be achieved by "priming" the numerator with Y/2. Instead of X/Y, calculate (X+Y/2)/Y. Instead of proof, let's go empirical on this one:

$ round()
> {
>   echo $((($1 + $2/2) / $2))
> }
$ round 4 10
0
$ round 5 10
1
$ round 6 10
1
$ round 9 10
1
$ round 10 10
1
$ round 14 10
1
$ round 15 10
2

Whenever the divisor is an even, positive number, if the numerator is congruent to half that number, it rounds up, and rounds down if it is one less than that.

For instance, round 6 12 goes to 1, as do all values which are equal to 6, modulo 12, like 18 (which goes to 2) and so on. round 5 12 goes down to 0.

For odd numbers, the behavior is correct. None of the exact rational numbers are midway between two consecutive multiples. For instance, with a denominator of 11 we have 5/11 < 5.5/11 (exact middle) < 6/11; and round 5 11 rounds down, whereas round 6 11 rounds up.

How to block calls in android

You could just re-direct specific numbers in your contacts to your voice-mail. That's already supported.

Otherwise I guess the documentation for 'Contacts' would be a good place to start looking.

Warning: Cannot modify header information - headers already sent by ERROR

Check the document encoding.

I had this same problem. I develop on Windows XP using Notepad++ and WampServer to run Apache locally and all was fine. After uploading to hosting provider that uses Apache on Unix I got this error. I had no extra PHP tags or white-space from extra lines after the closing tag.

For me this was caused by the encoding of the text documents. I used the "Convert to UTF-8 without BOM" option in Notepad++(under Encoding tab) and reloaded to the web server. Problem fixed, no code/editing changes required.

<button> background image

Try changing your CSS to this

button #rock {
    background: url('img/rock.png') no-repeat;
}

...provided that the image is in that place

Java 8 LocalDate Jackson format

Since LocalDateSerializer turns it into "[year,month,day]" (a json array) rather than "year-month-day" (a json string) by default, and since I don't want to require any special ObjectMapper setup (you can make LocalDateSerializer generate strings if you disable SerializationFeature.WRITE_DATES_AS_TIMESTAMPS but that requires additional setup to your ObjectMapper), I use the following:

imports:

import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;

code:

// generates "yyyy-MM-dd" output
@JsonSerialize(using = ToStringSerializer.class)
// handles "yyyy-MM-dd" input just fine (note: "yyyy-M-d" format will not work)
@JsonDeserialize(using = LocalDateDeserializer.class)
private LocalDate localDate;

And now I can just use new ObjectMapper() to read and write my objects without any special setup.

UIScrollView scroll to bottom programmatically

valdyr, hope this will help you:

CGPoint bottomOffset = CGPointMake(0, [textView contentSize].height - textView.frame.size.height);

if (bottomOffset.y > 0)
 [textView setContentOffset: bottomOffset animated: YES];

Getting a count of objects in a queryset in django

Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

Item.objects.values("contest").annotate(Count("id"))

I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

rake assets:precompile RAILS_ENV=production not working as required

Have you added this gem to your gemfile?

# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'

move that gem out of assets group and then run bundle again, I hope that would help!

jquery disable form submit on enter

$(document).on('keyup keypress', 'form input[type="text"]', function(e) {
  if(e.which == 13) {
    e.preventDefault();
    return false;
  }
});

This solution works on all forms on website (also on forms inserted with ajax), preventing only Enters in input texts. Place it in a document ready function, and forget this problem for a life.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

Initializing a member array in constructor initializer

  1. How can I do what I want to do (that is, initialize an array in a constructor (not assigning elements in the body)). Is it even possible?

Yes. It's using a struct that contains an array. You say you already know about that, but then I don't understand the question. That way, you do initialize an array in the constructor, without assignments in the body. This is what boost::array does.

Does the C++03 standard say anything special about initializing aggregates (including arrays) in ctor initializers? Or the invalidness of the above code is a corollary of some other rules?

A mem-initializer uses direct initialization. And the rules of clause 8 forbid this kind of thing. I'm not exactly sure about the following case, but some compilers do allow it.

struct A {
  char foo[6];
  A():foo("hello") { } /* valid? */
};

See this GCC PR for further details.

Do C++0x initializer lists solve the problem?

Yes, they do. However your syntax is invalid, I think. You have to use braces directly to fire off list initialization

struct A {
  int foo[3];
  A():foo{1, 2, 3} { }
  A():foo({1, 2, 3}) { } /* invalid */
};

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

This may be a hack:

as in question In Unix / Bash, is "xargs -p" a good way to prompt for confirmation before running any command?

we can using xargs to do the job:

echo ssh://[email protected]//somepath/morepath | xargs -p hg push

of course, this will be set as an alias, like hgpushrepo

Example:

$ echo foo | xargs -p ls -l
ls -l foo?...y
-rw-r--r--  1 mikelee    staff  0 Nov 23 10:38 foo

$ echo foo | xargs -p ls -l
ls -l foo?...n

$

Set Locale programmatically

For those who tried everything but not not working. Please check that if you set darkmode with AppCompatDelegate.setDefaultNightMode and the system is not dark, then Configuration.setLocale will not work above Andorid 7.0.

Add this code in your every activity to solve this issue:

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
  if (overrideConfiguration != null) {
    val uiMode = overrideConfiguration.uiMode
    overrideConfiguration.setTo(baseContext.resources.configuration)
    overrideConfiguration.uiMode = uiMode
  }
  super.applyOverrideConfiguration(overrideConfiguration)
}

Install Application programmatically on Android

Another solution that doesn't not require to hard-code the receiving app and that is therefore safer:

Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData( Uri.fromFile(new File(pathToApk)) );
startActivity(intent);

Styling HTML email for Gmail

Use inline styles for everything. This site will convert your classes to inline styles: http://premailer.dialect.ca/

jQuery UI Sortable, then write order into a database

Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/ where new order is saved in some HMTL element. Then you submit the form with this data to some PHP script, and iterate trough it with for loop.

Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.

400 vs 422 response to POST of data

To reflect the status as of 2015:

Behaviorally both 400 and 422 response codes will be treated the same by clients and intermediaries, so it actually doesn't make a concrete difference which you use.

However I would expect to see 400 currently used more widely, and furthermore the clarifications that the HTTPbis spec provides make it the more appropriate of the two status codes:

  • The HTTPbis spec clarifies the intent of 400 to not be solely for syntax errors. The broader phrase "indicates that the server cannot or will not process the request due to something which is perceived to be a client error" is now used.
  • 422 is specifically a WebDAV extension, and is not referenced in RFC 2616 or in the newer HTTPbis specification.

For context, HTTPbis is a revision of the HTTP/1.1 spec that attempts to clarify areas that were unclear or inconsistent. Once it has reached approved status it will supersede RFC2616.

iOS 7 App Icons, Launch images And Naming Convention While Keeping iOS 6 Icons

You should use Asset Catalog:

I have investigated, how we can use Asset Catalog; Now it seems to be easy for me. I want to show you steps to add icons and splash in asset catalog.

Note: No need to make any entry in info.plist file :) And no any other configuration.

In below image, at right side, you will see highlighted area, where you can mention which icons you need. In case of mine, i have selected first four checkboxes; As its for my app requirements. You can select choices according to your requirements.

enter image description here

Now, see below image. As you will select any App icon then you will see its detail at right side selected area. It will help you to upload correct resolution icon. enter image description here

If Correct resolution image will not be added then following warning will come. Just upload the image with correct resolution. enter image description here

After uploading all required dimensions, you shouldn't get any warning. enter image description here