Programs & Examples On #Oql

OQL stands for "Object Query Language". It is defined by the Object Data Management Group (ODMG).

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key


Encrypted Private Key

Proc-Type: 4,ENCRYPTED


-----BEGIN X509 CRL-----
-----END X509 CRL-----










-----BEGIN PKCS7-----
-----END PKCS7-----





Elliptic Curve


PGP Private Key


PGP Public Key


OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

this post was made a while ago, but it provides an answer that did not solve the problem regarding reaching the limit of requests in an iteration for me, so I publish this, to help who else has not served.

My environment happened in Ionic 3.

Instead of making a "pause" in the iteration, I ocurred the idea of ??iterating with a timer, this timer has the particularity of executing the code that would go in the iteration, but will run every so often until it is reached the maximum count of the "Array" in which we want to iterate.

In other words, we will consult the Google API in a certain time so that it does not exceed the limit allowed in milliseconds.

// Code to start the timer
    this.count= 0;
    let loading = this.loadingCtrl.create({
      content: 'Buscando los mejores servicios...'
    this.interval = setInterval(() => this.getDistancias(loading), 40);
// Function that runs the timer, that is, query Google API
    if(this.count>= this.datos.length){
    } else {
      var sucursal = this.datos[this.count];
      this.calcularDistancia(this.posicion, new LatLng(parseFloat(sucursal.position.latitude),parseFloat(sucursal.position.longitude)),sucursal.codigo).then(distancia => {
    }).catch(error => {
    this.count += 1;
  calcularDistancia(miPosicion, markerPosicion, codigo){
    return new Promise(async (resolve,reject) => {
      var service = new google.maps.DistanceMatrixService;
      var distance;
      var duration;
        origins: [miPosicion, 'salida'],
        destinations: [markerPosicion, 'llegada'],
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
      }, function(response, status){
        if (status == 'OK') {
          var originList = response.originAddresses;
          var destinationList = response.destinationAddresses;
            if(response != null && response != undefined){
              distance = response.rows[0].elements[0].distance.value;
              duration = response.rows[0].elements[0].duration.text;
            console.log("ERROR GOOGLE");

I hope this helps!

I'm sorry for my English, I hope it's not an inconvenience, I had to use the Google translator.

Regards, Leandro.

Create dataframe from a matrix

Using dplyr and tidyr:


df <- as_data_frame(mat) %>%      # convert the matrix to a data frame
  gather(name, val, C_0:C_1) %>%  # convert the data frame from wide to long
  select(name, time, val)         # reorder the columns

# A tibble: 6 x 3
   name  time   val
  <chr> <dbl> <dbl>
1   C_0   0.0   0.1
2   C_0   0.5   0.2
3   C_0   1.0   0.3
4   C_1   0.0   0.3
5   C_1   0.5   0.4
6   C_1   1.0   0.5

Regex: ignore case sensitivity

You can practice Regex In Visual Studio and Visual Studio Code using find/replace.

You need to select both Match Case and Regular Expressions for regex expressions with case. Else [A-Z] won't work.enter image description here

Visual Studio 2019 Community

How many bytes in a JavaScript string?

You can use the Blob to get the string size in bytes.


  new Blob(['']).size,                             // 4_x000D_
  new Blob(['']).size,                             // 4_x000D_
  new Blob(['']).size,                           // 8_x000D_
  new Blob(['']).size,                           // 8_x000D_
  new Blob(['I\'m a string']).size,                  // 12_x000D_
  // from Premasagar correction of Lauri's answer for_x000D_
  // strings containing lone characters in the surrogate pair range:_x000D_
  new Blob([String.fromCharCode(55555)]).size,       // 3_x000D_
  new Blob([String.fromCharCode(55555, 57000)]).size // 4 (not 6)_x000D_

Compare two files in Visual Studio

In Visual Studio 2012, 2013, 2015, you can also do it with Web Essentials, just right click the files and from context menu > Web Essential >> Diff selected files:

Edit: It's now available as a separate extension

enter image description here

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
    Image1.Width= imageWidth;

Android update activity UI from service

Callback from service to activity to update UI.
ResultReceiver receiver = new ResultReceiver(new Handler()) {
    protected void onReceiveResult(int resultCode, Bundle resultData) {
        //process results or update UI

Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

How do I negate a condition in PowerShell?

if you don't like the double brackets or you don't want to write a function, you can just use a variable.

$path = Test-Path C:\Code
if (!$path) {
    write "it doesn't exist!"

How to randomize two ArrayLists in the same fashion?

Use Collections.shuffle() twice, with two Random objects initialized with the same seed:

long seed = System.nanoTime();
Collections.shuffle(fileList, new Random(seed));
Collections.shuffle(imgList, new Random(seed));

Using two Random objects with the same seed ensures that both lists will be shuffled in exactly the same way. This allows for two separate collections.

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I had a similar issue using Apache 2.4 and PHP 7.

My client sent a lot of requests when refreshing (hard reloading) my application page in the browser and every time some of the last requests resulted in this error in console:


It turned out that my client was reaching the maximum amount of threads that was allowed. The threads exceeding this configured ceiling are simply not handled by Apache at all resulting in the connection reset error response.

The amount of threads can be easily raised by setting the ThreadsPerChild value for the module in question.
The easiest way to make such change is to uncomment the Server-pool management config file conf/extra/httpd-mpm.conf and then editing the preset values in the file to desired values.

1) Uncomment the Server-pool management file

# Server-pool management (MPM specific)
Include conf/extra/httpd-mpm.conf

2) Open and edit the file conf/extra/httpd-mpm.conf and raise the amount of threads

In my case I had to change the threads for the mpm_winnt_module:

# raised the amount of threads for mpm_winnt_module to 250
<IfModule mpm_winnt_module>
    ThreadsPerChild        250
    MaxConnectionsPerChild   0

A comprehensive explanation on these Server-pool management configuration settings can be found in this post on StackOverflow.

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

This will do what you want:

INSERT INTO table2 (st_id,uid,changed,status,assign_status)
SELECT st_id,from_uid,now(),'Pending','Assigned'
FROM table1

If you want to include all rows from table1. Otherwise you can add a WHERE statement to the end if you want to add only a subset of table1.

I hope this helps.

What is the "right" JSON date format?

There is only one correct answer to this and most systems get it wrong. Number of milliseconds since epoch, aka a 64 bit integer. Time Zone is a UI concern and has no business in the app layer or db layer. Why does your db care what time zone something is, when you know it's going to store it as a 64 bit integer then do the transformation calculations.

Strip out the extraneous bits and just treat dates as numbers up to the UI. You can use simple arithmetic operators to do queries and logic.

Getting Http Status code number (200, 301, 404, etc.) from HttpWebRequest and HttpWebResponse


HttpStatusCode (the type of response.StatusCode) is an enumeration where the values of the members match the HTTP status codes, e.g.

public enum HttpStatusCode
    Moved = 301,
    OK = 200,
    Redirect = 302,

NULL values inside NOT IN clause

In A, 3 is tested for equality against each member of the set, yielding (FALSE, FALSE, TRUE, UNKNOWN). Since one of the elements is TRUE, the condition is TRUE. (It's also possible that some short-circuiting takes place here, so it actually stops as soon as it hits the first TRUE and never evaluates 3=NULL.)

In B, I think it is evaluating the condition as NOT (3 in (1,2,null)). Testing 3 for equality against the set yields (FALSE, FALSE, UNKNOWN), which is aggregated to UNKNOWN. NOT ( UNKNOWN ) yields UNKNOWN. So overall the truth of the condition is unknown, which at the end is essentially treated as FALSE.

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

How to upload a file and JSON data in Postman?

At Back-end part

Rest service in Controller will have mixed @RequestPart and MultipartFile to serve such Multipart + JSON request.

@RequestMapping(value = "/executesampleservice", method = RequestMethod.POST,
consumes = {"multipart/form-data"})

public boolean yourEndpointMethod(
    @RequestPart("properties") @Valid ConnectionProperties properties,
    @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return projectService.executeSampleService(properties, file);

At front-end :

formData = new FormData();

formData.append("file", document.forms[formName].file.files[0]);
formData.append('properties', new Blob([JSON.stringify({
            "name": "root",
            "password": "root"                    
        })], {
            type: "application/json"

See in the image (POSTMAN request):

Click to view Postman request in form data for both file and json

URL Encode a string in jQuery for an AJAX request

encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:

    cache: false,
    type: "POST",
    url: "",
    data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
    dataType: "HTML",
    success: function (data) {
    error: function (xhr, ajaxOptions, thrownError) {

How to see tomcat is running or not

open http://localhost:8080/ in browser, if you get tomcat home page. it means tomcat is running

Comparing date part only without comparing time in JavaScript

Make sure you construct userDate with a 4 digit year as setFullYear(10, ...) !== setFullYear(2010, ...).

How to show progress bar while loading, using ajax

try this it may help you

  beforeSend: function(  ) {
    // load your loading fiel here
  .done(function( data ) {
    //hide your loading file here

How can I specify the required Node.js version in package.json?

A Mocha test case example:

describe('Check version of node', function () {
    it('Should test version assert', async function () {

            var version = process.version;
            var check = parseFloat(version.substr(1,version.length)) > 12.0;
            console.log("version: "+version);
            console.log("check: " +check);         
            assert.equal(check, true);

How to make an Android device vibrate? with different frequency?

Above answers are perfect. However I wanted to vibrate my app exactly twice on button click and this small information is missing here, hence posting for future readers like me. :)

We have to follow as mentioned above and the only change will be in the vibrate pattern as below,

long[] pattern = {0, 100, 1000, 300};
v.vibrate(pattern, -1); //-1 is important

This will exactly vibrate twice. As we already know

  1. 0 is for delay
  2. 100 says vibrate for 100ms for the first time
  3. next comes delay of 1000ms
  4. and post that vibrate again for 300ms

One can go on and on mentioning delay and vibration alternatively (e.g. 0, 100, 1000, 300, 1000, 300 for 3 vibrations and so on..) but remember @Dave's word use it responsibly. :)

Also note here that the repeat parameter is set to -1 which means the vibration will happen exactly as mentioned in the pattern. :)

C++ STL Vectors: Get iterator from index?

way mentioned by @dirkgently ( v.begin() + index ) nice and fast for vectors

but std::advance( v.begin(), index ) most generic way and for random access iterators works constant time too.

differences in usage:

std::vector<>::iterator it = ( v.begin() + index );


std::vector<>::iterator it = v.begin();
std::advance( it, index );

added after @litb notes.

Angular cookies

For read a cookie i've made little modifications of the Miquel version that doesn't work for me:

getCookie(name: string) {
        let ca: Array<string> = document.cookie.split(';');
        let cookieName = name + "=";
        let c: string;

        for (let i: number = 0; i < ca.length; i += 1) {
            if (ca[i].indexOf(name, 0) > -1) {
                c = ca[i].substring(cookieName.length +1, ca[i].length);
                console.log("valore cookie: " + c);
                return c;
        return "";

How to automatically generate N "distinct" colors?

If N is big enough, you're going to get some similar-looking colors. There's only so many of them in the world.

Why not just evenly distribute them through the spectrum, like so:

IEnumerable<Color> CreateUniqueColors(int nColors)
    int subdivision = (int)Math.Floor(Math.Pow(nColors, 1/3d));
    for(int r = 0; r < 255; r += subdivision)
        for(int g = 0; g < 255; g += subdivision)
            for(int b = 0; b < 255; b += subdivision)
                yield return Color.FromArgb(r, g, b);

If you want to mix up the sequence so that similar colors aren't next to each other, you could maybe shuffle the resulting list.

Am I underthinking this?

Change the project theme in Android Studio?

Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles

Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.enter image description here

Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

  • Theme.Holo for a "dark" theme.
  • Theme.Holo.Light for a "light" theme.

When using the Support Library, you must instead use the Theme.AppCompat themes:

  • Theme.AppCompat for the "dark" theme.
  • Theme.AppCompat.Light for the "light" theme.
  • Theme.AppCompat.Light.DarkActionBar for the light theme with a dark action bar.


JavaScript alert not working in Android WebView

The following code will work:

private WebView mWebView;
final Activity activity = this;

// private Button b;
public void onCreate(Bundle savedInstanceState) {
    mWebView = (WebView) findViewById(;
    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 1000);


java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Some Google tooling such as GWT has an embedded version of commons-codec with a pre-1.4 Base64 class. You may need to make such tooling JARs inaccessible to your code by refactoring your project such that only the parts of your code that need that tooling can see the dependency.

How to increase the max upload file size in ASP.NET?

I've the same problem in a win 2008 IIS server, I've solved the problem adding this configuration in the web.config:

    <httpRuntime executionTimeout="3600" maxRequestLength="102400" 
     appRequestQueueLimit="100" requestValidationMode="2.0"

The requestLengthDiskThreshold by default is 80000 bytes so it's too small for my application. requestLengthDiskThreshold is measured in bytes and maxRequestLength is expressed in Kbytes.

The problem is present if the application is using a System.Web.UI.HtmlControls.HtmlInputFile server component. Increasing the requestLengthDiskThreshold is necessary to solve it.

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;

    return true;

What is the proof of of (N–1) + (N–2) + (N–3) + ... + 1= N*(N–1)/2

I know that we are (n-1) * (n times), but why the division by 2?

It's only (n - 1) * n if you use a naive bubblesort. You can get a significant savings if you notice the following:

  • After each compare-and-swap, the largest element you've encountered will be in the last spot you were at.

  • After the first pass, the largest element will be in the last position; after the kth pass, the kth largest element will be in the kth last position.

Thus you don't have to sort the whole thing every time: you only need to sort n - 2 elements the second time through, n - 3 elements the third time, and so on. That means that the total number of compare/swaps you have to do is (n - 1) + (n - 2) + .... This is an arithmetic series, and the equation for the total number of times is (n - 1)*n / 2.

Example: if the size of the list is N = 5, then you do 4 + 3 + 2 + 1 = 10 swaps -- and notice that 10 is the same as 4 * 5 / 2.

how to draw directed graphs using networkx in python?

You need to use a directed graph instead of a graph, i.e.

G = nx.DiGraph()

Then, create a list of the edge colors you want to use and pass those to nx.draw (as shown by @Marius).

Putting this all together, I get the image below. Still not quite the other picture you show (I don't know where your edge weights are coming from), but much closer! If you want more control of how your output graph looks (e.g. get arrowheads that look like arrows), I'd check out NetworkX with Graphviz.

enter image description here

Get Substring - everything before certain char

The LINQy way

String.Concat( "223232-1.jpg".TakeWhile(c => c != '-') )

(But, you do need to test for null ;)

What are major differences between C# and Java?


With Java generics, you don't actually get any of the execution efficiency that you get with .NET because when you compile a generic class in Java, the compiler takes away the type parameter and substitutes Object everywhere. For instance if you have a Foo<T> class the java compiler generates Byte Code as if it was Foo<Object>. This means casting and also boxing/unboxing will have to be done in the "background".

I've been playing with Java/C# for a while now and, in my opinion, the major difference at the language level are, as you pointed, delegates.



AThe CROSS JOIN is meant to generate a Cartesian Product.

A Cartesian Product takes two sets A and B and generates all possible permutations of pair records from two given sets of data.

For instance, assuming you have the following ranks and suits database tables:

The ranks and suits tables

And the ranks has the following rows:

| name  | symbol | rank_value |
| Ace   | A      | 14         |
| King  | K      | 13         |
| Queen | Q      | 12         |
| Jack  | J      | 11         |
| Ten   | 10     | 10         |
| Nine  | 9      |  9         |

While the suits table contains the following records:

| name    | symbol |
| Club    | ?      |
| Diamond | ?      |
| Heart   | ?      |
| Spade   | ?      |

As CROSS JOIN query like the following one:

   r.symbol AS card_rank,
   s.symbol AS card_suit
   ranks r
   suits s

will generate all possible permutations of ranks and suites pairs:

| card_rank | card_suit |
| A         | ?         |
| A         | ?         |
| A         | ?         |
| A         | ?         |
| K         | ?         |
| K         | ?         |
| K         | ?         |
| K         | ?         |
| Q         | ?         |
| Q         | ?         |
| Q         | ?         |
| Q         | ?         |
| J         | ?         |
| J         | ?         |
| J         | ?         |
| J         | ?         |
| 10        | ?         |
| 10        | ?         |
| 10        | ?         |
| 10        | ?         |
| 9         | ?         |
| 9         | ?         |
| 9         | ?         |
| 9         | ?         |


On the other hand, INNER JOIN does not return the Cartesian Product of the two joining data sets.

Instead, the INNER JOIN takes all elements from the left-side table and matches them against the records on the right-side table so that:

  • if no record is matched on the right-side table, the left-side row is filtered out from the result set
  • for any matching record on the right-side table, the left-side row is repeated as if there was a Cartesian Product between that record and all its associated child records on the right-side table.

For instance, assuming we have a one-to-many table relationship between a parent post and a child post_comment tables that look as follows:

One-to-many table relationship

Now, if the post table has the following records:

| id | title     |
| 1  | Java      |
| 2  | Hibernate |
| 3  | JPA       |

and the post_comments table has these rows:

| id | review    | post_id |
| 1  | Good      | 1       |
| 2  | Excellent | 1       |
| 3  | Awesome   | 2       |

An INNER JOIN query like the following one:

SELECT AS post_id,
   p.title AS post_title,  AS review
FROM post p
INNER JOIN post_comment pc ON pc.post_id =

is going to include all post records along with all their associated post_comments:

| post_id | post_title | review    |
| 1       | Java       | Good      |
| 1       | Java       | Excellent |
| 2       | Hibernate  | Awesome   |

Basically, you can think of the INNER JOIN as a filtered CROSS JOIN where only the matching records are kept in the final result set.

Why is it string.join(list) instead of list.join(string)?

Both are not nice.

string.join(xs, delimit) means that the string module is aware of the existence of a list, which it has no business knowing about, since the string module only works with strings.

list.join(delimit) is a bit nicer because we're so used to strings being a fundamental type(and lingually speaking, they are). However this means that join needs to be dispatched dynamically because in the arbitrary context of a.split("\n") the python compiler might not know what a is, and will need to look it up(analogously to vtable lookup), which is expensive if you do it a lot of times.

if the python runtime compiler knows that list is a built in module, it can skip the dynamic lookup and encode the intent into the bytecode directly, whereas otherwise it needs to dynamically resolve "join" of "a", which may be up several layers of inheritence per call(since between calls, the meaning of join may have changed, because python is a dynamic language).

sadly, this is the ultimate flaw of abstraction; no matter what abstraction you choose, your abstraction will only make sense in the context of the problem you're trying to solve, and as such you can never have a consistent abstraction that doesn't become inconsistent with underlying ideologies as you start gluing them together without wrapping them in a view that is consistent with your ideology. Knowing this, python's approach is more flexible since it's cheaper, it's up to you to pay more to make it look "nicer", either by making your own wrapper, or your own preprocessor.

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

How do I create a Java string from the contents of a file?

A flexible solution using IOUtils from Apache commons-io in combination with StringWriter:

Reader input = new FileReader();
StringWriter output = new StringWriter();
try {
  IOUtils.copy(input, output);
} finally {
String fileContents = output.toString();

It works with any reader or input stream (not just with files), for example when reading from a URL.

Static array vs. dynamic array in C++

Static arrays are allocated memory at compile time and the memory is allocated on the stack. Whereas, the dynamic arrays are allocated memory at the runtime and the memory is allocated from heap.

int arr[] = { 1, 3, 4 }; // static integer array.   
int* arr = new int[3]; // dynamic integer array.

Linux/Unix command to determine if process is running?

The simpliest way is to use ps and grep:

running=`ps ax | grep -v grep | grep $command | wc -l`
if [ running -gt 0 ]; then
    echo "Command is running"
    echo "Command is not running"

If your command has some command arguments, then you can also put more 'grep cmd_arg1' after 'grep $command' to filter out other possible processes that you are not interested in.

Example: show me if any java process with supplied argument:

is running

ps ax | grep -v grep | grep java | grep | wc -l

How to decode JWT Token?

You need the secret string which was used to generate encrypt token. This code works for me:

protected string GetName(string token)
        string secret = "this is a string used for encrypt and decrypt token"; 
        var key = Encoding.ASCII.GetBytes(secret);
        var handler = new JwtSecurityTokenHandler();
        var validations = new TokenValidationParameters
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        var claims = handler.ValidateToken(token, validations, out var tokenSecure);
        return claims.Identity.Name;

Adb Devices can't find my phone

I have a ZTE Crescent phone (Orange San Francisco II).

When I connect the phone to the USB a disk shows up in OS X named 'ZTE_USB_Driver'.

Running adb devices displays no connected devices. But after I eject the 'ZTE_USB_Driver' disk from OS X, and run adb devices again the phone shows up as connected.

Why is it OK to return a 'vector' from a function?

I think you are referring to the problem in C (and C++) that returning an array from a function isn't allowed (or at least won't work as expected) - this is because the array return will (if you write it in the simple form) return a pointer to the actual array on the stack, which is then promptly removed when the function returns.

But in this case, it works, because the std::vector is a class, and classes, like structs, can (and will) be copied to the callers context. [Actually, most compilers will optimise out this particular type of copy using something called "Return Value Optimisation", specifically introduced to avoid copying large objects when they are returned from a function, but that's an optimisation, and from a programmers perspective, it will behave as if the assignment constructor was called for the object]

As long as you don't return a pointer or a reference to something that is within the function returning, you are fine.

How do I run a PowerShell script when the computer starts?


1. Start powershell with the "Run as Administrator" option

2. Enable running unsigned scripts with:

set-executionpolicy remotesigned

3. prepare your powershell script and know its path:

$path = "C:\Users\myname\myscript.ps1"


1. setup a trigger, see also New-JobTrigger (PSScheduledJob) - PowerShell | Microsoft Docs

$trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30

2. register a scheduled job, see also Register-ScheduledJob (PSScheduledJob) - PowerShell | Microsoft Docs

Register-ScheduledJob -Trigger $trigger -FilePath $path -Name MyScheduledJob

you can check it with Get-ScheduledJob -Name MyScheduledJob

3. Reboot Windows (restart /r) and check the result with:

Get-Job -name MyScheduledJob

see also Get-Job (Microsoft.PowerShell.Core) - PowerShell | Microsoft Docs


  1. How to enable execution of PowerShell scripts? - Super User
  2. Use PowerShell to Create Job that Runs at Startup | Scripting Blog

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

this main works in both linux and windows - found it through trial and error and help from others so can't explain why it works, it just does int main(int argc, char** argv)

no tchar.h necessary

and here is the same answer in Wikipedia Main function

Join/Where with LINQ and Lambda

Posting because when I started LINQ + EntityFramework, I stared at these examples for a day.

If you are using EntityFramework, and you have a navigation property named Meta on your Post model object set up, this is dirt easy. If you're using entity and don't have that navigation property, what are you waiting for?

  .Where(post => post.ID == id)
  .Select(post => new { post, post.Meta });

If you're doing code first, you'd set up the property thusly:

class Post {
  public int ID {get; set}
  public int MetaID { get; set; }
  public virtual Meta Meta {get; set;}

Simplest JQuery validation rules example

The input in the markup is missing "type", the input (text I assume) has the attribute name="name" and ID="cname", the provided code by Ayo calls the input named "cname"* where it should be "name".

Eclipse: stop code from running (java)

The easiest way to do this is to click on the Terminate button(red square) in the console:

enter image description here

How to get ASCII value of string in C#


string value = "9quali52ty3";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

You now have an array of the ASCII value of the bytes. I got the following:

57 113 117 97 108 105 53 50 116 121 51

CSS override rules and specificity

The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.

To make the second one override the first one, you can make more specific by adding information of it's parents:

table.rule1 tr td.rule2 {
    background-color: #ffff00;

Here is a nice article for more information on selector precedence.

How to pass arguments to Shell Script through docker run

Use the same

echo $1

Build the image using the existing Dockerfile:

docker build -t test .

Run the image with arguments abc or xyz or something else.

docker run -ti --rm test / abc

docker run -ti --rm test / xyz

ab load testing

Load testing your API by using just ab is not enough. However, I think it's a great tool to give you a basic idea how your site is performant.

If you want to use the ab command in to test multiple API endpoints, with different data, all at the same time in background, you need to use "nohup" command. It runs any command even when you close the terminal.

I wrote a simple script that automates the whole process, feel free to use it:

Calling onclick on a radiobutton list using javascript

The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.

The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.

This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.

Get controller and action name from within controller?

You can get controller name or action name from action like any variable. They are just special (controller and action) and already defined so you do not need to do anything special to get them except telling you need them.

public string Index(string controller,string action)
     var names=string.Format("Controller : {0}, Action: {1}",controller,action);
     return names;

Or you can include controller , action in your models to get two of them and your custom data.

public class DtoModel
        public string Action { get; set; }
        public string Controller { get; set; }
        public string Name { get; set; }

public string Index(DtoModel baseModel)
        var names=string.Format("Controller : {0}, Action: {1}",baseModel.Controller,baseModel.Action);
        return names;

nano error: Error opening terminal: xterm-256color

somehow and sometimes "terminfo" folder comes corrupted after a fresh installation. i don't know why, but the problem can be solved in this way:

1. Download Lion Installer from the App Store
2. Download unpkg:
3. Open Lion Installer app in Finder (Right click -> Show Package
4. Open InstallESD.dmg (under SharedSupport)
5. Unpack BSD.pkg with unpkg (Located under Packages)   Term info
will be located in the new BSD folder in /usr/share/terminfo

hope it helps.

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:


before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

Angular2, what is the correct way to disable an anchor element?

I have used

[style.pointer-events]="isEditedParaOrder ?'none':'auto'" 

in my anchor tag so that they can not move to anchor tag by using tab to use "enter" key and also pointer itself we are setting to 'none' based on property 'isEditedParaO rder' whi

VBA: Conditional - Is Nothing

In my sample code, I was setting my object to nothing, and I couldn't get the "not" part of the if statement to work with the object. I tried if My_Object is not nothing and also if not My_Object is nothing. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this:

if My_Object is Nothing Then
    'do nothing
    'Do something
End if

How to make a jquery function call after "X" seconds

You can just use the normal setTimeout method in JavaScript.


setTimeout( function(){ 
    // Do something after 1 second 
  }  , 1000 );

In your example, you might want to use showStickySuccessToast directly.

Pushing from local repository to GitHub hosted remote


git push

from the command line inside the repository directory

How to initialize a nested struct?

You can define a struct and create its object in another struct like i have done below:

package main

import "fmt"

type Address struct {
    streetNumber int
    streetName   string
    zipCode      int

type Person struct {
    name    string
    age     int
    address Address

func main() {
    var p Person = "Vipin"
    p.age = 30
    p.address = Address{
        streetName:   "Krishna Pura",
        streetNumber: 14,
        zipCode:      475110,
    fmt.Println("Name: ",
    fmt.Println("Age: ", p.age)
    fmt.Println("StreetName: ", p.address.streetName)
    fmt.Println("StreeNumber: ", p.address.streetNumber)

Hope it helped you :)

How can I generate random alphanumeric strings?

One line of code Membership.GeneratePassword() does the trick :)

Here is a demo for the same.

Printing out a linked list using toString

When the JVM tries to run your application, it calls your main method statically; something like this:


That means there is no instance of your LinkedList class. In order to call your toString() method, you can create a new instance of your LinkedList class.

So the body of your main method should be like this:

public static void main(String[] args){
    // creating an instance of LinkedList class
    LinkedList ll = new LinkedList();

    // adding some data to the list


What are the differences between the different saving methods in Hibernate?

This link explains in good manner :

We all have those problems that we encounter just infrequently enough that when we see them again, we know we’ve solved this, but can’t remember how.

The NonUniqueObjectException thrown when using Session.saveOrUpdate() in Hibernate is one of mine. I’ll be adding new functionality to a complex application. All my unit tests work fine. Then in testing the UI, trying to save an object, I start getting an exception with the message “a different object with the same identifier value was already associated with the session.” Here’s some example code from Java Persistence with Hibernate.

            Session session = sessionFactory1.openSession();
            Transaction tx = session.beginTransaction();
            Item item = (Item) session.get(Item.class, new Long(1234));
            session.close(); // end of first session, item is detached

            item.getId(); // The database identity is "1234"
            item.setDescription("my new description");
            Session session2 = sessionFactory.openSession();
            Transaction tx2 = session2.beginTransaction();
            Item item2 = (Item) session2.get(Item.class, new Long(1234));
            session2.update(item); // Throws NonUniqueObjectException

To understand the cause of this exception, it’s important to understand detached objects and what happens when you call saveOrUpdate() (or just update()) on a detached object.

When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application’s memory, but Hibernate is no longer responsible for tracking changes to the objects.

If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.

Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.

So what are we to do? In Hibernate 3, we have merge() (in Hibernate 2, use saveOrUpdateCopy()). This method will force Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.

        Session session = sessionFactory1.openSession();
        Transaction tx = session.beginTransaction();
        Item item = (Item) session.get(Item.class, new Long(1234));
        session.close(); // end of first session, item is detached

        item.getId(); // The database identity is "1234"
        item.setDescription("my new description");
        Session session2 = sessionFactory.openSession();
        Transaction tx2 = session2.beginTransaction();
        Item item2 = (Item) session2.get(Item.class, new Long(1234));
        Item item3 = session2.merge(item); // Success!

It’s important to note that merge returns a reference to the newly updated version of the instance. It isn’t reattaching item to the Session. If you test for instance equality (item == item3), you’ll find it returns false in this case. You will probably want to work with item3 from this point forward.

It’s also important to note that the Java Persistence API (JPA) doesn’t have a concept of detached and reattached objects, and uses EntityManager.persist() and EntityManager.merge().

I’ve found in general that when using Hibernate, saveOrUpdate() is usually sufficient for my needs. I usually only need to use merge when I have objects that can have references to objects of the same type. Most recently, the cause of the exception was in the code validating that the reference wasn’t recursive. I was loading the same object into my session as part of the validation, causing the error.

Where have you encountered this problem? Did merge work for you or did you need another solution? Do you prefer to always use merge, or prefer to use it only as needed for specific cases

how to check for null with a ng-if values in a view with angularjs?

See the correct way with your example:

<div ng-if="!test.view">1</div>
<div ng-if="!!test.view">2</div>

Regards, Nicholls

HTML page disable copy/paste

You can use jquery for this:

$('body').bind('copy paste',function(e) {
    e.preventDefault(); return false; 

Using jQuery bind() and specififying your desired eventTypes .

How do I set the proxy to be used by the JVM

From the Java documentation (not the javadoc API):

Set the JVM flags http.proxyHost and http.proxyPort when starting your JVM on the command line. This is usually done in a shell script (in Unix) or bat file (in Windows). Here's the example with the Unix shell script:

JAVA_FLAGS=-Dhttp.proxyHost= -Dhttp.proxyPort=8800
java ${JAVA_FLAGS} ...

When using containers such as JBoss or WebLogic, my solution is to edit the start-up scripts supplied by the vendor.

Many developers are familiar with the Java API (javadocs), but many times the rest of the documentation is overlooked. It contains a lot of interesting information:

Update : If you do not want to use proxy to resolve some local/intranet hosts, check out the comment from @Tomalak:

Also don't forget the http.nonProxyHosts property!


How do I change the owner of a SQL Server database?

Here is a way to change the owner on ALL DBS (excluding System)

EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
 exec sp_changedbowner ''sa''

Create hyperlink to another sheet

The "!" sign is the key element. If you have a cell object (like "mycell" in following code sample) and link a cell to this object you must pay attention to ! element.

You must do something like this:

.Cells(i, 2).Hyperlinks.Add Anchor:=.Range(Cells(i, 2).Address), Address:="", _
     SubAddress:= "'" & ws.Name & "'" & _
     "!" & mycell.Address

jQuery Datepicker localization

You must extend the regional options like this (code split on multiple lines for readability):

var options = $.extend(
    {},                                  // empty object
    $.datepicker.regional["fr"],         // fr regional
    { dateFormat: "d MM, y" /*, ... */ } // your custom options

The order of parameters is important because of the way jQuery.extend works. Two incorrect examples:

 * This overwrites the global variable itself instead of creating a
 * customized copy of french regional settings
$.extend($.datepicker.regional["fr"], { dateFormat: "d MM, y"});

 * The desired dateFormat is overwritten by french regional 
 * settings' date format
$.extend({ dateFormat: "d MM, y"}, $.datepicker.regional["fr"]);

PS: you also need to load the jQuery UI i18n files:

<script src="//">

Is there a way to create multiline comments in Python?

Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.

Here is an example:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

How can I check if a string represents an int, without using try/except?

I do this all the time b/c I have a mild but admittedly irrational aversion to using the try/except pattern. I use this:

all([xi in '1234567890' for xi in x])

It doesn't accommodate negative numbers, so you could strip out all minus signs on the left side, and then check if the result comprises digits from 0-9:

all([xi in '1234567890' for xi in x.lstrip('-')])

You could also pass x to str() if you're not sure the input is a string:

all([xi in '1234567890' for xi in str(x).lstrip('-')])

There are some (edge?) cases where this falls apart:

  1. It doesn't work for various scientific and/or exponential notations (e.g. 1.2E3, 10^3, etc.) - both will return False. I don't think other answers accommodated this either, and even Python 3.8 has inconsistent opinions, since type(1E2) gives <class 'float'> whereas type(10^2) gives <class 'int'>.
  2. An empty string input gives True.
  3. A leading plus sign (e.g. "+7") gives False.
  4. Multiple minus signs are ignored so long as they're leading characters. This behavior is similar to the python interpreter* in that type(---1) returns <class int>. However, it isn't completely consistent with the interpreter in that int('---1') gives an error, but my solution returns True with the same input.

So it won't work for every possible input, but if you can exclude those, it's an OK one-line check that returns False if x is not an integer and True if x is an integer. But if you really want behavior that exactly models the int() built-in, you're better off using try/except.

I don't know if it's pythonic, but it's one line, and it's relatively clear what the code does.

*I don't mean to say that the interpreter ignores leading minus signs, just that any number of leading minus signs does not change that the result is an integer. int(--1) is actually interpreted as -(-1), or 1. int(---1) is interpreted as -(-(-1)), or -1. So an even number of leading minus signs gives a positive integer, and an odd number of minus signs gives a negative integer, but the result is always an integer.

What Regex would capture everything from ' mark to the end of a line?


Starting with a single quote ('), match any character (.) zero or more times (*) until the end of the line ($).

Core Data: Quickest way to delete all instances of an entity

in iOS 11.3 and Swift 4.1

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        let batchDeleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest )
        batchDeleteRequest.resultType = .resultTypeCount
        do {
            let batchDeleteResult = try dataController.viewContext.execute(batchDeleteRequest) as! NSBatchDeleteResult
            print("The batch delete request has deleted \(batchDeleteResult.result!) records.")
            dataController.viewContext.reset() // reset managed object context (need it for working)
        } catch {
            let updateError = error as NSError
            print("\(updateError), \(updateError.userInfo)")

you have to call reset after you do execute. If not, it will not update on the table view.

Split string on whitespace in Python

import re
s = "many   fancy word \nhello    \thi"
re.split('\s+', s)

Powershell script to check if service is started, if not then start it

Given $arrService = Get-Service -Name $ServiceName, $arrService.Status is a static property, corresponding to the value at the time of the call. Use $arrService.Refresh() when needed to renew the properties to current values.

MSDN ~ ServiceController.Refresh()

Refreshes property values by resetting the properties to their current values.

How to make a smooth image rotation in Android?

If you are using a set Animation like me you should add the interpolation inside the set tag:

<set xmlns:android=""

    android:toDegrees="360" />

    android:toAlpha="1.0" />


That Worked for me.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@Jk1's answer is fine, but Mockito also allows for more succinct injection using annotations:

@InjectMocks MyClass myClass; //@InjectMocks automatically instantiates too
@Mock MyInterface myInterface

But regardless of which method you use, the annotations are not being processed (not even your @Mock) unless you somehow call the static MockitoAnnotation.initMocks() or annotate the class with @RunWith(MockitoJUnitRunner.class).

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

<!DOCTYPE html>

   <link rel="stylesheet" type="text/css" href="main.css" />

 <div id="page-container">
   <div id="content-wrap">
     <!-- all other page content -->
   <footer id="footer"></footer>


#page-container {
  position: relative;
  min-height: 100vh;

#content-wrap {
  padding-bottom: 2.5rem;    /* Footer height */

#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 2.5rem;            /* Footer height */

Javascript ES6/ES5 find in array and change

May be use Filter.

const list = [{id:0}, {id:1}, {id:2}];
let listCopy = [...list];
let filteredDataSource = listCopy.filter((item) => {
       if ( === 1) {
  = 12345;

        return item;

Array [Object { id: 0 }, Object { id: 12345 }, Object { id: 2 }]

Class has no objects member


After doing:

$ pip install pylint-django

Follow this link:

Notice that the way to make pylint have into account pylint-django is by specifying:

"python.linting.pylintArgs": ["--load-plugins", "pylint_django"]

in the settings.json of VS Code.

But after that, you will notice a lot of new linting errors. Then, read what it said here:

These arguments are passed whenever the python.linting.pylintUseMinimalCheckers is set to true (the default). If you specify a value in pylintArgs or use a Pylint configuration file (see the next section), then pylintUseMinimalCheckers is implicitly set to false.

What I have done is creating a .pylintrc file as described in the link, and then, configured the following parameters inside the file (leaving the rest of the file untouched):




Now pylint works as expected.

How to calculate UILabel height dynamically?

In my case, I was using a fixed size header for each section but with a dynamically cell size in each header. The cell's height, depends on the label's height.

Working with:

tableView.estimatedRowHeight = SomeNumber
tableView.rowHeight = UITableViewAutomaticDimension

Works but when using:

tableView.reloadSections(IndexSet(integer: sender.tag) , with: .automatic)

when a lot of headers are not collapsed, creates a lot of bugs such as header duplication (header type x below the same type) and weird animations when the framework reloads with animation, even when using with type .none (FYI, a fixed header height and cell height works).

The solution is making the use of heightForRowAt callback and calculate the height of the label by your self (plus the animation looks a lot better). Remember that the height is being called first.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat
    let object = dataDetailsController.getRowObject(forIndexPath: indexPath)
    let label = UILabel(frame: tableView.frame)
    let font = UIFont(name: "HelveticaNeue-Bold", size: 25)
    label.text = object?.name
    label.font = font
    label.numberOfLines = 0
    label.textAlignment = .center
    let size = label.frame.height
    return Float(size) == 0 ? 34 : size

How do you print in a Go test using the "testing" package?

In case your using testing.M and associated setup/teardown; -v is valid here as well.

package g 

import (

func TestSomething(t *testing.T) {

func setup() {
    fmt.Println("setting up")

func teardown() {
    fmt.Println("tearing down")

func TestMain(m *testing.M) {
    result := m.Run()
$ go test -v g_test.go 
setting up
=== RUN   TestSomething
    g_test.go:10: later
--- SKIP: TestSomething (0.00s)
tearing down
ok      command-line-arguments  0.002s

Indexes of all occurrences of character in a string

I had this problem as well, until I came up with this method.

public static int[] indexesOf(String s, String flag) {
    int flagLen = flag.length();
    String current = s;
    int[] res = new int[s.length()];
    int count = 0;
    int base = 0;
    while(current.contains(flag)) {
        int index = current.indexOf(flag);
        res[count] = index + base;
        base += index + flagLen;
        current = current.substring(current.indexOf(flag) + flagLen, current.length());
        ++ count;
    return Arrays.copyOf(res, count);

This method can be used to find indexes of any flag of any length in a string, for example:

public class Main {

    public static void main(String[] args) {
        int[] indexes = indexesOf("Hello, yellow jello", "ll");

        // Prints [2, 9, 16]

    public static int[] indexesOf(String s, String flag) {
        int flagLen = flag.length();
        String current = s;
        int[] res = new int[s.length()];
        int count = 0;
        int base = 0;
        while(current.contains(flag)) {
            int index = current.indexOf(flag);
            res[count] = index + base;
            base += index + flagLen;
            current = current.substring(current.indexOf(flag) + flagLen, current.length());
            ++ count;
        return Arrays.copyOf(res, count);

Detecting real time window size changes in Angular 4

If you'd like you components to remain easily testable you should wrap the global window object in an Angular Service:

import { Injectable } from '@angular/core';

export class WindowService {

  get windowRef() {
    return window;


You can then inject it like any other service:

    private windowService: WindowService
) { }

And consume...

  ngOnInit() {
      const width= this.windowService.windowRef.innerWidth;

How to substring in jquery

Standard javascript will do that using the following syntax:

string.substring(from, to)

var name = "nameGorge";
var output = name.substring(4);

Read more here:

Visual Studio breakpoints not being hit

Right click on your project, then left click Properties, and select the Web tab. Debuggers > ASP.NET

Use and meaning of "in" in an if statement?

It depends on what next is.

If it's a string (as in your example), then in checks for substrings.

>>> "in" in "indigo"
>>> "in" in "violet"
>>> "0" in "10"
>>> "1" in "10"

If it's a different kind of iterable (list, tuple, set, dictionary...), then in checks for membership.

>>> "in" in ["in", "out"]
>>> "in" in ["indigo", "violet"]

In a dictionary, membership is seen as "being one of the keys":

>>> "in" in {"in": "out"}
>>> "in" in {"out": "in"}

Generic Interface

Here's another suggestion:

public interface Service<T> {
   T execute();

using this simple interface you can pass arguments via constructor in the concrete service classes:

public class FooService implements Service<String> {

    private final String input1;
    private final int input2;

    public FooService(String input1, int input2) {
       this.input1 = input1;
       this.input2 = input2;

    public String execute() {
        return String.format("'%s%d'", input1, input2);

ImageMagick security policy 'PDF' blocking conversion

As pointed out in some comments, you need to edit the policies of ImageMagick in /etc/ImageMagick-7/policy.xml. More particularly, in ArchLinux at the time of writing (05/01/2019) the following line is uncommented:

<policy domain="coder" rights="none" pattern="{PS,PS2,PS3,EPS,PDF,XPS}" />

Just wrap it between <!-- and --> to comment it, and pdf conversion should work again.

At runtime, find all classes in a Java application that extend a base class

Thanks all who answered this question.

It seems this is indeed a tough nut to crack. I ended up giving up and creating a static array and getter in my baseclass.

public abstract class Animal{
    private static Animal[] animals= null;
    public static Animal[] getAnimals(){
        if (animals==null){
            animals = new Animal[]{
                new Dog(),
                new Cat(),
                new Lion()
        return animals;

It seems that Java just isn't set up for self-discoverability the way C# is. I suppose the problem is that since a Java app is just a collection of .class files out in a directory / jar file somewhere, the runtime doesn't know about a class until it's referenced. At that time the loader loads it -- what I'm trying to do is discover it before I reference it which is not possible without going out to the file system and looking.

I always like code that can discover itself instead of me having to tell it about itself, but alas this works too.

Thanks again!

what is the differences between sql server authentication and windows authentication..?

When granting a user access to a database there are a few considerations to be made with advantages and disadvantages in terms of usability and security. Here we have two options for authenticating and granting permission to users. The first is by giving everyone the sa (systems admin) account access and then restricting the permissions manually by retaining a list of the users in which you can grant or deny permissions as needed. This is also known as the SQL authentication method. There are major security flaws in this method, as listed below. The second and better option is to have the Active Directory (AD) handle all the necessary authentication and authorization, also known as Windows authentication. Once the user logs in to their computer the application will connect to the database using those Windows login credentials on the operating system.

The major security issue with using the SQL option is that it violates the principle of least privilege (POLP) which is to only give the user the absolutely necessary permissions they need and no more. By using the sa account you present serious security flaws. The POLP is violated because when the application uses the sa account they have access to the entire database server. Windows authentication on the other hand follows the POLP by only granting access to one database on the server.

The second issue is that there is no need for every instance of the application to have the admin password. This means any application is a potential attack point for the entire server. Windows only uses the Windows credentials to login to the SQL Server. The Windows passwords are stored in a repository as opposed to the SQL database instance itself and the authentication takes place internally within Windows without having to store sa passwords on the application.

A third security issue arises by using the SQL method involves passwords. As presented on the Microsoft website and various security forums, the SQL method doesn’t’ enforce password changing or encryption, rather they are sent as clear text over the network. And the SQL method doesn’t lockout after failing attempts thus allowing a prolonged attempt to break in. Active Directory however, uses Kerberos protocol to encrypt passwords while employing as well a password change system and lockout after failing attempts.

There are efficiency disadvantages as well. Since you will be requiring the user to enter the credentials every time they want to access the database users may forget their credentials.

If a user being removed you would have to remove his credentials from every instance of the application. If you have to update the sa admin password you would have to update every instance of the SQL server. This is time consuming and unsafe, it leaves open the possibility of a dismissed user retaining access to the SQL Server. With the Windows method none of these concerns arise. Everything is centralized and handled by the AD.

The only advantages of using the SQL method lie in its flexibility. You are able to access it from any operating system and network, even remotely. Some older legacy systems as well as some web-based applications may only support sa access.

The AD method also provides time-saving tools such as groups to make it easier to add and remove users, and user tracking ability.

Even if you manage to correct these security flaws in the SQL method, you would be reinventing the wheel. When considering the security advantages provided by Windows authentication, including password policies and following the POLP, it is a much better choice over the SQL authentication. Therefore it is highly recommended to use the Windows authentication option.

How to export iTerm2 Profiles

I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2.


Gradle to execute Java class (without modifying build.gradle)

You can parameterise it and pass gradle clean build -Pprokey=goodbye

task choiceMyMainClass(type: JavaExec) {
     group = "Execution"
    description = "Run Option main class with JavaExecTask"
    classpath = sourceSets.main.runtimeClasspath

    if (project.hasProperty('prokey')){
        if (prokey == 'hello'){
            main = 'com.sam.home.HelloWorld'
        else if (prokey == 'goodbye'){
            main = 'com.sam.home.GoodBye'
    } else {
            println 'Invalid value is enterrd';

       // println 'Invalid value is enterrd'+ project.prokey;

Are complex expressions possible in ng-hide / ng-show?

I generally try to avoid expressions with ng-show and ng-hide as they were designed as booleans, not conditionals. If I need both conditional and boolean logic, I prefer to put in the conditional logic using ng-if as the first check, then add in an additional check for the boolean logic with ng-show and ng-hide

Howerver, if you want to use a conditional for ng-show or ng-hide, here is a link with some examples: Conditional Display using ng-if, ng-show, ng-hide, ng-include, ng-switch

Calculating distance between two points (Latitude, Longitude)

As you're using SQL 2008 or later, I'd recommend checking out the GEOGRAPHY data type. SQL has built in support for geospatial queries.

e.g. you'd have a column in your table of type GEOGRAPHY which would be populated with a geospatial representation of the coordinates (check out the MSDN reference linked above for examples). This datatype then exposes methods allowing you to perform a whole host of geospatial queries (e.g. finding the distance between 2 points)

How do I open the "front camera" on the Android platform?

public void surfaceCreated(SurfaceHolder holder) {
    try {
        mCamera =;

        Camera.Parameters p = mCamera.getParameters();
    } catch (IOException e) {
        // TODO Auto-generated catch block

Android check permission for LocationManager

With Android API level (23), we are required to check for permissions.

I had your same problem, but the following worked for me and I am able to retrieve Location data successfully:

(1) Ensure you have your permissions listed in the Manifest:

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

(2) Ensure you request permissions from the user:

if ( ContextCompat.checkSelfPermission( this, android.Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) {

            ActivityCompat.requestPermissions( this, new String[] {  android.Manifest.permission.ACCESS_COARSE_LOCATION  },
                                                LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION );

(3) Ensure you use ContextCompat as this has compatibility with older API levels.

(4) In your location service, or class that initializes your LocationManager and gets the last known location, we need to check the permissions:

if ( Build.VERSION.SDK_INT >= 23 &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;

(5) This approach only worked for me after I included @TargetApi(23) at the top of my initLocationService method.

(6) I also added this to my gradle build:

compile ''

Here is my LocationService for reference:

public class LocationService implements LocationListener  {

    //The minimum distance to change updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters

    //The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 0;//1000 * 60 * 1; // 1 minute

    private final static boolean forceNetwork = false;

    private static LocationService instance = null;

    private LocationManager locationManager;
    public Location location;
    public double longitude;
    public double latitude; 

     * Singleton implementation
     * @return
    public static LocationService getLocationManager(Context context)     {
        if (instance == null) {
            instance = new LocationService(context);
        return instance;

     * Local constructor
    private LocationService( Context context )     {

        LogService.log("LocationService created");

     * Sets up location service after permissions is granted
    private void initLocationService(Context context) {

        if ( Build.VERSION.SDK_INT >= 23 &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
             ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return  ;

        try   {
            this.longitude = 0.0;
            this.latitude = 0.0;
            this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

            // Get GPS and network status
            this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (forceNetwork) isGPSEnabled = false;

            if (!isNetworkEnabled && !isGPSEnabled)    {
                // cannot get location
                this.locationServiceAvailable = false;
                this.locationServiceAvailable = true;

                if (isNetworkEnabled) {
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    if (locationManager != null)   {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }//end if

                if (isGPSEnabled)  {
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

                    if (locationManager != null)  {
                        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        } catch (Exception ex)  {
            LogService.log( "Error creating location service: " + ex.getMessage() );


    public void onLocationChanged(Location location)     {
        // do stuff here with location object 

I tested with an Android Lollipop device so far only. Hope this works for you.

Split a string by a delimiter in python

You may be interested in the csv module, which is designed for comma-separated files but can be easily modified to use a custom delimiter.

import csv
csv.register_dialect( "myDialect", delimiter = "__", <other-options> )
lines = [ "MATCHES__STRING" ]

for row in csv.reader( lines ):

Load a bitmap image into Windows Forms using open file dialog

It's simple. Just add:

PictureBox1.BackgroundImageLayout = ImageLayout.Zoom;

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:


then your problem will be solved.

How to loop through array in jQuery?

Use the each() function of jQuery.

Here is an example:

$.each(currnt_image_list.split(','), function(index, value) { 
  alert(index + ': ' + value); 

What are all the possible values for HTTP "Content-Type" header?

As is defined in RFC 1341:

In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:

Content-Type := type "/" subtype *[";" parameter]

type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token

x-token := < The two characters "X-" followed, with no intervening white space, by any token >

subtype := token

parameter := attribute "=" value

attribute := token

value := token / quoted-string

token := 1*

tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values

And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).

As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).

Also note the comment above:

If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.

You'll notice that a lot of HTTP requests/responses include an X- header of some sort which are self defined, keep this in mind when validating the types.

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

It's just common stuff for making cin input work faster.

For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.

The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).

How to comment out a block of code in Python

On Eric4 there is an easy way: select a block, type Ctrl+M to comment the whole block or Ctrl+alt+M to uncomment.

How do I extract data from JSON with PHP?

The acepted Answer is very detailed and correct in most of the cases.

I just want to add that i was getting an error while attempting to load a JSON text file encoded with UTF8, i had a well formatted JSON but the 'json_decode' always returned me with NULL, it was due the BOM mark.

To solve it, i made this PHP function:

function load_utf8_file($filePath)
    $response = null;
        if (file_exists($filePath)) {
            $text = file_get_contents($filePath);
            $response = preg_replace("/^\xEF\xBB\xBF/", '', $text);          
    } catch (Exception $e) {
      echo 'ERROR: ',  $e->getMessage(), "\n";
   finally{  }
   return $response;

Then i use it like this to load a JSON file and get a value from it:

$str = load_utf8_file('appconfig.json'); 
$json = json_decode($str, true); 
echo $json['prod']['deploy']['hostname'];

How do I make a text input non-editable?

you just need to add disabled at the end

<input type="text" value="3" class="field left" disabled>

What exactly is RESTful programming?

What is API Testing?

API testing utilizes programming to send calls to the API and get the yield. It testing regards the segment under test as a black box. The objective of API testing is to confirm right execution and blunder treatment of the part preceding its coordination into an application.


REST: Representational State Transfer.

  • It’s an arrangement of functions on which the testers performs requests and receive responses. In REST API interactions are made via HTTP protocol.
  • REST also permits communication between computers with each other over a network.
  • For sending and receiving messages, it involves using HTTP methods, and it does not require a strict message definition, unlike Web services.
  • REST messages often accepts the form either in form of XML, or JavaScript Object Notation (JSON).

4 Commonly Used API Methods:-

  1. GET: – It provides read only access to a resource.
  2. POST: – It is used to create or update a new resource.
  3. PUT: – It is used to update or replace an existing resource or create a new resource.
  4. DELETE: – It is used to remove a resource.

Steps to Test API Manually:-

To use API manually, we can use browser based REST API plugins.

  1. Install POSTMAN(Chrome) / REST(Firefox) plugin
  2. Enter the API URL
  3. Select the REST method
  4. Select content-Header
  5. Enter Request JSON (POST)
  6. Click on send
  7. It will return output response

Steps to Automate REST API

Set the maximum character length of a UITextField

For Swift 2.1+

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if (range.length + range.location > textField.text!.characters.count )
        return false;

    let newLength = textField.text!.characters.count + string.characters.count - range.length
    return newLength <= 25

Hope it helps

Rails: update_attribute vs update_attributes

To answer your question, update_attribute skips pre save "validations" but it still runs any other callbacks like after_save etc. So if you really want to "just update the column and skip any AR cruft" then you need to use (apparently)

Model.update_all(...) see

Can a java lambda have more than 1 parameter?

For this case you could use interfaces from default library (java 1.8):


There is a small (not the best) example of default method in interface:

default BiFunction<File, String, String> getFolderFileReader() {
    return (directory, fileName) -> {
        try {
            return FileUtils.readFile(directory, fileName);
        } catch (IOException e) {
            LOG.error("Unable to read file {} in {}.", fileName, directory.getAbsolutePath(), e);
        return "";

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute


$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.


MyDate %>%
   filter(! %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 

You should be able to remove the annoying NAs on your plot. Hope this works :)

Git asks for username every time I push

To set the credentials for the entire day that is 24 hours.

git config --global credential.helper 'cache --timeout 86400'

Else for 1 hour replace the 86400 secs to 3600.


all configuration options for the 'cache' authentication helper:

git help credential-cache

MySQL: How to add one day to datetime field in query

You can try this:

SELECT DATE(DATE_ADD(m_inv_reqdate, INTERVAL + 1 DAY)) FROM  tr08_investment

How to fix corrupted git repository?

I tried moving away the object files with 0 bytes and fetching them again from the remote, and it worked:

find . -type f -size 0 -exec mv {} /tmp \;
git fetch

It fetched the missing objects from the remote and allowed me to continue working without reinitializing the whole repo.

How can I pass a list as a command-line argument with argparse?

I want to handle passing multiple lists, integer values and strings.

Helpful link => How to pass a Bash variable to Python?

def main(args):
    my_args = []
    for arg in args:
        if arg.startswith("[") and arg.endswith("]"):
            arg = arg.replace("[", "").replace("]", "")


if __name__ == "__main__":
    import sys

Order is not important. If you want to pass a list just do as in between "[" and "] and seperate them using a comma.


python my_string 3 "[1,2]" "[3,4,5]"

Output => ['my_string', '3', ['1', '2'], ['3', '4', '5']], my_args variable contains the arguments in order.

Send response to all clients except sender

Here is my list (updated for 1.0):

// sending to sender-client only
socket.emit('message', "this is a test");

// sending to all clients, include sender
io.emit('message', "this is a test");

// sending to all clients except sender
socket.broadcast.emit('message', "this is a test");

// sending to all clients in 'game' room(channel) except sender'game').emit('message', 'nice game');

// sending to all clients in 'game' room(channel), include sender'game').emit('message', 'cool game');

// sending to sender client, only if they are in 'game' room(channel)'game').emit('message', 'enjoy the game');

// sending to all clients in namespace 'myNamespace', include sender
io.of('myNamespace').emit('message', 'gg');

// sending to individual socketid'message', 'for your eyes only');

// list socketid
for (var socketid in io.sockets.sockets) {}
Object.keys(io.sockets.sockets).forEach((socketid) => {});

C# - Fill a combo box with a DataTable

Are you applying a RowFilter to your DefaultView later in the code? This could change the results returned.

I would also avoid using the string as the display member if you have a direct reference the the data column I would use the object properties:

mnuActionLanguage.ComboBox.DataSource = lTable.DefaultView;
mnuActionLanguage.ComboBox.DisplayMember = lName.ColumnName;

I have tried this with a blank form and standard combo, and seems to work for me.

How to send an email from JavaScript

JavaScript can't send email from a web browser. However, stepping back from the solution you've already tried to implement, you can do something that meets the original requirement:

send an email without refreshing the page

You can use JavaScript to construct the values that the email will need and then make an AJAX request to a server resource that actually sends the email. (I don't know what server-side languages/technologies you're using, so that part is up to you.)

If you're not familiar with AJAX, a quick Google search will give you a lot of information. Generally you can get it up and running quickly with jQuery's $.ajax() function. You just need to have a page on the server that can be called in the request.

how to redirect to external url from c# controller

If you are using MVC then it would be more appropriate to use RedirectResult instead of using Response.Redirect.

public ActionResult Index() {
        return new RedirectResult("");

Reference -

Does IE9 support console.log, and is it a real function?

I would like to mention that IE9 does not raise the error if you use console.log with developer tools closed on all versions of Windows. On XP it does, but on Windows 7 it doesn't. So if you dropped support for WinXP in general, you're fine using console.log directly.

Managing SSH keys within Jenkins for Git

According to this article, you may try following command:

   ssh-add -l

If your key isn't in the list, then

   ssh-add /var/lib/jenkins/.ssh/id_rsa_project

How do I make a file:// hyperlink that works in both IE and Firefox?

just use


works in IE, Firefox and Chrome as far as I can tell.

see for more info

How to display (print) vector in Matlab?

Here's another approach that takes advantage of Matlab's strjoin function. With strjoin it's easy to customize the delimiter between values.

x = [1, 2, 3];
fprintf('Answer: (%s)\n', strjoin(cellstr(num2str(x(:))),', '));

This results in: Answer: (1, 2, 3)

Getting first and last day of the current month

var myDate = DateTime.Now;
var startOfMonth = new DateTime(myDate.Year, myDate.Month, 1);
var endOfMonth = startOfMonth.AddMonths(1).AddDays(-1);

That should give you what you need.

Font Awesome icon inside text input element

You're right. :before and :after pseudo content is not intended to work on replaced content like img and input elements. Adding a wrapping element and declare a font-family is one of the possibilities, as is using a background image. Or maybe a html5 placeholder text fits your needs:

<input name="username" placeholder="&#61447;">

Browsers that don’t support the placeholder attribute will simply ignore it.


The before content selector selects the input: input[type="text"]:before. You should select the wrapper: .wrapper:before. See . I also added the placeholder suggestion where the wrapper is redundant.

.wrapper input[type="text"] {
    position: relative; 

input { font-family: 'FontAwesome'; } /* This is for the placeholder */

.wrapper:before {
    font-family: 'FontAwesome';
    position: relative;
    left: -5px;
    content: "\f007";

<p class="wrapper"><input placeholder="&#61447; Username"></p>


Font Awesome uses the Unicode Private Use Area (PUA) to store icons. Other characters are not present and fall back to the browser default. That should be the same as any other input. If you define a font on input elements, then supply the same font as fallback for situations where us use an icon. Like this:

input { font-family: 'FontAwesome', YourFont; }

Prompt Dialog in Windows Forms

There is no such thing natively in Windows Forms.

You have to create your own form for that or:

use the Microsoft.VisualBasic reference.

Inputbox is legacy code brought into .Net for VB6 compatibility - so i advise to not do this.

Check if string contains only digits

If you want to even support for float values (Dot separated values) then you can use this expression :

var isNumber = /^\d+\.\d+$/.test(value);

django import error - No module named

For those of you using Django 1.6 or newer, note that execute_manager was removed. There is a solution posted in the second SO answer here.

Loop through an array in JavaScript

Use the while loop...

var i = 0, item, items = ['one', 'two', 'three'];
while(item = items[i++]){

It logs: 'one', 'two', and 'three'

And for the reverse order, an even more efficient loop:

var items = ['one', 'two', 'three'], i = items.length;

It logs: 'three', 'two', and 'one'

Or the classical for loop:

var items = ['one', 'two', 'three']
for(var i=0, l = items.length; i < l; i++){

It logs: 'one','two','three'

Reference: Google Closure: How not to write JavaScript

What is the most efficient way to deep clone an object in JavaScript?

Here is my way of deep cloning a object with ES2015 default value and spread operator

 const makeDeepCopy = (obj, copy = {}) => {
  for (let item in obj) {
    if (typeof obj[item] === 'object') {
      makeDeepCopy(obj[item], copy)
    if (obj.hasOwnProperty(item)) {
      copy = {
  return copy

const testObj = {_x000D_
  "type": "object",_x000D_
  "properties": {_x000D_
    "userId": {_x000D_
      "type": "string",_x000D_
      "chance": "guid"_x000D_
    "emailAddr": {_x000D_
      "type": "string",_x000D_
      "chance": {_x000D_
        "email": {_x000D_
          "domain": ""_x000D_
      "pattern": "[email protected]"_x000D_
  "required": [_x000D_
const makeDeepCopy = (obj, copy = {}) => {_x000D_
  for (let item in obj) {_x000D_
    if (typeof obj[item] === 'object') {_x000D_
      makeDeepCopy(obj[item], copy)_x000D_
    if (obj.hasOwnProperty(item)) {_x000D_
      copy = {_x000D_
  return copy_x000D_

RegExp in TypeScript

In typescript, the declaration is something like this:

const regex : RegExp = /.+\*.+/;

using RegExp constructor:

const regex = new RegExp('.+\\*.+');

JavaScript - Hide a Div at startup (load)

Barring the CSS solution. The fastest possible way is to hide it immediatly with a script.

<div id="hideme"></div>
<script type="text/javascript">

In this case I would recommend the CSS solution by Vega. But if you need something more complex (like an animation) you can use this approach.

This has some complications (see comments below). If you want this piece of script to really run as fast as possible you can't use jQuery, use native JS only and defer loading of all other scripts.

How do you split a list into evenly sized chunks?

heh, one line version

In [48]: chunk = lambda ulist, step:  map(lambda i: ulist[i:i+step],  xrange(0, len(ulist), step))

In [49]: chunk(range(1,100), 10)
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
 [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
 [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
 [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],
 [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],
 [51, 52, 53, 54, 55, 56, 57, 58, 59, 60],
 [61, 62, 63, 64, 65, 66, 67, 68, 69, 70],
 [71, 72, 73, 74, 75, 76, 77, 78, 79, 80],
 [81, 82, 83, 84, 85, 86, 87, 88, 89, 90],
 [91, 92, 93, 94, 95, 96, 97, 98, 99]]

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Currently, Microsoft don't provide download option for '2007 Office System Driver: Data Connectivity Components' and click on first answer for '2007 Office System Driver: Data Connectivity Components' redirect to Cnet where getting download link creates confusion.

That's why who use SQL Server 2014 and latest version of SQL Server in Windows 10 click on below link for download this component which resolve your problem : - Microsoft Access Database Engine 2010

Happy Coding!

How can I create a text box for a note in markdown?

The following methods work on GitHub, on GitLab... and on Stackoverflow, which now uses CommonMark!

> One-Line Box made with Blockquote

One-Line Box made with Blockquote

`One-Line Box made with Backticks`

One-Line Box made with Backticks

Box made with Triple Backticks

Box made with Triple Backticks  

~ ~ ~
Box made with Triple Tildes
(remove the spaces between the tildes to make this work)
~ ~ ~

Box made with Triple Tildes

Box made with Four Spaces at the start of each line:

    “Sometimes we must let go of our pride and do what is requested of us.”
    Padmé Amidala

... or use horizontal lines?

Three dashes (---) make a horizontal line:

Note: “ Your focus determines your reality.” – Qui-Gon Jinn.

For more configurations, I strongly advise the excellent GitLab Markdown Guide.
You can also check the less detailed GitHub basic formatting syntax.
You can compare Markdown implementations using Babelmark.

Useful hints :

  • to force a newline, put two spaces at the end of the line;

  • to escape special characters, use \.

What is the difference between rb and r+b modes in file objects

r+ is used for reading, and writing mode. b is for binary. r+b mode is open the binary file in read or write mode.
You can read more here.

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my file now has the following addition


Thanks for the heads up as to how to do this, Benjamin.

How to show what a commit did?


$ git log -p

do what you need?

Check out the chapter on Git Log in the Git Community Book for more examples. (Or look at the the documentation.)

Update: As others (Jakub and Bombe) already pointed out: although the above works, git show is actually the command that is intended to do exactly what was asked for.

How can you float: right in React Native?

why does the Text take up the full space of the View, instead of just the space for "Hello"?

Because the View is a flex container and by default has flexDirection: 'column' and alignItems: 'stretch', which means that its children should be stretched out to fill its width.

(Note, per the docs, that all components in React Native are display: 'flex' by default and that display: 'inline' does not exist at all. In this way, the default behaviour of a Text within a View in React Native differs from the default behaviour of span within a div on the web; in the latter case, the span would not fill the width of the div because a span is an inline element by default. There is no such concept in React Native.)

How can the Text be floated / aligned to the right?

The float property doesn't exist in React Native, but there are loads of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:

1. Use textAlign: 'right' on the Text element

  <Text style={{textAlign: 'right'}}>Hello, World!</Text>

(This approach doesn't change the fact that the Text fills the entire width of the View; it just right-aligns the text within the Text.)

2. Use alignSelf: 'flex-end' on the Text

  <Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>

This shrinks the Text element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the View.

3. Use alignItems: 'flex-end' on the View

<View style={{alignItems: 'flex-end'}}>
  <Text>Hello, World!</Text>

This is equivalent to setting alignSelf: 'flex-end' on all the View's children.

4. Use flexDirection: 'row' and justifyContent: 'flex-end' on the View

<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
  <Text>Hello, World!</Text>

flexDirection: 'row' sets the main direction of layout to be horizontal instead of vertical; justifyContent is just like alignItems, but controls alignment in the main direction instead of the cross direction.

5. Use flexDirection: 'row' on the View and marginLeft: 'auto' on the Text

<View style={{flexDirection: 'row'}}>
  <Text style={{marginLeft: 'auto'}}>Hello, World!</Text>

This approach is demonstrated, in the context of the web and real CSS, at

6. Use position: 'absolute' and right: 0 on the Text:

  <Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>

Like in real CSS, this takes the Text "out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the View by default (although you can explicitly set a distance from the top of the View using the top style property).

Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.

"starting Tomcat server 7 at localhost has encountered a prob"

In eclipse->in server tap-> double click on Tomcat server at localhost-> Ports -> HTTP/1.1

Default port number will be 8080. Change this to 8081. Tomcat version7.0

I have configured tomcat server also in NetBeans IDE 7.4 for JSP. So am facing this issue.

How to set the value of a hidden field from a controller in mvc

Please try using following way.

@Html.Hidden("hdnFlag",(object) Convert.ToInt32(ViewBag.page_Count))

How do you change text to bold in Android?

In the ideal world you would set the text style attribute in you layout XML definition like that:


There is a simple way to achieve the same result dynamically in your code by using setTypeface method. You need to pass and object of Typeface class, which will describe the font style for that TextView. So to achieve the same result as with the XML definition above you can do the following:

TextView Tv = (TextView) findViewById(;
Typeface boldTypeface = Typeface.defaultFromStyle(Typeface.BOLD);

The first line will create the object form predefined style (in this case Typeface.BOLD, but there are many more predefined). Once we have an instance of typeface we can set it on the TextView. And that's it our content will be displayed on the style we defined.

I hope it helps you a lot.For better info you can visit

How to nicely format floating numbers to string without unnecessary decimal 0's

new DecimalFormat("00.#").format(20.236)
//out =20.2

new DecimalFormat("00.#").format(2.236)
//out =02.2
  1. 0 for minimum number of digits
  2. Renders # digits

Convert date formats in bash

It's enough to do:

datatime=`date -d "${data}" '+%Y%m%d'`
echo $datatime

If you want to add also the time you can use in that way

datatime=`date -d "${data}" '+%Y%m%d %T'`

echo $data
Wed Feb 6 03:57:15 EST 2019

echo $datatime
20190206 03:57:15

Differences between MySQL and SQL Server

Anyone have any good experience with a "port" of a database from SQL Server to MySQL?

This should be fairly painful! I switched versions of MySQL from 4.x to 5.x and various statements wouldn't work anymore as they used to. The query analyzer was "improved" so statements which previously were tuned for performance would not work anymore as expected.

The lesson learned from working with a 500GB MySQL database: It's a subtle topic and anything else but trivial!

How do I convert NSMutableArray to NSArray?

If you're constructing an array via mutability and then want to return an immutable version, you can simply return the mutable array as an "NSArray" via inheritance.

- (NSArray *)arrayOfStrings {
    NSMutableArray *mutableArray = [NSMutableArray array];
    mutableArray[0] = @"foo";
    mutableArray[1] = @"bar";

    return mutableArray;

If you "trust" the caller to treat the (technically still mutable) return object as an immutable NSArray, this is a cheaper option than [mutableArray copy].

Apple concurs:

To determine whether it can change a received object, the receiver of a message must rely on the formal type of the return value. If it receives, for example, an array object typed as immutable, it should not attempt to mutate it. It is not an acceptable programming practice to determine if an object is mutable based on its class membership.

The above practice is discussed in more detail here:

Best Practice: Return mutableArray.copy or mutableArray if return type is NSArray

How can I include null values in a MIN or MAX?

Use IsNull

SELECT recordid, MIN(startdate), MAX(IsNull(enddate, Getdate()))
FROM tmp 
GROUP BY recordid

I've modified MIN in the second instruction to MAX

Loop through array of values with Arrow Function

In short:

someValues.forEach((element) => {

If you care about index, then second parameter can be passed to receive the index of current element:

someValues.forEach((element, index) => {
    console.log(`Current index: ${index}`);

Refer here to know more about Array of ES6:

Disposing WPF User Controls

My scenario is little different, but the intent is same i would like to know when the parent window hosting my user control is closing/closed as The view(i.e my usercontrol) should invoke the presenters oncloseView to execute some functionality and perform clean up. ( well we are implementing a MVP pattern on a WPF PRISM application).

I just figured that in the Loaded event of the usercontrol, i can hook up my ParentWindowClosing method to the Parent windows Closing event. This way my Usercontrol can be aware when the Parent window is being closed and act accordingly!

Change type of varchar field to integer: "cannot be cast automatically to type integer"

If you are working on development environment(or on for production env. it may be backup your data) then first to clear the data from the DB field or set the value as 0.

UPDATE table_mame SET field_name= 0;

After that to run the below query and after successfully run the query, to the schemamigration and after that run the migrate script.

ALTER TABLE table_mame ALTER COLUMN field_name TYPE numeric(10,0) USING field_name::numeric;

I think it will help you.

Python: Passing variables between functions

Your return is useless if you don't assign it


Exception thrown in catch and finally clause

class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}

public class C1 {
    public static void main(String[] args) throws Exception {
        try {
            System.out.print("TryA L1\n");
            System.out.print("TryB L1\n");
        catch (Exception i) {
            System.out.print("Catch L1\n");                
        finally {
            System.out.print("Finally L1\n");
            throw new MyExc1();

    static void q() throws Exception {
        try {
            System.out.print("TryA L2\n");
            System.out.print("TryB L2\n");
        catch (Exception y) {
            System.out.print("Catch L2\n");
            throw new MyExc2();  
        finally {
            System.out.print("Finally L2\n");
            throw new Exception();

    static void q2() throws Exception {
        throw new MyExc1();


TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1        
Exception in thread "main" MyExc1 at C1.main(

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

in my case I was using below dependency


and getting the same exception of Auth fail, but updated dependency to below version and problem get resolved.


Java HTML Parsing

Several years ago I used JTidy for the same purpose:

"JTidy is a Java port of HTML Tidy, a HTML syntax checker and pretty printer. Like its non-Java cousin, JTidy can be used as a tool for cleaning up malformed and faulty HTML. In addition, JTidy provides a DOM interface to the document that is being processed, which effectively makes you able to use JTidy as a DOM parser for real-world HTML.

JTidy was written by Andy Quick, who later stepped down from the maintainer position. Now JTidy is maintained by a group of volunteers.

More information on JTidy can be found on the JTidy SourceForge project page ."

cleanup php session files

# Every 30 minutes, not on the hour<br>
# Grabs maxlifetime directly from \`php -i\`<br>
# doesn't care if /var/lib/php5 exists, errs go to /dev/null<br>

09,39 * * * *   find /var/lib/php5/ -type f -cmin +$(echo "\`php -i|grep -i session.gc_maxlifetime|cut -d' ' -f3\` / 60" | bc) -exec rm -f {} \\; >/dev/null 2>&1

The Breakdown: Only files: find /var/lib/php5/ -type f
Older than minutes: -cmin
Get php settings: $(echo "`php -i|grep -i session.gc_maxlifetime
Do the math: |cut -d' ' -f3` / 60" | bc)
RM matching files: -exec rm -f {} \;

upstream sent too big header while reading response header from upstream

upstream sent too big header while reading response header from upstream is nginx's generic way of saying "I don't like what I'm seeing"

  1. Your upstream server thread crashed
  2. The upstream server sent an invalid header back
  3. The Notice/Warnings sent back from STDERR overflowed their buffer and both it and STDOUT were closed

3: Look at the error logs above the message, is it streaming with logged lines preceding the message? PHP message: PHP Notice: Undefined index: Example snippet from a loop my log file:

2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
... // 20 lines of same
PHP message: PHP Notice:  Undefined index: Firstname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Lastname in /srv/www/classes/data_convert.php on line 1090
PHP message: PHP Notice:  Undef
2015/11/23 10:30:02 [error] 32451#0: *580927 FastCGI sent in stderr: "ta_convert.php on line 1090
PHP message: PHP Notice:  Undefined index: Firstname

you can see in the 3rd line from the bottom that the buffer limit was hit, broke, and the next thread wrote in over it. Nginx then closed the connection and returned 502 to the client.

2: log all the headers sent per request, review them and make sure they conform to standards (nginx does not permit anything older than 24 hours to delete/expire a cookie, sending invalid content length because error messages were buffered before the content counted...). getallheaders function call can usually help out in abstracted code situations php get all headers

examples include:

//expire cookie
setcookie ( 'bookmark', '', strtotime('2012-01-01 00:00:00') );
// nginx will refuse this header response, too far past to accept

and this:

header('Content-type: image/jpg');

<?php   //a space was injected into the output above this line
header('Content-length: ' . filesize('image.jpg') );
echo file_get_contents('image.jpg');
// error! the response is now 1-byte longer than header!!

1: verify, or make a script log, to ensure your thread is reaching the correct end point and not exiting before completion.

Block direct access to a file over http but allow php script access

The safest way is to put the files you want kept to yourself outside of the web root directory, like Damien suggested. This works because the web server follows local file system privileges, not its own privileges.

However, there are a lot of hosting companies that only give you access to the web root. To still prevent HTTP requests to the files, put them into a directory by themselves with a .htaccess file that blocks all communication. For example,

Order deny,allow
Deny from all

Your web server, and therefore your server side language, will still be able to read them because the directory's local permissions allow the web server to read and execute the files.

How to change the color of a CheckBox?

If your minSdkVersion is 21+ use android:buttonTint attribute to update the color of a checkbox:

  android:buttonTint="@color/tint_color" />

In projects that use AppCompat library and support Android versions below 21 you can use a compat version of the buttonTint attribute:

  app:buttonTint="@color/tint_color" />

In this case if you want to subclass a CheckBox don't forget to use AppCompatCheckBox instead.


You can change CheckBoxs drawable using android:button="@drawable/your_check_drawable" attribute.

Is a view faster than a simple query?

Against all expectation, views are way slower in some circumstances.

I discovered this recently when I had problems with data which was pulled from Oracle which needed to be massaged into another format. Maybe 20k source rows. A small table. To do this we imported the oracle data as unchanged as I could into a table and then used views to extract data. We had secondary views based on those views. Maybe 3-4 levels of views.

One of the final queries, which extracted maybe 200 rows would take upwards of 45 minutes! That query was based on a cascade of views. Maybe 3-4 levels deep.

I could take each of the views in question, insert its sql into one nested query, and execute it in a couple of seconds.

We even found that we could even write each view into a temp table and query that in place of the view and it was still way faster than simply using nested views.

What was even odder was that performance was fine until we hit some limit of source rows being pulled into the database, performs just dropped off a cliff over the space of a couple of days - a few more source rows was all it took.

So, using queries which pull from views which pull from views is much slower than a nested query - which makes no sense for me.

How to make HTML element resizable using pure Javascript?

I just created a CodePen that shows how this can be done pretty easily using ES6.

Basically, here is the class that does this.

let getPropertyValue = function(style, prop) {
  let value = style.getPropertyValue(prop);
  value = value ? value.replace(/[^0-9.]/g, '') : '0';
  return parseFloat(value);

let getElementRect = function(element) {
  let style = window.getComputedStyle(element, null);
  return {
    x: getPropertyValue(style, 'left'),
    y: getPropertyValue(style, 'top'),
    width: getPropertyValue(style, 'width'),
    height: getPropertyValue(style, 'height')

class Resizer {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.element = element;
        this.options = options;
        this.offsetX = 0;
        this.offsetY = 0;
        this.handle = document.createElement('div');
        this.handle.setAttribute('class', 'drag-resize-handlers');
        this.handle.setAttribute('data-direction', 'br');
        this.wrapper.appendChild(this.handle); =; =; =; =; = 'relative'; = 0; = 0;
        this.onResize = this.resizeHandler.bind(this);
        this.onStop = this.stopResize.bind(this);
        this.handle.addEventListener('mousedown', this.initResize.bind(this));

    initResize(event) {
        this.stopResize(event, true);
        this.handle.addEventListener('mousemove', this.onResize);
        this.handle.addEventListener('mouseup', this.onStop);

    resizeHandler(event) {
        this.offsetX = event.clientX - (this.wrapper.offsetLeft + this.handle.offsetLeft);
        this.offsetY = event.clientY - (this.wrapper.offsetTop + this.handle.offsetTop);
        let wrapperRect = getElementRect(this.wrapper);
        let elementRect = getElementRect(this.element); = (wrapperRect.width + this.offsetX) + 'px'; = (wrapperRect.height + this.offsetY) + 'px'; = (elementRect.width + this.offsetX) + 'px'; = (elementRect.height + this.offsetY) + 'px';

    stopResize(event, nocb) {
        this.handle.removeEventListener('mousemove', this.onResize); 
        this.handle.removeEventListener('mouseup', this.onStop);

class Dragger {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.options = options;
        this.element = element;
        this.element.draggable = true;
        this.element.setAttribute('draggable', true);
        this.element.addEventListener('dragstart', this.dragStart.bind(this));

    dragStart(event) {
        let wrapperRect = getElementRect(this.wrapper);
        var x = wrapperRect.x - parseFloat(event.clientX);
        var y = wrapperRect.y - parseFloat(event.clientY);
        event.dataTransfer.setData("text/plain", + ',' + x + ',' + y);

    dragStop(event, prevX, prevY) {
        var posX = parseFloat(event.clientX) + prevX;
        var posY = parseFloat(event.clientY) + prevY; = posX + 'px'; = posY + 'px';

class DragResize {
    constructor(element, options) {
        options = options || {};
        this.wrapper = document.createElement('div');
        this.wrapper.setAttribute('class', 'tooltip drag-resize');
        if (element.parentNode) {
          element.parentNode.insertBefore(this.wrapper, element);
        element.resizer = new Resizer(this.wrapper, element, options);
        element.dragger = new Dragger(this.wrapper, element, options);

document.body.addEventListener('dragover', function (event) {
    return false;

document.body.addEventListener('drop', function (event) {
    var dropData = event.dataTransfer.getData("text/plain").split(',');
    var element = document.getElementById(dropData[0]);
    element.dragger.dragStop(event, parseFloat(dropData[1]), parseFloat(dropData[2]));
    return false;

How to maintain page scroll position after a jquery event is carried out?

  scrollTop: $('#answer-<%= %>').offset().top - 50
}, 700);

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

EF is looking for a table named dbo.BaseCs. Might be an entity name pluralizing issue. Check out this link.

EDIT: Updated link.

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

For window-10 resolved error- make' is not recognized as an internal or external command.

  1. Download MinGW - Minimalist GNU for Windows from here

  2. install it

  3. While installation mark all basic setup packages like shown in image enter image description here

  4. Apply changes enter image description here

  5. After completion of installation copy C:\MinGW\bin paste in system variable

Open MyComputer properties and follow as shown in image enter image description here

You may also need to install this


When to use references vs. pointers

References are cleaner and easier to use, and they do a better job of hiding information. References cannot be reassigned, however. If you need to point first to one object and then to another, you must use a pointer. References cannot be null, so if any chance exists that the object in question might be null, you must not use a reference. You must use a pointer. If you want to handle object manipulation on your own i.e if you want to allocate memory space for an object on the Heap rather on the Stack you must use Pointer

int *pInt = new int; // allocates *pInt on the Heap

How to make an Android Spinner with initial text "Select One"?

here's a simple one

    private boolean isFirst = true;
private void setAdapter() {
    final ArrayList<String> spinnerArray = new ArrayList<String>();     
    spinnerArray.add("Select your option");
    spinnerArray.add("Option 1");
    spinnerArray.add("Option 2");
    spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
            TextView tv = (TextView)selectedItemView;
            String res = tv.getText().toString().trim();
            if (res.equals("Option 1")) {
            //do Something
        } else if (res.equals("Option 2")) {
            //do Something else

        public void onNothingSelected(AdapterView<?> parentView) { }


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_spinner_style,spinnerArray) {
         public View getView(int position, View convertView, ViewGroup parent) {
             View v = super.getView(position, convertView, parent);
             int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());                  
             ((TextView) v).setTypeface(tf2);
             ((TextView) v).getLayoutParams().height = height;
             ((TextView) v).setGravity(Gravity.CENTER);
             ((TextView) v).setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
             ((TextView) v).setTextColor(Color.WHITE);
             return v;

         public View getDropDownView(int position, View convertView,
                 ViewGroup parent) {
             if (isFirst) {
                 isFirst = false;
             View v = super.getDropDownView(position, convertView, parent);                  
             ((TextView) v).setTextColor(Color.argb(255, 70, 70, 70));
             ((TextView) v).setTypeface(tf2);
             ((TextView) v).setGravity(Gravity.CENTER);
             return v;

What evaluates to True/False in R?

T and TRUE are True, F and FALSE are False. T and F can be redefined, however, so you should only rely upon TRUE and FALSE. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.

Determining whether an object is a member of a collection in VBA

This is an old question. I have carefully reviewed all the answers and comments, tested the solutions for performance.

I came up with the fastest option for my environment which does not fail when a collection has objects as well as primitives.

Public Function ExistsInCollection(col As Collection, key As Variant) As Boolean
    On Error GoTo err
    ExistsInCollection = True
    Exit Function
    ExistsInCollection = False
End Function

In addition, this solution does not depend on hard-coded error values. So the parameter col As Collection can be substituted by some other collection type variable, and the function must still work. E.g., on my current project, I will have it as col As ListColumns.

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>

How to declare and add items to an array in Python?

I believe you are all wrong. you need to do:

array = array[] in order to define it, and then:

array.append ["hello"] to add to it.

Chrome:The website uses HSTS. Network errors...this page will probably work later

One very quick way around this is, when you're viewing the "Your connection is not private" screen:

type badidea

type thisisunsafe (credit to The Java Guy for finding the new passphrase)

That will allow the security exception when Chrome is otherwise not allowing the exception to be set via clickthrough, e.g. for this HSTS case.

This is only recommended for local connections and local-network virtual machines, obviously, but it has the advantage of working for VMs being used for development (e.g. on port-forwarded local connections) and not just direct localhost connections.

Note: the Chrome developers have changed this passphrase in the past, and may do so again. If badidea ceases to work, please leave a note here if you learn the new passphrase. I'll try to do the same.

Edit: as of 30 Jan 2018 this passphrase appears to no longer work.

If I can hunt down a new one I'll post it here. In the meantime I'm going to take the time to set up a self-signed certificate using the method outlined in this stackoverflow post:

How to create a self-signed certificate with openssl?

Edit: as of 1 Mar 2018 and Chrome Version 64.0.3282.186 this passphrase works again for HSTS-related blocks on .dev sites.

Edit: as of 9 Mar 2018 and Chrome Version 65.0.3325.146 the badidea passphrase no longer works.

Edit 2: the trouble with self-signed certificates seems to be that, with security standards tightening across the board these days, they cause their own errors to be thrown (nginx, for example, refuses to load an SSL/TLS cert that includes a self-signed cert in the chain of authority, by default).

The solution I'm going with now is to swap out the top-level domain on all my .app and .dev development sites with .test or .localhost. Chrome and Safari will no longer accept insecure connections to standard top-level domains (including .app).

The current list of standard top-level domains can be found in this Wikipedia article, including special-use domains:

Wikipedia: List of Internet Top Level Domains: Special Use Domains

These top-level domains seem to be exempt from the new https-only restrictions:

  • .local
  • .localhost
  • .test
  • (any custom/non-standard top-level domain)

See the answer and link from codinghands to the original question for more information:

answer from codinghands

grabbing first row in a mysql query only

You didn't specify how the order is determined, but this will give you a rank value in MySQL:

       @rownum := @rownum +1 AS rank
  JOIN (SELECT @rownum := 0) r
 WHERE = 'sarmen'

Then you can pick out what rows you want, based on the rank value.

Should Jquery code go in header or footer?

For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.

C library function to perform sort

C/C++ standard library <stdlib.h> contains qsort function.

This is not the best quick sort implementation in the world but it fast enough and VERY EASY to be used... the formal syntax of qsort is:


The only thing that you need to implement is the compare_function, which takes in two arguments of type "const void", which can be cast to appropriate data structure, and then return one of these three values:

  • negative, if a should be before b
  • 0, if a equal to b
  • positive, if a should be after b

1. Comparing a list of integers:

simply cast a and b to integers if x < y,x-y is negative, x == y, x-y = 0, x > y, x-y is positive x-y is a shortcut way to do it :) reverse *x - *y to *y - *x for sorting in decreasing/reverse order

int compare_function(const void *a,const void *b) {
int *x = (int *) a;
int *y = (int *) b;
return *x - *y;

2. Comparing a list of strings:

For comparing string, you need strcmp function inside <string.h> lib. strcmp will by default return -ve,0,ve appropriately... to sort in reverse order, just reverse the sign returned by strcmp

#include <string.h>
int compare_function(const void *a,const void *b) {
return (strcmp((char *)a,(char *)b));

3. Comparing floating point numbers:

int compare_function(const void *a,const void *b) {
double *x = (double *) a;
double *y = (double *) b;
// return *x - *y; // this is WRONG...
if (*x < *y) return -1;
else if (*x > *y) return 1; return 0;

4. Comparing records based on a key:

Sometimes you need to sort a more complex stuffs, such as record. Here is the simplest way to do it using qsort library.

typedef struct {
int key;
double value;
} the_record;

int compare_function(const void *a,const void *b) {
the_record *x = (the_record *) a;
the_record *y = (the_record *) b;
return x->key - y->key;

cartesian product in pandas

I find using pandas MultiIndex to be the best tool for the job. If you have a list of lists lists_list, call pd.MultiIndex.from_product(lists_list) and iterate over the result (or use it in DataFrame index).

Git undo local branch delete

First: back up your entire directory, including the .git directory.

Second: You can use git fsck --lost-found to obtain the ID of the lost commits.

Third: rebase or merge onto the lost commit.

Fourth: Always think twice before using -D or --force with git :)

You could also read this good discussion of how to recover from this kind of error.

EDIT: By the way, don't run git gc (or allow it to run by itself - i.e. don't run git fetch or anything similar) or you may lose your commits for ever.

IntelliJ IDEA 13 uses Java 1.5 despite setting to 1.7

I had the following property working for me in IntelliJ 2017


Detect change to selected date with bootstrap-datepicker

Here is my code for that:

$('#date-daily').datepicker().on('changeDate', function(e) {

Just uncomment the one you prefer. The first option changes the value of other input element. The second one alerts the date with datepicker default format. The third one alerts the date with your own custom format. The last option outputs to log (default format date).

It's your choice to use the , e.dates (for múltiple date input) or e.format(...).

here some more info

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

A simple solution that no one else has said but worked for me was not running without sudo or not as root.

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

How do I sort a dictionary by value?

As simple as: sorted(dict1, key=dict1.get)

Well, it is actually possible to do a "sort by dictionary values". Recently I had to do that in a Code Golf (Stack Overflow question Code golf: Word frequency chart). Abridged, the problem was of the kind: given a text, count how often each word is encountered and display a list of the top words, sorted by decreasing frequency.

If you construct a dictionary with the words as keys and the number of occurrences of each word as value, simplified here as:

from collections import defaultdict
d = defaultdict(int)
for w in text.split():
    d[w] += 1

then you can get a list of the words, ordered by frequency of use with sorted(d, key=d.get) - the sort iterates over the dictionary keys, using the number of word occurrences as a sort key .

for w in sorted(d, key=d.get, reverse=True):
    print(w, d[w])

I am writing this detailed explanation to illustrate what people often mean by "I can easily sort a dictionary by key, but how do I sort by value" - and I think the original post was trying to address such an issue. And the solution is to do sort of list of the keys, based on the values, as shown above.

What is Vim recording and how can it be disabled?

Type :h recording to learn more.

                           *q* *recording*
q{0-9a-zA-Z"}           Record typed characters into register {0-9a-zA-Z"}
                        (uppercase to append).  The 'q' command is disabled
                        while executing a register, and it doesn't work inside
                        a mapping.  {Vi: no recording}

q                       Stops recording.  (Implementation note: The 'q' that
                        stops recording is not stored in the register, unless
                        it was the result of a mapping)  {Vi: no recording}

@{0-9a-z".=*}           Execute the contents of register {0-9a-z".=*} [count]
                        times.  Note that register '%' (name of the current
                        file) and '#' (name of the alternate file) cannot be
                        used.  For "@=" you are prompted to enter an
                        expression.  The result of the expression is then
                        executed.  See also |@:|.  {Vi: only named registers}

Java - checking if parseInt throws exception

You could try


It is part of org/apache/commons/lang3/math/NumberUtils and it checks whether the string can be parsed by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String).

See below:

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

{"<user xmlns=''> was not expected.} Deserializing Twitter XML

XmlSerializer xs = new XmlSerializer(typeof(User), new XmlRootAttribute("yourRootName")); 

How to draw a dotted line with css?

Add following attribute to the element you want to have dotted line.

style="border-bottom: 1px dotted #ff0000;"

Get Absolute URL from Relative path (refactored method)

Still nothing good enough using native stuff. Here is what I ended up with:

public static string GetAbsoluteUrl(string url)
    if (String.IsNullOrEmpty(url))
        return String.Empty;

    if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
        return url;

    HttpContext context = HttpContext.Current;

    if (url.StartsWith("~/"))
        url = (context.Handler as Page).ResolveUrl(url);

    string port = (context.Request.Url.Port != 80 && context.Request.Url.Port != 443) ? ":" + context.Request.Url.Port : String.Empty;
    return context.Request.Url.Scheme + Uri.SchemeDelimiter + context.Request.Url.Host + port + "/" + url.TrimStart('/');

Ways to eliminate switch in code

I think that what you are looking for is the Strategy Pattern.

This can be implemented in a number of ways, which have been mentionned in other answers to this question, such as:

  • A map of values -> functions
  • Polymorphism. (the sub-type of an object will decide how it handles a specific process).
  • First class functions.

How to send POST request?

If you don't want to use a module you have to install like requests, and your use case is very basic, then you can use urllib2

urllib2.urlopen(url, body)

See the documentation for urllib2 here:

Eloquent ORM laravel 5 Get Array of ids

You may also use all() method to get array of selected attributes.

$test=test::select('id')->where('id' ,'>' ,0)->all();


Creating random numbers with no duplicates

Following code create a sequence random number between [1,m] that was not generated before.

public class NewClass {

    public List<Integer> keys = new ArrayList<Integer>();

    public int rand(int m) {
        int n = (int) (Math.random() * m + 1);
        if (!keys.contains(n)) {
            return n;
        } else {
            return rand(m);

    public static void main(String[] args) {
        int m = 4;
        NewClass ne = new NewClass();
        for (int i = 0; i < 4; i++) {
        System.out.println("list: " + ne.keys);

What is the use of BindingResult interface in spring MVC?

Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.

Then, you can check this object looking for validation errors:

validator.validate(modelObject, bindingResult);  
if (bindingResult.hasErrors()) {  
    // do something  

Get Today's date in Java at midnight time

Defining ‘Midnight’

The word “midnight” is tricky to define.

Some think of it as the moment before a new day starts. Trying to represent that in software as tricky as the last moment of the day can always be subdivided as a smaller fraction of a second.

I suggest a better way of thinking about this is to get “first moment of the day”.

This supports the commonly used approach of defining a span of time as ‘Half-Open’, where the beginning is inclusive while the ending is exclusive. So a full day starts with the first moment of the day and runs up to, but not including, the first moment of the following day. A full day would like this (notice the date going from the 3rd to the 4th):



If using the Joda-Time library, call withTimeAtStartOfDay.

Note how we specify the time zone. If omitted, the JVM’s current default time zone is implicitly applied. Better to be explicit.

DateTime todayStart = DateTimeZone.forID( "America/Montreal" ) ).withTimeAtStartOfDay() ;

If using Java 8 or later, better to use the java.time package built into Java. See sibling Answer by Jens Hoffman.

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for

SQLite select where empty?

Maybe you mean

select x
from some_table
where some_column is null or some_column = ''

but I can't tell since you didn't really ask a question.

setTimeout or setInterval?

Your code will have different execution intevals, and in some projects, such as online games it's not acceptable. First, what should you do, to make your code work with same intevals, you should change "myTimeoutFunction" to this:

function myTimeoutFunction()
    setTimeout(myTimeoutFunction, 1000);

After this change, it will be equal to

function myTimeoutFunction()
setInterval(myTimeoutFunction, 1000);

But, you will still have not stable result, because JS is single-threaded. For now, if JS thread will be busy with something, it will not be able to execute your callback function, and execution will be postponed for 2-3 msec. Is you have 60 executions per second, and each time you have random 1-3 sec delay, it will be absolutely not acceptable (after one minute it will be around 7200 msec delay), and I can advice to use something like this:

    function Timer(clb, timeout) {
        this.clb = clb;
        this.timeout = timeout;
        this.stopTimeout = null;
        this.precision = -1;

    Timer.prototype.start = function() {
        var me = this;
        var now = new Date();
        if(me.precision === -1) {
            me.precision = now.getTime();
        me.stopTimeout = setTimeout(function(){
        }, me.precision - now.getTime() + me.timeout);
        me.precision += me.timeout;

    Timer.prototype.stop = function() {
        this.precision = -1;

    function myTimeoutFunction()

    var timer = new Timer(myTimeoutFunction, 1000);

This code will guarantee stable execution period. Even thread will be busy, and your code will be executed after 1005 mseconds, next time it will have timeout for 995 msec, and result will be stable.