Programs & Examples On #Jline

JLine is a Java library for handling console input. It is similar in functionality to BSD editline and GNU readline. People familiar with the readline/editline capabilities for modern shells (such as bash and tcsh) will find most of the command editing features of JLine to be familiar.

How do I iterate through table rows and cells in JavaScript?

If you want one with a functional style, like this:

    const table = document.getElementById("mytab1");
    const cells = table.rows.toArray()
                  .flatMap(row => row.cells.toArray())
                  .map(cell => cell.innerHTML); //["col1 Val1", "col2 Val2", "col1 Val3", "col2 Val4"]

You may modify the prototype object of HTMLCollection (allowing to use in a way that resembles extension methods in C#) and embed into it a function that converts collection into array, allowing to use higher order funcions with the above style (kind of linq style in C#):

    Object.defineProperty(HTMLCollection.prototype, "toArray", {
        value: function toArray() {
            return Array.prototype.slice.call(this, 0);
        },
        writable: true,
        configurable: true
    });

Writing .csv files from C++

There is nothing special about a CSV file. You can create them using a text editor by simply following the basic rules. The RFC 4180 (tools.ietf.org/html/rfc4180) accepted separator is the comma ',' not the semi-colon ';'. Programs like MS Excel expect a comma as a separator.

There are some programs that treat the comma as a decimal and the semi-colon as a separator, but these are technically outside of the "accepted" standard for CSV formatted files.

So, when creating a CSV you create your filestream and add your lines like so:

#include <iostream>
#include <fstream>
int main( int argc, char* argv[] )
{
      std::ofstream myfile;
      myfile.open ("example.csv");
      myfile << "This is the first cell in the first column.\n";
      myfile << "a,b,c,\n";
      myfile << "c,s,v,\n";
      myfile << "1,2,3.456\n";
      myfile << "semi;colon";
      myfile.close();
      return 0;
}

This will result in a CSV file that looks like this when opened in MS Excel:

Image of CSV file created with C++

How to use sbt from behind proxy?

Using

sbt -Dhttp.proxyHost=yourServer-Dhttps.proxyHost=yourServer -Dhttp.proxyPort=yourPort -Dhttps.proxyPort=yourPort

works in Ubuntu 15.10 x86_64 x86_64 GNU/Linux.

Replace yourServer by the proper address without the http:// nor https:// prefixes in Dhttp and Dhttps, respectively. Remember to avoid the quotation marks. No usr/pass included in the code-line, to include that just add -Dhttp.proxyUser=usr -Dhttp.proxyPassword=pass with the same typing criteria. Thanks @Jacek Laskowski!. Cheers

PHP form - on submit stay on same page

You can use the # action in a form action:

<?php
    if(isset($_POST['SubmitButton'])){ // Check if form was submitted

        $input = $_POST['inputText']; // Get input text
        $message = "Success! You entered: " . $input;
    }
?>

<html>
    <body>
        <form action="#" method="post">
            <?php echo $message; ?>
            <input type="text" name="inputText"/>
            <input type="submit" name="SubmitButton"/>
        </form>
    </body>
</html>

Using classes with the Arduino

Can you provide an example of what did not work? As you likely know, the Wiring language is based on C/C++, however, not all of C++ is supported.

Whether you are allowed to create classes in the Wiring IDE, I'm not sure (my first Arduino is in the mail right now). I do know that if you wrote a C++ class, compiled it using AVR-GCC, then loaded it on your Arduino using AVRDUDE, it would work.

The most efficient way to implement an integer based power function pow(int, int)

I use recursive, if the exp is even,5^10 =25^5.

int pow(float base,float exp){
   if (exp==0)return 1;
   else if(exp>0&&exp%2==0){
      return pow(base*base,exp/2);
   }else if (exp>0&&exp%2!=0){
      return base*pow(base,exp-1);
   }
}

If file exists then delete the file

IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in  Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat

How to disable auto-play for local video in iframe

<iframe width="420" height="315"
    src="https://www.youtube.com/embed/aNOgO7aNslo?rel=0">
</iframe>

You're supposed to put the characters ?rel=0 after the YouTube video unique link and before the quotations. it worked for me

Table with fixed header and fixed column on pure css

Something like this may work for you... It will probably require you to have set column widths for your header row.

thead { 
    position: fixed;
}

http://jsfiddle.net/vkhNC/

Update:

I am not convinced that the example you gave is possible with just CSS. I would love for someone to prove me wrong. Here is what I have so far. It is not the finished product but it could be a start for you. I hope this points you in a helpful direction, wherever that may be.

Regex Last occurrence?

What about this regex: \\[^\\]+$

Why is synchronized block better than synchronized method?

One classic difference between Synchronized block and Synchronized method is that Synchronized method locks the entire object. Synchronized block just locks the code within the block.

Synchronized method: Basically these 2 sync methods disable multithreading. So one thread completes the method1() and the another thread waits for the Thread1 completion.

class SyncExerciseWithSyncMethod {

public synchronized void method1() {
    try {
        System.out.println("In Method 1");
        Thread.sleep(5000);
    } catch (Exception e) {
        System.out.println("Catch of method 1");
    } finally {
        System.out.println("Finally of method 1");
    }

}

public synchronized void method2() {
    try {
        for (int i = 1; i < 10; i++) {
            System.out.println("Method 2 " + i);
            Thread.sleep(1000);
        }
    } catch (Exception e) {
        System.out.println("Catch of method 2");
    } finally {
        System.out.println("Finally of method 2");
    }
}

}

Output

In Method 1

Finally of method 1

Method 2 1

Method 2 2

Method 2 3

Method 2 4

Method 2 5

Method 2 6

Method 2 7

Method 2 8

Method 2 9

Finally of method 2


Synchronized block: Enables multiple threads to access the same object at same time [Enables multi-threading].

class SyncExerciseWithSyncBlock {

public Object lock1 = new Object();
public Object lock2 = new Object();

public void method1() {
    synchronized (lock1) {
        try {
            System.out.println("In Method 1");
            Thread.sleep(5000);
        } catch (Exception e) {
            System.out.println("Catch of method 1");
        } finally {
            System.out.println("Finally of method 1");
        }
    }

}

public void method2() {

    synchronized (lock2) {
        try {
            for (int i = 1; i < 10; i++) {
                System.out.println("Method 2 " + i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println("Catch of method 2");
        } finally {
            System.out.println("Finally of method 2");
        }
    }
}

}

Output

In Method 1

Method 2 1

Method 2 2

Method 2 3

Method 2 4

Method 2 5

Finally of method 1

Method 2 6

Method 2 7

Method 2 8

Method 2 9

Finally of method 2

Laravel Escaping All HTML in Blade Template

use this tag {!! description text !!}

Simple way to compare 2 ArrayLists

private int compareLists(List<String> list1, List<String> list2){
    Collections.sort(list1);
    Collections.sort(list2);

    int maxIteration = 0;
    if(list1.size() == list2.size() || list1.size() < list2.size()){
        maxIteration = list1.size();
    } else {
        maxIteration = list2.size();
    }

    for (int index = 0; index < maxIteration; index++) {
        int result = list1.get(index).compareTo(list2.get(index));
        if (result == 0) {
            continue;
        } else {
            return result;
        }
    }
    return list1.size() - list2.size();
}

Download single files from GitHub

This is what worked for me just now...

  1. Open the raw file in a seperate tab.

  2. Copy the whole thing in your notepad in a new file.

  3. Save the file in the extension it originally had

tested with a php file that i downloaded just now (at time of answer)

How to find my Subversion server version number?

To find the version of the subversion REPOSITORY you can:

  1. Look to the repository on the web and on the bottom of the page it will say something like:
    "Powered by Subversion version 1.5.2 (r32768)."
  2. From the command line: <insert curl, grep oneliner here>

If not displayed, view source of the page

<svn version="1.6.13 (r1002816)" href="http://subversion.tigris.org/"> 

Now for the subversion CLIENT:

svn --version

will suffice

Add A Year To Today's Date

This code adds the amount of years required for a date.

var d = new Date();
// => Tue Oct 01 2017 00:00:00 GMT-0700 (PDT)

var amountOfYearsRequired = 2;
d.setFullYear(d.getFullYear() + amountOfYearsRequired);
// => Tue Oct 01 2019 00:00:00 GMT-0700 (PDT)

Function inside a function.?

function inside a function or so called nested functions are very usable if you need to do some recursion processes such as looping true multiple layer of array or a file tree without multiple loops or sometimes i use it to avoid creating classes for small jobs which require dividing and isolating functionality among multiple functions. but before you go for nested functions you have to understand that

  1. child function will not be available unless the main function is executed
  2. Once main function got executed the child functions will be globally available to access
  3. if you need to call the main function twice it will try to re define the child function and this will throw a fatal error

so is this mean you cant use nested functions? No, you can with the below workarounds

first method is to block the child function being re declaring into global function stack by using conditional block with function exists, this will prevent the function being declared multiple times into global function stack.

function myfunc($a,$b=5){
    if(!function_exists("child")){
        function child($x,$c){
            return $c+$x;   
        }
    }
    
    try{
        return child($a,$b);
    }catch(Exception $e){
        throw $e;
    }
    
}

//once you have invoke the main function you will be able to call the child function
echo myfunc(10,20)+child(10,10);

and the second method will be limiting the function scope of child to local instead of global, to do that you have to define the function as a Anonymous function and assign it to a local variable, then the function will only be available in local scope and will re declared and invokes every time you call the main function.

function myfunc($a,$b=5){
    $child = function ($x,$c){
        return $c+$x;   
    };
    
    try{
        return $child($a,$b);
    }catch(Exception $e){
        throw $e;
    }
    
}

echo myfunc(10,20);

remember the child will not be available outside the main function or global function stack

How to check that Request.QueryString has a specific value or not in ASP.NET?

To resolve your problem, write the following line on your page's Page_Load method.

if (String.IsNullOrEmpty(Request.QueryString["aspxerrorpath"])) return;

.Net 4.0 provides more closer look to null, empty or whitespace strings, use it as shown in the following line:

if(string.IsNullOrWhiteSpace(Request.QueryString["aspxerrorpath"])) return;

This will not run your next statements (your business logics) if query string does not have aspxerrorpath.

Declare an empty two-dimensional array in Javascript?

We usually know the number of columns but maybe not rows (records). Here is an example of my solution making use of much of the above here. (For those here more experienced in JS than me - pretty much everone - any code improvement suggestions welcome)

     var a_cols = [null,null,null,null,null,null,null,null,null];
     var a_rxc  = [[a_cols]];

     // just checking  var arr =  a_rxc.length ; //Array.isArray(a_rxc);
     // alert ("a_rxc length=" + arr) ; Returned 1 
     /* Quick test of array to check can assign new rows to a_rxc. 
        i can be treated as the rows dimension and  j the columns*/
       for (i=0; i<3; i++) {
          for (j=0; j<9; j++) {
            a_rxc[i][j] = i*j;
            alert ("i=" + i + "j=" + j + "  "  + a_rxc[i][j] );
           }
          if (i+1<3) { a_rxc[i+1] = [[a_cols]]; }
        }

And if passing this array to the sever the ajax that works for me is

 $.post("../ajax/myservercode.php",
       {
        jqArrArg1 : a_onedimarray,
        jqArrArg2 : a_rxc
       },
       function(){  },"text" )
        .done(function(srvresp,status) { $("#id_PageContainer").html(srvresp);} ) 
        .fail(function(jqXHR,status) { alert("jqXHR AJAX error " + jqXHR + ">>" + status );} );

How to resolve the error on 'react-native start'

https://github.com/facebook/metro/issues/453

for who still get this error without official patch in react-native , expo

use yarn and add this setting into package.json

{
  ...
  "resolutions": {
    "metro-config": "bluelovers/metro-config-hotfix-0.56.x"
  },
 ...

awk without printing newline

If Perl is an option, here is a solution using fedorqui's example:

seq 5 | perl -ne 'chomp; print "$_ "; END{print "\n"}'

Explanation:
chomp removes the newline
print "$_ " prints each line, appending a space
the END{} block is used to print a newline

output: 1 2 3 4 5

Confused by python file mode "w+"

Here is a list of the different modes of opening a file:

  • r

    Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

  • rb

    Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

  • r+

    Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

  • rb+

    Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

  • w

    Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • wb

    Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

  • w+

    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • wb+

    Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

  • a

    Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • ab

    Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

  • a+

    Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

  • ab+

    Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

How to get string objects instead of Unicode from JSON?

That's because json has no difference between string objects and unicode objects. They're all strings in javascript.

I think JSON is right to return unicode objects. In fact, I wouldn't accept anything less, since javascript strings are in fact unicode objects (i.e. JSON (javascript) strings can store any kind of unicode character) so it makes sense to create unicode objects when translating strings from JSON. Plain strings just wouldn't fit since the library would have to guess the encoding you want.

It's better to use unicode string objects everywhere. So your best option is to update your libraries so they can deal with unicode objects.

But if you really want bytestrings, just encode the results to the encoding of your choice:

>>> nl = json.loads(js)
>>> nl
[u'a', u'b']
>>> nl = [s.encode('utf-8') for s in nl]
>>> nl
['a', 'b']

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

OnClickListener in Android Studio

protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_my);
    titolorecuperato = (TextView) findViewById(R.id.textView);
    String stitolo = titolorecuperato.getText().toString();

    Button btnHome = (Button) findViewById(R.id.button);

    btnHome.setOnClickListener(new View.OnClickListener() {

       @Override
        public void onClick(View view) {

       }
});

same thing as Nic007 said before.

You do need to write code inside "onCreate" method. Sorry me too for the indent... (first comment here)

Spring Data JPA and Exists query

Apart from the accepted answer, I'm suggesting another alternative. Use QueryDSL, create a predicate and use the exists() method that accepts a predicate and returns Boolean.

One advantage with QueryDSL is you can use the predicate for complicated where clauses.

How to use private Github repo as npm dependency

It can be done via https and oauth or ssh.

https and oauth: create an access token that has "repo" scope and then use this syntax:

"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"

or

ssh: setup ssh and then use this syntax:

"package-name": "git+ssh://[email protected]:<user>/<repo>.git"

(note the use of colon instead of slash before user)

Convert boolean result into number/integer

I just came across this shortcut today.

~~(true)

~~(false)

People much smarter than I can explain:

http://james.padolsey.com/javascript/double-bitwise-not/

Python JSON encoding

The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.

From www.json.org:

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

How do I count occurrence of duplicate items in array

Count duplicate element of an array in PHP without using in-built function

$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
        for($i=0;$i<$arrlength-1;$i++)
        {
          $key=$arraychars[$i];
          if($arrCount[$key]>=1)
            {
              $arrCount[$key]++;
            } else{
              $arrCount[$key]=1;
        }
        echo $arraychars[$i]."<br>";
     }
        echo "<pre>";
        print_r($arrCount);

Detect if a page has a vertical scrollbar?

try this:

var hasVScroll = document.body.scrollHeight > document.body.clientHeight;

This will only tell you if the vertical scrollHeight is bigger than the height of the viewable content, however. The hasVScroll variable will contain true or false.

If you need to do a more thorough check, add the following to the code above:

// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");

// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible" 
             || cStyle.overflowY == "visible"
             || (hasVScroll && cStyle.overflow == "auto")
             || (hasVScroll && cStyle.overflowY == "auto");

How to find the minimum value in an ArrayList, along with the index number? (Java)

You have to traverse the whole array and keep two auxiliary values:

  • The minimum value you find (on your way towards the end)
  • The index of the place where you found the min value

Suppose your array is called myArray. At the end of this code minIndex has the index of the smallest value.

var min = Number.MAX_VALUE; //the largest number possible in JavaScript
var minIndex = -1;

for (int i=0; i<myArray.length; i++){
   if (myArray[i] < min){
      min = myArray[i];
      minIndex = i;
   }
}

This is assuming the worst case scenario: a totally random array. It is an O(n) algorithm or order n algorithm, meaning that if you have n elements in your array, then you have to look at all of them before knowing your answer. O(n) algorithms are the worst ones because they take a lot of time to solve the problem.

If your array is sorted or has any other specific structure, then the algorithm can be optimized to be faster.

Having said that, though, unless you have a huge array of thousands of values then don't worry about optimization since the difference between an O(n) algorithm and a faster one would not be noticeable.

encapsulation vs abstraction real world example

Encapsulation helps in adhering to Single Responsibility principle and Abstraction helps in adhering to Code to Interface and not to implement.

Say I have a class for Car : Service Provider Class and Driver Class : Service Consumer Class.

For Abstraction : we define abstract Class for CAR and define all the abstract methods in it , which are function available in the car like : changeGear(), applyBrake().

Now the actual Car (Concrete Class i.e. like Mercedes , BMW will implement these methods in their own way and abstract the execution and end user will still apply break and change gear for particular concrete car instance and polymorphically the execution will happen as defined in concrete class.

For Encapsulation : Now say Mercedes come up with new feature/technology: Anti Skid Braking, while implementing the applyBrake(), it will encapsulate this feature in applyBrake() method and thus providing cohesion, and service consumer will still access by same method applyBrake() of the car object. Thus Encapsulation lets further in same concrete class implementation.

How do I get the last character of a string using an Excel function?

=RIGHT(A1)  

is quite sufficient (where the string is contained in A1).

Similar in nature to LEFT, Excel's RIGHT function extracts a substring from a string starting from the right-most character:

SYNTAX

RIGHT( text, [number_of_characters] )

Parameters or Arguments

text

The string that you wish to extract from.

number_of_characters

Optional. It indicates the number of characters that you wish to extract starting from the right-most character. If this parameter is omitted, only 1 character is returned.

Applies To

Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Since number_of_characters is optional and defaults to 1 it is not required in this case.

However, there have been many issues with trailing spaces and if this is a risk for the last visible character (in general):

=RIGHT(TRIM(A1))  

might be preferred.

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

Why controllers are needed

The difference between link and controller comes into play when you want to nest directives in your DOM and expose API functions from the parent directive to the nested ones.

From the docs:

Best Practice: use controller when you want to expose an API to other directives. Otherwise use link.

Say you want to have two directives my-form and my-text-input and you want my-text-input directive to appear only inside my-form and nowhere else.

In that case, you will say while defining the directive my-text-input that it requires a controller from the parent DOM element using the require argument, like this: require: '^myForm'. Now the controller from the parent element will be injected into the link function as the fourth argument, following $scope, element, attributes. You can call functions on that controller and communicate with the parent directive.

Moreover, if such a controller is not found, an error will be raised.

Why use link at all

There is no real need to use the link function if one is defining the controller since the $scope is available on the controller. Moreover, while defining both link and controller, one does need to be careful about the order of invocation of the two (controller is executed before).

However, in keeping with the Angular way, most DOM manipulation and 2-way binding using $watchers is usually done in the link function while the API for children and $scope manipulation is done in the controller. This is not a hard and fast rule, but doing so will make the code more modular and help in separation of concerns (controller will maintain the directive state and link function will maintain the DOM + outside bindings).

Why both no-cache and no-store should be used in HTTP response?

Note that Internet Explorer from version 5 up to 8 will throw an error when trying to download a file served via https and the server sending Cache-Control: no-cache or Pragma: no-cache headers.

See http://support.microsoft.com/kb/812935/en-us

The use of Cache-Control: no-store and Pragma: private seems to be the closest thing which still works.

chrome : how to turn off user agent stylesheet settings?

https://developers.google.com/chrome-developer-tools/docs/settings

  1. Open Chrome dev tools
  2. Click gear icon on bottom right
  3. In General section, check or uncheck "Show user agent styles".

How to remove underline from a name on hover

_x000D_
_x000D_
legend.green-color{_x000D_
    color:green !important;_x000D_
}
_x000D_
_x000D_
_x000D_

Why use pip over easy_install?

As an addition to fuzzyman's reply:

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers - Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.

Print list without brackets in a single row

For array of integer type, we need to change it to string type first and than use join function to get clean output without brackets.

    arr = [1, 2, 3, 4, 5]    
    print(', '.join(map(str, arr)))

OUTPUT - 1, 2, 3, 4, 5

For array of string type, we need to use join function directly to get clean output without brackets.

    arr = ["Ram", "Mohan", "Shyam", "Dilip", "Sohan"]
    print(', '.join(arr)

OUTPUT - Ram, Mohan, Shyam, Dilip, Sohan

Reverse of JSON.stringify?

JSON.stringify and JSON.parse are almost oposites, and "usually" this kind of thing will work:

var obj = ...;
var json = JSON.stringify(obj);  
var obj2 = JSON.parse(json);

so that obj and obj2 are "the same".

However there are some limitations to be aware of. Often these issues dont matter as you're dealing with simple objects. But I'll illustrate some of them here, using this helper function:

function jsonrepack( obj ) { return JSON.parse(JSON.stringify(obj) ); }
  • You'll only get ownProperties of the object and lose prototypes:

    var MyClass = function() { this.foo="foo"; } 
    MyClass.prototype = { bar:"bar" }
    
    var o = new MyClass();
    var oo = jsonrepack(o);
    console.log(oo.bar); // undefined
    console.log( oo instanceof MyClass ); // false
    
  • You'll lose identity:

    var o = {};
    var oo = jsonrepack(o);
    console.log( o === oo ); // false
    
  • Functions dont survive:

    jsonrepack( { f:function(){} } ); // Returns {}
    
  • Date objects end up as strings:

    jsonrepack(new Date(1990,2,1)); // Returns '1990-02-01T16:00:00.000Z'
    
  • Undefined values dont survive:

    var v = { x:undefined }
    console.log("x" in v);              // true
    console.log("x" in jsonrepack(v));  // false
    
  • Objects that provide a toJSON function may not behave correctly.

    x = { f:"foo", toJSON:function(){ return "EGAD"; } }
    jsonrepack(x) // Returns 'EGAD'
    

I'm sure there are issues with other built-in-types too. (All this was tested using node.js so you may get slightly different behaviour depending on your environment too).

When it does matter it can sometimes be overcome using the additional parameters of JSON.parse and JSON.stringify. For example:

function MyClass (v) {
   this.date = new Date(v.year,1,1);
   this.name = "an object";
};

MyClass.prototype.dance = function() {console.log("I'm dancing"); }

var o = new MyClass({year:2010});
var s = JSON.stringify(o);

// Smart unpack function
var o2 = JSON.parse( s, function(k,v){
  if(k==="") { 
     var rv = new MyClass(1990,0,0);
     rv.date = v.date;
     rv.name = v.name;
     return rv
  } else if(k==="date") {
    return new Date( Date.parse(v) );
  } else { return v; } } );

console.log(o);             // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o.constructor); // [Function: MyClass]
o.dance();                  // I'm dancing

console.log(o2);            // { date: <Mon Feb 01 2010 ...>, name: 'an object' }
console.log(o2.constructor) // [Function: MyClass]        
o2.dance();                 // I'm dancing

google chrome extension :: console.log() from background page?

You can open the background page's console if you click on the "background.html" link in the extensions list.

To access the background page that corresponds to your extensions open Settings / Extensions or open a new tab and enter chrome://extensions. You will see something like this screenshot.

Chrome extensions dialogue

Under your extension click on the link background page. This opens a new window. For the context menu sample the window has the title: _generated_background_page.html.

Is it possible to get the index you're sorting over in Underscore.js?

When available, I believe that most lodash array functions will show the iteration. But sorting isn't really an iteration in the same way: when you're on the number 66, you aren't processing the fourth item in the array until it's finished. A custom sort function will loop through an array a number of times, nudging adjacent numbers forward or backward, until the everything is in its proper place.

jQuery UI Tabs - How to Get Currently Selected Tab Index

When are you trying to access the ui object? ui will be undefined if you try to access it outside of the bind event. Also, if this line

var selectedTab = $("#TabList").tabs().data("selected.tabs");

is ran in the event like this:

$("#TabList").bind("tabsselect", function(event, ui) {
  var selectedTab = $("#TabList").tabs().data("selected.tabs");
});

selectedTab will equal the current tab at that point in time (the "previous" one.) This is because the "tabsselect" event is called before the clicked tab becomes the current tab. If you still want to do it this way, using "tabsshow" instead will result in selectedTab equaling the clicked tab.

However, that seems over-complex if all you want is the index. ui.index from within the event or $("#TabList").tabs().data("selected.tabs") outside of the event should be all that you need.

How to Pass data from child to parent component Angular

Register the EventEmitter in your child component as the @Output:

@Output() onDatePicked = new EventEmitter<any>();

Emit value on click:

public pickDate(date: any): void {
    this.onDatePicked.emit(date);
}

Listen for the events in your parent component's template:

<div>
    <calendar (onDatePicked)="doSomething($event)"></calendar>
</div>

and in the parent component:

public doSomething(date: any):void {
    console.log('Picked date: ', date);
}

It's also well explained in the official docs: Component interaction.

Failed to install Python Cryptography package with PIP and setup.py

This solved the problem for me (Ubuntu 16.04):

sudo apt-get install build-essential libssl-dev libffi-dev python-dev python3-dev

and then it was working like this:

pip install cryptography
pip install pyopenssl ndg-httpsclient pyasn1

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

Java Delegates?

The code described offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:

  class Class1 {
        public void show(String s) { System.out.println(s); }
    }

    class Class2 {
        public void display(String s) { System.out.println(s); }
    }

    // allows static method as well
    class Class3 {
        public static void staticDisplay(String s) { System.out.println(s); }
    }

    public class TestDelegate  {
        public static final Class[] OUTPUT_ARGS = { String.class };
        public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);

        public void main(String[] args)  {
            Delegate[] items = new Delegate[3];

            items[0] = DO_SHOW .build(new Class1(),"show,);
            items[1] = DO_SHOW.build (new Class2(),"display");
            items[2] = DO_SHOW.build(Class3.class, "staticDisplay");

            for(int i = 0; i < items.length; i++) {
                items[i].invoke("Hello World");
            }
        }
    }

Mark error in form using Bootstrap

Bootstrap V3:

Once i was searching for laravel features then i got to know this amazing form validation. Later on, i amended glyphicon icon features. Now, it looks great.

<div class="col-md-12">
<div class="form-group has-error has-feedback">
    <input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>       
    <span class="help-block"><p>The Email field is required.</p></span>                                        
</div>
</div>
<div class="clearfix"></div>

<div class="col-md-6">
<div class="form-group has-error has-feedback">
    <input id="account_holder_name" name="name" type="text" placeholder="Name" class="form-control ">
    <span class="glyphicon glyphicon-remove form-control-feedback"></span>                                            
    <span class="help-block"><p>The Name field is required.</p></span>                                        
</div>
</div>
<div class="col-md-6">
<div class="form-group has-error has-feedback">
 <input id="check_np" name="check_no" type="text" placeholder="Check no" class="form-control ">
 <span class="glyphicon glyphicon-remove form-control-feedback"></span>
<span class="help-block"><p>The Check No. field is required.</p></span>                                       
</div>
</div>

This is what it looks like: enter image description here

Once i completed it i thought i should implement it in Codeigniter as well. So here is the Codeigniter-3 validation with Bootstrap:

Controller

function addData()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','trim|required|valid_email|max_length[128]');
if($this->form_validation->run() == FALSE)
{
//validation fails. Load your view.
$this->loadViews('Load your view','pass your data to view if any');
}
else
{  
 //validation pass. Your code here.
}
}

View

<div class="col-md-12">
<?php 
 $email_error = (form_error('email') ? 'has-error has-feedback' : '');
 if(!empty($email_error)){
 $emailData = '<span class="help-block">'.form_error('email').'</span>';
 $emailClass = $email_error;
 $emailIcon = '<span class="glyphicon glyphicon-remove form-control-feedback"></span>';
}
else{
    $emailClass = $emailIcon = $emailData = '';
 } 
 ?>
<div class="form-group <?= $emailClass ?>">
<input id="enter email" name="email" type="text" placeholder="Enter email" class="form-control ">
<?= $emailIcon ?>
<?= $emailData ?>
</div>
</div>

Output: enter image description here

How to store array or multiple values in one column

Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:

create table foo (
  bar  int[] default '{}'
);

select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]

create index on foo using gin (bar); -- allows to use an index in the above query

But as the prior answer suggests, it will be better to normalize properly.

How do I correct the character encoding of a file?

Follow these steps with Notepad++

1- Copy the original text

2- In Notepad++, open new file, change Encoding -> pick an encoding you think the original text follows. Try as well the encoding "ANSI" as sometimes Unicode files are read as ANSI by certain programs

3- Paste

4- Then to convert to Unicode by going again over the same menu: Encoding -> "Encode in UTF-8" (Not "Convert to UTF-8") and hopefully it will become readable

The above steps apply for most languages. You just need to guess the original encoding before pasting in notepad++, then convert through the same menu to an alternate Unicode-based encoding to see if things become readable.

Most languages exist in 2 forms of encoding: 1- The old legacy ANSI (ASCII) form, only 8 bits, was used initially by most computers. 8 bits only allowed 256 possibilities, 128 of them where the regular latin and control characters, the final 128 bits were read differently depending on the PC language settings 2- The new Unicode standard (up to 32 bit) give a unique code for each character in all currently known languages and plenty more to come. if a file is unicode it should be understood on any PC with the language's font installed. Note that even UTF-8 goes up to 32 bit and is just as broad as UTF-16 and UTF-32 only it tries to stay 8 bits with latin characters just to save up disk space

Maximum call stack size exceeded error

This can also cause a Maximum call stack size exceeded error:

var items = [];
[].push.apply(items, new Array(1000000)); //Bad

Same here:

items.push(...new Array(1000000)); //Bad

From the Mozilla Docs:

But beware: in using apply this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. To illustrate this latter case: if such an engine had a limit of four arguments (actual limits are of course significantly higher), it would be as if the arguments 5, 6, 2, 3 had been passed to apply in the examples above, rather than the full array.

So try:

var items = [];
var newItems = new Array(1000000);
for(var i = 0; i < newItems.length; i++){
  items.push(newItems[i]);
}

How to return multiple values?

You can do something like this:

public class Example
{
    public String name;
    public String location;

    public String[] getExample()
    {
        String ar[] = new String[2];
        ar[0]= name;
        ar[1] =  location;
        return ar; //returning two values at once
    }
}

What is difference between 'git reset --hard HEAD~1' and 'git reset --soft HEAD~1'?

This is the main difference between use git reset --hard and git reset --soft:

--soft

Does not touch the index file or the working tree at all (but resets the head to , just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

--hard

Resets the index and working tree. Any changes to tracked files in the working tree since are discarded.

Create line after text with css

Here is how I do this: http://jsfiddle.net/Zz7Wq/2/

I use a background instead of after and use my H1 or H2 to cover the background. Not quite your method above but does work well for me.

CSS

.title-box { background: #fff url('images/bar-orange.jpg') repeat-x left; text-align: left; margin-bottom: 20px;}
.title-box h1 { color: #000; background-color: #fff; display: inline; padding: 0 50px 0 50px; }

HTML

<div class="title-box"><h1>Title can go here</h1></div>
<div class="title-box"><h1>Title can go here this one is really really long</h1></div>

How to send 500 Internal Server Error error from a PHP script

Your code should look like:

<?php
if ( that_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

if ( something_else_happened ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
    header("HTTP/1.0 500 Internal Server Error");
    die();
}

// the script can also fail on the above line
// e.g. a mysql error occurred


header('HTTP/1.1 200 OK');
?>

I assume you stop execution if something goes wrong.

How to set the DefaultRoute to another Route in React Router

You can use Redirect instead of DefaultRoute

<Redirect from="/" to="searchDashboard" />

Update 2019-08-09 to avoid problem with refresh use this instead, thanks to Ogglas

<Redirect exact from="/" to="searchDashboard" />

jQuery first child of "this"

you can use DOM

$(this).children().first()
// is equivalent to
$(this.firstChild)

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

How to echo print statements while executing a sql script

I don't know if this helps:

suppose you want to run a sql script (test.sql) from the command line:

mysql < test.sql

and the contents of test.sql is something like:

SELECT * FROM information_schema.SCHEMATA;
\! echo "I like to party...";

The console will show something like:

CATALOG_NAME    SCHEMA_NAME            DEFAULT_CHARACTER_SET_NAME      
         def    information_schema     utf8
         def    mysql                  utf8
         def    performance_schema     utf8
         def    sys                    utf8
I like to party...

So you can execute terminal commands inside an sql statement by just using \!, provided the script is run via a command line.

\! #terminal_commands

How to pass data from 2nd activity to 1st activity when pressed back? - android

Activity1 should start Activity2 with startActivityForResult().

Activity2 should use setResult() to send data back to Activity1.

In Activity2,

@Override
public void onBackPressed() {
    String data = mEditText.getText();
    Intent intent = new Intent();
    intent.putExtra("MyData", data);
    setResult(resultcode, intent);
}

In Activity1,

onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 1) {
        if(resultCode == RESULT_OK) {
            String myStr=data.getStringExtra("MyData");
            mTextView.setText(myStr);
        }
    }
}

.gitignore file for java eclipse project

You need to add your source files with git add or the GUI equivalent so that Git will begin tracking them.

Use git status to see what Git thinks about the files in any given directory.

Which is better: <script type="text/javascript">...</script> or <script>...</script>

<script type="text/javascript"></script> because its the right way and compatible with all browsers

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

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

Either decorate your root entity with the XmlRoot attribute which will be used at compile time.

[XmlRoot(Namespace = "www.contoso.com", ElementName = "MyGroupName", DataType = "string", IsNullable=true)]

Or specify the root attribute when de serializing at runtime.

XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "user";
// xRoot.Namespace = "http://www.cpandl.com";
xRoot.IsNullable = true;

XmlSerializer xs = new XmlSerializer(typeof(User),xRoot);

GIT: Checkout to a specific folder

If you're working under your feature and don't want to checkout back to master, you can run:

cd ./myrepo

git worktree add ../myrepo_master master

git worktree remove ../myrepo_master

It will create ../myrepo_master directory with master branch commits, where you can continue work

How to check if array element is null to avoid NullPointerException in Java

String labels[] = { "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" }; 

if(Arrays.toString(labels).indexOf("null") > -1)  {
    System.out.println("Array Element Must not be null");
                     (or)
    throw new Exception("Array Element Must not be null");
}        
------------------------------------------------------------------------------------------         

For two Dimensional array

String labels2[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };    

if(Arrays.deepToString(labels2).indexOf("null") > -1)  {
    System.out.println("Array Element Must not be null");
                 (or)
    throw new Exception("Array Element Must not be null");
}    
------------------------------------------------------------------------------------------

same for Object Array    

String ObjectArray[][] = {{ "MH", null, "AP", "KL", "CH", "MP", "GJ", "OR" },{ "MH", "FG", "AP", "KL", "CH", "MP", "GJ", "OR" };    

if(Arrays.deepToString(ObjectArray).indexOf("null") > -1)  {
    System.out.println("Array Element Must not be null");
              (or)
    throw new Exception("Array Element Must not be null");
  }

If you want to find a particular null element, you should use for loop as above said .

C# LINQ select from list

In likeness of how I found this question using Google, I wanted to take it one step further. Lets say I have a string[] states and a db Entity of StateCounties and I just want the states from the list returned and not all of the StateCounties.

I would write:

db.StateCounties.Where(x => states.Any(s => x.State.Equals(s))).ToList();

I found this within the sample of CheckBoxList for nu-get.

How do I import a specific version of a package using go get?

That worked for me

GO111MODULE=on go get -u github.com/segmentio/[email protected]

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);

Switch/toggle div (jQuery)

Since one div is initially hidden, you can simply call toggle for both divs:

<a href="javascript:void(0);" id="forgot-password">forgot password?</a>
<div id="login-form">login form</div>

<div id="recover-password" style="display:none;">recover password</div>

<script type="text/javascript">
$(function(){
  $('#forgot-password').click(function(){
     $('#login-form').toggle();
     $('#recover-password').toggle(); 
  });
});
</script>

pandas groupby sort descending order

Other instance of preserving the order or sort by descending:

In [97]: import pandas as pd                                                                                                    

In [98]: df = pd.DataFrame({'name':['A','B','C','A','B','C','A','B','C'],'Year':[2003,2002,2001,2003,2002,2001,2003,2002,2001]})

#### Default groupby operation:
In [99]: for each in df.groupby(["Year"]): print each                                                                           
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)

### order preserved:
In [100]: for each in df.groupby(["Year"], sort=False): print each                                                               
(2003,    Year name
0  2003    A
3  2003    A
6  2003    A)
(2002,    Year name
1  2002    B
4  2002    B
7  2002    B)
(2001,    Year name
2  2001    C
5  2001    C
8  2001    C)

In [106]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"]))                        
Out[106]: 
        Year name
Year             
2003 0  2003    A
     3  2003    A
     6  2003    A
2002 1  2002    B
     4  2002    B
     7  2002    B
2001 2  2001    C
     5  2001    C
     8  2001    C

In [107]: df.groupby(["Year"], sort=False).apply(lambda x: x.sort_values(["Year"])).reset_index(drop=True)
Out[107]: 
   Year name
0  2003    A
1  2003    A
2  2003    A
3  2002    B
4  2002    B
5  2002    B
6  2001    C
7  2001    C
8  2001    C

How do I change the database name using MySQL?

Unfortunately, MySQL does not explicitly support that (except for dumping and reloading database again).

From http://dev.mysql.com/doc/refman/5.1/en/rename-database.html:

13.1.32. RENAME DATABASE Syntax

RENAME {DATABASE | SCHEMA} db_name TO new_db_name;

This statement was added in MySQL 5.1.7 but was found to be dangerous and was removed in MySQL 5.1.23. ... Use of this statement could result in loss of database contents, which is why it was removed. Do not use RENAME DATABASE in earlier versions in which it is present.

How to convert/parse from String to char in java?

An Essay way :

public class CharToInt{  
public static void main(String[] poo){  
String ss="toyota";
for(int i=0;i<ss.length();i++)
  {
     char c = ss.charAt(i); 
    // int a=c;  
     System.out.println(c); } } 
} 

For Output see this link: Click here

Thanks :-)

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Your RecyclerView in Kotlin

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
        textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
        textViewcolor.text = t.name
    }
}

How long do browsers cache HTTP 301s?

301 is a cacheable response per HTTP RFC and browsers will cache it depending on the HTTP caching headers you have on the response. Use FireBug or Charles to examine response headers to know the exact duration the response will be cached for.

If you would like to control the caching duration, you can use the the HTTP response headers Cache-Control and Expires to do the same. Alternatively, if you don't want to cache the 301 response at all, use the following headers.

Cache-Control: no-store, no-cache, must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT

What is an optional value in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String?

You can refer to this link to get knowledge in deep: https://medium.com/@agoiabeladeyemi/optionals-in-swift-2b141f12f870

SQL Server: Is it possible to insert into two tables at the same time?

I want to stress on using

SET XACT_ABORT ON;

for the MSSQL transaction with multiple sql statements.

See: https://msdn.microsoft.com/en-us/library/ms188792.aspx They provide a very good example.

So, the final code should look like the following:

SET XACT_ABORT ON;

BEGIN TRANSACTION
   DECLARE @DataID int;
   INSERT INTO DataTable (Column1 ...) VALUES (....);
   SELECT @DataID = scope_identity();
   INSERT INTO LinkTable VALUES (@ObjectID, @DataID);
COMMIT

Read all files in a folder and apply a function to each data frame

On the contrary, I do think working with list makes it easy to automate such things.

Here is one solution (I stored your four dataframes in folder temp/).

filenames <- list.files("temp", pattern="*.csv", full.names=TRUE)
ldf <- lapply(filenames, read.csv)
res <- lapply(ldf, summary)
names(res) <- substr(filenames, 6, 30)

It is important to store the full path for your files (as I did with full.names), otherwise you have to paste the working directory, e.g.

filenames <- list.files("temp", pattern="*.csv")
paste("temp", filenames, sep="/")

will work too. Note that I used substr to extract file names while discarding full path.

You can access your summary tables as follows:

> res$`df4.csv`
       A              B        
 Min.   :0.00   Min.   : 1.00  
 1st Qu.:1.25   1st Qu.: 2.25  
 Median :3.00   Median : 6.00  
 Mean   :3.50   Mean   : 7.00  
 3rd Qu.:5.50   3rd Qu.:10.50  
 Max.   :8.00   Max.   :16.00  

If you really want to get individual summary tables, you can extract them afterwards. E.g.,

for (i in 1:length(res))
  assign(paste(paste("df", i, sep=""), "summary", sep="."), res[[i]])

Is std::vector copying the objects with a push_back?

Yes, std::vector<T>::push_back() creates a copy of the argument and stores it in the vector. If you want to store pointers to objects in your vector, create a std::vector<whatever*> instead of std::vector<whatever>.

However, you need to make sure that the objects referenced by the pointers remain valid while the vector holds a reference to them (smart pointers utilizing the RAII idiom solve the problem).

Python-Requests close http connection

As discussed here, there really isn't such a thing as an HTTP connection and what httplib refers to as the HTTPConnection is really the underlying TCP connection which doesn't really know much about your requests at all. Requests abstracts that away and you won't ever see it.

The newest version of Requests does in fact keep the TCP connection alive after your request.. If you do want your TCP connections to close, you can just configure the requests to not use keep-alive.

s = requests.session()
s.config['keep_alive'] = False

Ctrl+click doesn't work in Eclipse Juno

The solution for me was to configure the build path to include the project itself.

  1. Right click on open project.
  2. highlight build path
  3. click on Configure build path…
  4. click on Source
  5. Click Add Folder… button.
  6. Put a check mark next to your project.
  7. Click OK.

If necessary, click the project menu and choose the ‘clean…’ option to rebuild.

jQuery SVG vs. Raphael

I've recently used both Raphael and jQuery SVG - and here are my thoughts:

Raphael

Pros: a good starter library, easy to do a LOT of things with SVG quickly. Well written and documented. Lots of examples and Demos. Very extensible architecture. Great with animation.

Cons: is a layer over the actual SVG markup, makes it difficult to do more complex things with SVG - such as grouping (it supports Sets, but not groups). Doesn't do great w/ editing of already existing elements.

jQuery SVG

Pros: a jquery plugin, if you're already using jQuery. Well written and documented. Lots of examples and demos. Supports most SVG elements, allows native access to elements easily

Cons: architecture not as extensible as Raphael. Some things could be better documented (like configure of SVG element). Doesn't do great w/ editing of already existing elements. Relies on SVG semantics for animation - which is not that great.

SnapSVG as a pure SVG version of Raphael

SnapSVG is the successor of Raphael. It is supported only in the SVG enabled browsers and supports almost all the features of SVG.

Conclusion

If you're doing something quick and easy, Raphael is an easy choice. If you're going to do something more complex, I chose to use jQuery SVG because I can manipulate the actual markup significantly easier than with Raphael. And if you want a non-jQuery solution then SnapSVG is a good option.

Is this the proper way to do boolean test in SQL?

With Postgres, you may use

select * from users where active

or

select * from users where active = 't'

If you want to use integer value, you have to consider it as a string. You can't use integer value.

select * from users where active = 1   -- Does not work

select * from users where active = '1' -- Works 

jquery UI dialog: how to initialize without a title bar?

I use this in my projects

$("#myDialog").dialog(dialogOpts);
// remove the title bar
$("#myDialog").siblings('div.ui-dialog-titlebar').remove();
// one liner
$("#myDialog").dialog(dialogOpts).siblings('.ui-dialog-titlebar').remove();

How to create a density plot in matplotlib?

You can do something like:

s = np.random.normal(2, 3, 1000)
import matplotlib.pyplot as plt
count, bins, ignored = plt.hist(s, 30, density=True)
plt.plot(bins, 1/(3 * np.sqrt(2 * np.pi)) * np.exp( - (bins - 2)**2 / (2 * 3**2) ), 
linewidth=2, color='r')
plt.show()

What does -1 mean in numpy reshape?

import numpy as np
x = np.array([[2,3,4], [5,6,7]]) 

# Convert any shape to 1D shape
x = np.reshape(x, (-1)) # Making it 1 row -> (6,)

# When you don't care about rows and just want to fix number of columns
x = np.reshape(x, (-1, 1)) # Making it 1 column -> (6, 1)
x = np.reshape(x, (-1, 2)) # Making it 2 column -> (3, 2)
x = np.reshape(x, (-1, 3)) # Making it 3 column -> (2, 3)

# When you don't care about columns and just want to fix number of rows
x = np.reshape(x, (1, -1)) # Making it 1 row -> (1, 6)
x = np.reshape(x, (2, -1)) # Making it 2 row -> (2, 3)
x = np.reshape(x, (3, -1)) # Making it 3 row -> (3, 2)

Node.js heap out of memory

Just in case anyone runs into this in an environment where they cannot set node properties directly (in my case a build tool):

NODE_OPTIONS="--max-old-space-size=4096" node ...

You can set the node options using an environment variable if you cannot pass them on the command line.

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

Typescript: difference between String and string

The two types are distinct in JavaScript as well as TypeScript - TypeScript just gives us syntax to annotate and check types as we go along.

String refers to an object instance that has String.prototype in its prototype chain. You can get such an instance in various ways e.g. new String('foo') and Object('foo'). You can test for an instance of the String type with the instanceof operator, e.g. myString instanceof String.

string is one of JavaScript's primitive types, and string values are primarily created with literals e.g. 'foo' and "bar", and as the result type of various functions and operators. You can test for string type using typeof myString === 'string'.

The vast majority of the time, string is the type you should be using - almost all API interfaces that take or return strings will use it. All JS primitive types will be wrapped (boxed) with their corresponding object types when using them as objects, e.g. accessing properties or calling methods. Since String is currently declared as an interface rather than a class in TypeScript's core library, structural typing means that string is considered a subtype of String which is why your first line passes compilation type checks.

Remove plot axis values

Change the axis_colour to match the background and if you are modifying the background dynamically you will need to update the axis_colour simultaneously. * The shared picture shows the graph/plot example using mock data ()

### Main Plotting Function ###
plotXY <- function(time, value){

    ### Plot Style Settings ###

    ### default bg is white, set it the same as the axis-colour 
    background <- "white"

    ### default col.axis is black, set it the same as the background to match
    axis_colour <- "white"

    plot_title <- "Graph it!"
    xlabel <- "Time"
    ylabel <- "Value"
    label_colour <- "black"
    label_scale <- 2
    axis_scale <- 2
    symbol_scale <- 2
    title_scale <- 2
    subtitle_scale <- 2
    # point style 16 is a black dot
    point <- 16 
    # p - points, l - line, b - both
    plot_type <- "b"

    plot(time, value, main=plot_title, cex=symbol_scale, cex.lab=label_scale, cex.axis=axis_scale, cex.main=title_scale, cex.sub=subtitle_scale, xlab=xlabel, ylab=ylabel, col.lab=label_colour, col.axis=axis_colour, bg=background, pch=point, type=plot_type)
}

plotXY(time, value)

enter image description here

Controlling fps with requestAnimationFrame?

Here's a good explanation I found: CreativeJS.com, to wrap a setTimeou) call inside the function passed to requestAnimationFrame. My concern with a "plain" requestionAnimationFrame would be, "what if I only want it to animate three times a second?" Even with requestAnimationFrame (as opposed to setTimeout) is that it still wastes (some) amount of "energy" (meaning that the Browser code is doing something, and possibly slowing the system down) 60 or 120 or however many times a second, as opposed to only two or three times a second (as you might want).

Most of the time I run my browsers with JavaScript intentially off for just this reason. But, I'm using Yosemite 10.10.3, and I think there's some kind of timer problem with it - at least on my old system (relatively old - meaning 2011).

Program to find largest and second largest number in array

package secondhighestno;

import java.util.Scanner;

/**
 *
 * @author Laxman
 */
public class SecondHighestno {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner sc=new Scanner(System.in);
        int n =sc.nextInt();
        int a[]=new int[n];
        for(int i=0;i<n;i++){
            a[i]=sc.nextInt();
        }
        int max1=a[0],max2=a[0];
        for(int j=0;j<n;j++){
            if(a[j]>max1){
                max1=a[j];
            }
        }
        for(int k=0;k<n;k++){
            if(a[k]>max2 && max1>a[k]){
                max2=a[k];
            }
        }
        System.out.println(max1+" "+max2);
    }
}

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

In addition to what Angular University said above you may want to use @Import to aggregate @Configuration classes to the other class (AuthenticationController in my case) :

@Import(SecurityConfig.class)
@RestController
public class AuthenticationController {
@Autowired
private AuthenticationManager authenticationManager;
//some logic
}

Spring doc about Aggregating @Configuration classes with @Import: link

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

Nothing above made it work for me. The thing for me is that I was testing a subscription and i forgot SkuType.SUBS, changing it to INAPP for the reserved google test product fixed it.

SQL Server String Concatenation with Null

In Sql Server:

insert into Table_Name(PersonName,PersonEmail) values(NULL,'[email protected]')

PersonName is varchar(50), NULL is not a string, because we are not passing with in single codes, so it treat as NULL.

Code Behind:

string name = (txtName.Text=="")? NULL : "'"+ txtName.Text +"'";
string email = txtEmail.Text;

insert into Table_Name(PersonName,PersonEmail) values(name,'"+email+"')

How do a send an HTTPS request through a proxy in Java?

Try the Apache Commons HttpClient library instead of trying to roll your own: http://hc.apache.org/httpclient-3.x/index.html

From their sample code:

  HttpClient httpclient = new HttpClient();
  httpclient.getHostConfiguration().setProxy("myproxyhost", 8080);

  /* Optional if authentication is required.
  httpclient.getState().setProxyCredentials("my-proxy-realm", " myproxyhost",
   new UsernamePasswordCredentials("my-proxy-username", "my-proxy-password"));
  */

  PostMethod post = new PostMethod("https://someurl");
  NameValuePair[] data = {
     new NameValuePair("user", "joe"),
     new NameValuePair("password", "bloggs")
  };
  post.setRequestBody(data);
  // execute method and handle any error responses.
  // ...
  InputStream in = post.getResponseBodyAsStream();
  // handle response.


  /* Example for a GET reqeust
  GetMethod httpget = new GetMethod("https://someurl");
  try { 
    httpclient.executeMethod(httpget);
    System.out.println(httpget.getStatusLine());
  } finally {
    httpget.releaseConnection();
  }
  */

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Autonumber value of last inserted row - MS Access / VBA

Private Function addInsert(Media As String, pagesOut As Integer) As Long


    Set rst = db.OpenRecordset("tblenccomponent")
    With rst
        .AddNew
        !LeafletCode = LeafletCode
        !LeafletName = LeafletName
        !UNCPath = "somePath\" + LeafletCode + ".xml"
        !Media = Media
        !CustomerID = cboCustomerID.Column(0)
        !PagesIn = PagesIn
        !pagesOut = pagesOut
        addInsert = CLng(rst!enclosureID) 'ID is passed back to calling routine
        .Update
    End With
    rst.Close

End Function

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Here's my solution using json.dump():

def jsonWrite(p, pyobj, ensure_ascii=False, encoding=SYSTEM_ENCODING, **kwargs):
    with codecs.open(p, 'wb', 'utf_8') as fileobj:
        json.dump(pyobj, fileobj, ensure_ascii=ensure_ascii,encoding=encoding, **kwargs)

where SYSTEM_ENCODING is set to:

locale.setlocale(locale.LC_ALL, '')
SYSTEM_ENCODING = locale.getlocale()[1]

String's Maximum length in Java - calling length() method

I have a 2010 iMac with 8GB of RAM, running Eclipse Neon.2 Release (4.6.2) with Java 1.8.0_25. With the VM argument -Xmx6g, I ran the following code:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
    try {
        sb.append('a');
    } catch (Throwable e) {
        System.out.println(i);
        break;
    }
}
System.out.println(sb.toString().length());

This prints:

Requested array size exceeds VM limit
1207959550

So, it seems that the max array size is ~1,207,959,549. Then I realized that we don't actually care if Java runs out of memory: we're just looking for the maximum array size (which seems to be a constant defined somewhere). So:

for (int i = 0; i < 1_000; i++) {
    try {
        char[] array = new char[Integer.MAX_VALUE - i];
        Arrays.fill(array, 'a');
        String string = new String(array);
        System.out.println(string.length());
    } catch (Throwable e) {
        System.out.println(e.getMessage());
        System.out.println("Last: " + (Integer.MAX_VALUE - i));
        System.out.println("Last: " + i);
    }
}

Which prints:

Requested array size exceeds VM limit
Last: 2147483647
Last: 0
Requested array size exceeds VM limit
Last: 2147483646
Last: 1
Java heap space
Last: 2147483645
Last: 2

So, it seems the max is Integer.MAX_VALUE - 2, or (2^31) - 3

P.S. I'm not sure why my StringBuilder maxed out at 1207959550 while my char[] maxed out at (2^31)-3. It seems that AbstractStringBuilder doubles the size of its internal char[] to grow it, so that probably causes the issue.

Changing element style attribute dynamically using JavaScript

Assuming you have HTML like this:

<div id='thediv'></div>

If you want to modify the style attribute of this div, you'd use

document.getElementById('thediv').style.[ATTRIBUTE] = '[VALUE]'

Replace [ATTRIBUTE] with the style attribute you want. Remember to remove '-' and make the following letter uppercase.

Examples

document.getElementById('thediv').style.display = 'none'; //changes the display
document.getElementById('thediv').style.paddingLeft = 'none'; //removes padding

How to fix date format in ASP .NET BoundField (DataFormatString)?

I had the same problem, only need to show shortdate (without the time), moreover it was needed to have multi-language settings, so depends of the language, show dd-mm-yyyy or mm-dd-yyyy.

Finally using DataFormatString="{0:d}, all works fine and show only the date with culture format.

python pandas: apply a function with arguments to a series

Series.apply(func, convert_dtype=True, args=(), **kwds)

args : tuple

x = my_series.apply(my_function, args = (arg1,))

How do I define and use an ENUM in Objective-C?

I recommend using NS_OPTIONS or NS_ENUM. You can read more about it here: http://nshipster.com/ns_enum-ns_options/

Here's an example from my own code using NS_OPTIONS, I have an utility that sets a sublayer (CALayer) on a UIView's layer to create a border.

The h. file:

typedef NS_OPTIONS(NSUInteger, BSTCMBorder) {
    BSTCMBOrderNoBorder     = 0,
    BSTCMBorderTop          = 1 << 0,
    BSTCMBorderRight        = 1 << 1,
    BSTCMBorderBottom       = 1 << 2,
    BSTCMBOrderLeft         = 1 << 3
};

@interface BSTCMBorderUtility : NSObject

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color;

@end

The .m file:

@implementation BSTCMBorderUtility

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color
{

    // Make a left border on the view
    if (border & BSTCMBOrderLeft) {

    }

    // Make a right border on the view
    if (border & BSTCMBorderRight) {

    }

    // Etc

}

@end

How to convert int to char with leading zeros?

DECLARE @number1 INT, @number2 INT

SET @number1 = 1

SET @number2 = 867

-- Without the 'RTRIM', the value returned is 3__ !!!

SELECT RIGHT('000' + RTRIM(CAST(@number1 AS NCHAR(3)), 3 )) AS NUMBER_CONVERTED

-- Without the 'RTRIM', the value returned is 867___ !!!

SELECT RIGHT('000000' + RTRIM(CAST(@number2 AS NCHAR(6)), 6 )) AS NUMBER_CONVERTED

How to change Android version and code version number?

After updating the manifest file, instead of building your project, go to command line and reach the path ...bld\Debug\platforms\android. Run the command "ant release". Your new release.apk file will have a new version code.

How to cancel an $http request in AngularJS?

For some reason config.timeout doesn't work for me. I used this approach:

_x000D_
_x000D_
let cancelRequest = $q.defer();_x000D_
let cancelPromise = cancelRequest.promise;_x000D_
_x000D_
let httpPromise = $http.get(...);_x000D_
_x000D_
$q.race({ cancelPromise, httpPromise })_x000D_
    .then(function (result) {_x000D_
..._x000D_
});
_x000D_
_x000D_
_x000D_

And cancelRequest.resolve() to cancel. Actually it doesn't not cancel a request but you don't get unnecessary response at least.

Hope this helps.

How can I convert ArrayList<Object> to ArrayList<String>?

Using Java 8 lambda:

ArrayList<Object> obj = new ArrayList<>();
obj.add(1);
obj.add("Java");
obj.add(3.14);

ArrayList<String> list = new ArrayList<>();
obj.forEach((xx) -> list.add(String.valueOf(xx)));

Making a UITableView scroll when text field is selected

I tried almost the same approach and came up with a simpler and smaller code for the same. I created a IBOutlet iTextView and associated with the UITextView in the IB.

 -(void)keyboardWillShow:(NSNotification *)notification
    {
        NSLog(@"Keyboard");
        CGRect keyFrame = [[[notification userInfo]objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];

        [UIView beginAnimations:@"resize view" context:nil];
        [UIView setAnimationCurve:1];
        [UIView setAnimationDuration:1.0];
        CGRect frame = iTableView.frame;
        frame.size.height = frame.size.height -  keyFrame.size.height;
        iTableView.frame = frame;
        [iTableView scrollRectToVisible:frame animated:YES];
        [UIView commitAnimations];

    }

Convert list to array in Java

Either:

Foo[] array = list.toArray(new Foo[0]);

or:

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

Update:

It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.

From JetBrains Intellij Idea inspection:

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

What does "select 1 from" do?

The construction is usually used in "existence" checks

if exists(select 1 from customer_table where customer = 'xxx')

or

if exists(select * from customer_table where customer = 'xxx')

Both constructions are equivalent. In the past people said the select * was better because the query governor would then use the best indexed column. This has been proven not true.

Call a stored procedure with parameter in c#

You have to add parameters since it is needed for the SP to execute

using (SqlConnection con = new SqlConnection(dc.Con))
{
    using (SqlCommand cmd = new SqlCommand("SP_ADD", con))
    {
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@FirstName", txtfirstname.Text);
        cmd.Parameters.AddWithValue("@LastName", txtlastname.Text);
        con.Open();
        cmd.ExecuteNonQuery();
    }            
}

how to convert object to string in java

Looking at the output, it seems that your "temp" is a String array. You need to loop across the array to display each value.

Does VBA have Dictionary Structure?

The scripting runtime dictionary seems to have a bug that can ruin your design at advanced stages.

If the dictionary value is an array, you cannot update values of elements contained in the array through a reference to the dictionary.

Real-world examples of recursion

Check if the created image is going to work within a size restricted box.

function check_size($font_size, $font, $text, $width, $height) {
        if (!is_string($text)) {
            throw new Exception('Invalid type for $text');
        }   
        $box = imagettfbbox($font_size, 0, $font, $text);
        $box['width'] = abs($box[2] - $box[0]);
        if ($box[0] < -1) {
            $box['width'] = abs($box[2]) + abs($box[0]) - 1;
        }   
        $box['height'] = abs($box[7]) - abs($box[1]);
        if ($box[3] > 0) {
            $box['height'] = abs($box[7] - abs($box[1])) - 1;
        }   
        return ($box['height'] < $height && $box['width'] < $width) ? array($font_size, $box['width'], $height) : $this->check_size($font_size - 1, $font, $text, $width, $height);
    }

ViewPager PagerAdapter not updating the View

All these solution did not help me. thus i found a working solution: You can setAdapter every time, but it isn't enough. you should do these before changing adapter:

FragmentManager fragmentManager = slideShowPagerAdapter.getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
List<Fragment> fragments = fragmentManager.getFragments();
for (Fragment f : fragments) {
    transaction.remove(f);
}
transaction.commit();

and after this:

viewPager.setAdapter(adapter);

Removing single-quote from a string in php

Using your current str_replace method:

$FileName = str_replace("'", "", $UserInput);

While it's hard to see, the first argument is a double quote followed by a single quote followed by a double quote. The second argument is two double quotes with nothing in between.

With str_replace, you could even have an array of strings you want to remove entirely:

$remove[] = "'";
$remove[] = '"';
$remove[] = "-"; // just as another example

$FileName = str_replace( $remove, "", $UserInput );

How to send multiple data fields via Ajax?

I am new to AJAX and I have tried this and it works well.

function q1mrks(country,m) {
  // alert("hellow");
  if (country.length==0) {
    //alert("hellow");
    document.getElementById("q1mrks").innerHTML="";
    return;
  }
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
    }
  }
  xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
  //mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
  xmlhttp.send();
}

Regex: Check if string contains at least one digit

I'm surprised nobody has mentioned the simplest version:

\d

This will match any digit. If your regular expression engine is Unicode-aware, this means it will match anything that's defined as a digit in any language, not just the Arabic numerals 0-9.

There's no need to put it in [square brackets] to define it as a character class, as one of the other answers did; \d works fine by itself.

Since it's not anchored with ^ or $, it will match any subset of the string, so if the string contains at least one digit, this will match.

And there's no need for the added complexity of +, since the goal is just to determine whether there's at least one digit. If there's at least one digit, this will match; and it will do so with a minimum of overhead.

How do I finish the merge after resolving my merge conflicts?

The next steps after resolving the conflicts manually are:-

  1. git add .
  2. git status (this will show you which commands are necessary to continue automatic merge procedure)
  3. [command git suggests, e.g. git merge --continue, git cherry-pick --continue, git rebase --continue]

How do I set a textbox's text to bold at run time?

Depending on your application, you'll probably want to use that Font assignment either on text change or focus/unfocus of the textbox in question.

Here's a quick sample of what it could look like (empty form, with just a textbox. Font turns bold when the text reads 'bold', case-insensitive):

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        RegisterEvents();
    }

    private void RegisterEvents()
    {
        _tboTest.TextChanged += new EventHandler(TboTest_TextChanged);
    }

    private void TboTest_TextChanged(object sender, EventArgs e)
    {
        // Change the text to bold on specified condition
        if (_tboTest.Text.Equals("Bold", StringComparison.OrdinalIgnoreCase))
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Bold);
        }
        else
        {
            _tboTest.Font = new Font(_tboTest.Font, FontStyle.Regular);
        }
    }
}

Convert double to float in Java

The problem is, your value cannot be stored accurately in single precision floating point type. Proof:

public class test{
    public static void main(String[] args){
        Float a = Float.valueOf("23423424666767");
        System.out.printf("%f\n", a); //23423424135168,000000
        System.out.println(a);        //2.34234241E13
    }
}

Another thing is: you don't get "2.3423424666767E13", it's just the visual representation of the number stored in memory. "How you print out" and "what is in memory" are two distinct things. Example above shows you how to print the number as float, which avoids scientific notation you were getting.

Failed to Connect to MySQL at localhost:3306 with user root

It worked for me this way:

Step1: Open System Preference > MySQL > Initialize Database.

Step2: Put password you used while installing MySQL.

Step3: Start MySQL server.

Step4: Come back to MySQL Workbench and double connect/ create a new one.

Which Java library provides base64 encoding/decoding?

Java 9

Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind module which will need to be included.

module org.example.foo {
    requires java.xml.bind;
}

Java 8

Java 8 now provides java.util.Base64 for encoding and decoding base64.

Encoding

byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=

Decoding

byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world

Java 6 and 7

Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter can be used. This is part of the JRE, no extra libraries required.

Encoding

byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=  

Decoding

byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world

Placing an image to the top right corner - CSS

Position the div relatively, and position the ribbon absolutely inside it. Something like:

#content {
  position:relative;
}

.ribbon {
  position:absolute;
  top:0;
  right:0;
}

Detect changed input text box

I think you can use keydown too:

$('#fieldID').on('keydown', function (e) {
  //console.log(e.which);
  if (e.which === 8) {
    //do something when pressing delete
    return true;
  } else {
    //do something else
    return false;
  }
});

How can I escape a double quote inside double quotes?

Bash allows you to place strings adjacently, and they'll just end up being glued together.

So this:

$ echo "Hello"', world!'

produces

Hello, world!

The trick is to alternate between single and double-quoted strings as required. Unfortunately, it quickly gets very messy. For example:

$ echo "I like to use" '"double quotes"' "sometimes"

produces

I like to use "double quotes" sometimes

In your example, I would do it something like this:

$ dbtable=example
$ dbload='load data local infile "'"'gfpoint.csv'"'" into '"table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '"'"'"' LINES "'TERMINATED BY "'"'\n'"'" IGNORE 1 LINES'
$ echo $dbload

which produces the following output:

load data local infile "'gfpoint.csv'" into table example FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY "'\n'" IGNORE 1 LINES

It's difficult to see what's going on here, but I can annotate it using Unicode quotes. The following won't work in bash – it's just for illustration:

dbload=load data local infile "’“'gfpoint.csv'”‘" into’“table $dbtable FIELDS TERMINATED BY ',' ENCLOSED BY '”‘"’“' LINES”‘TERMINATED BY "’“'\n'”‘" IGNORE 1 LINES

The quotes like “ ‘ ’ ” in the above will be interpreted by bash. The quotes like " ' will end up in the resulting variable.

If I give the same treatment to the earlier example, it looks like this:

$ echoI like to use"double quotes"sometimes

How to execute command stored in a variable?

$cmd would just replace the variable with it's value to be executed on command line. eval "$cmd" does variable expansion & command substitution before executing the resulting value on command line

The 2nd method is helpful when you wanna run commands that aren't flexible eg.
for i in {$a..$b}
format loop won't work because it doesn't allow variables.
In this case, a pipe to bash or eval is a workaround.

Tested on Mac OSX 10.6.8, Bash 3.2.48

Visual Studio popup: "the operation could not be completed"

enter image description hereRestart the visual studio as Admin will work on in many cases.

Ruby combining an array into one string

Here's my solution:

@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>

Typescript: How to extend two classes?

There are so many good answers here already, but i just want to show with an example that you can add additional functionality to the class being extended;

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor => {
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
            if (name !== 'constructor') {
                derivedCtor.prototype[name] = baseCtor.prototype[name];
            }
        });
    });
}

class Class1 {
    doWork() {
        console.log('Working');
    }
}

class Class2 {
    sleep() {
        console.log('Sleeping');
    }
}

class FatClass implements Class1, Class2 {
    doWork: () => void = () => { };
    sleep: () => void = () => { };


    x: number = 23;
    private _z: number = 80;

    get z(): number {
        return this._z;
    }

    set z(newZ) {
        this._z = newZ;
    }

    saySomething(y: string) {
        console.log(`Just saying ${y}...`);
    }
}
applyMixins(FatClass, [Class1, Class2]);


let fatClass = new FatClass();

fatClass.doWork();
fatClass.saySomething("nothing");
console.log(fatClass.x);

Maven error in eclipse (pom.xml) : Failure to transfer org.apache.maven.plugins:maven-surefire-plugin:pom:2.12.4

For Unix Users

find ~/.m2 -name "*.lastUpdated" -exec grep -q "Could not transfer" {} \; -print -exec rm {} \;

Right-click your project and choose Update Dependencies

For Windows

  • CD (change directory) to .m2\repository
  • execute the command for /r %i in (*.lastUpdated) do del %i
  • Then right-click your project and choose Update Dependencies

jQuery loop over JSON result from AJAX Success?

If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.

$.get('url', function(data, statusText, xheader){
 // your code within the success callback
  var data = $.parseJSON(data);
  $.each(data, function(i){
         console.log(data[i]);
      })
})

Error: TypeError: $(...).dialog is not a function

Be sure to insert full version of jQuery UI. Also you should init the dialog first:

_x000D_
_x000D_
$(function () {_x000D_
  $( "#dialog1" ).dialog({_x000D_
    autoOpen: false_x000D_
  });_x000D_
  _x000D_
  $("#opener").click(function() {_x000D_
    $("#dialog1").dialog('open');_x000D_
  });_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>_x000D_
 _x000D_
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>_x000D_
_x000D_
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />_x000D_
_x000D_
<button id="opener">open the dialog</button>_x000D_
<div id="dialog1" title="Dialog Title" hidden="hidden">I'm a dialog</div>
_x000D_
_x000D_
_x000D_

Restart android machine

Have you tried simply 'reboot' with adb?

  adb reboot

Also you can run complete shell scripts (e.g. to reboot your emulator) via adb:

 adb shell <command>

The official docs can be found here.

No plot window in matplotlib

The code snippet below works on both Eclipse and the Python shell:

import numpy as np
import matplotlib.pyplot as plt

# Come up with x and y
x = np.arange(0, 5, 0.1)
y = np.sin(x)

# Just print x and y for fun
print x
print y

# Plot the x and y and you are supposed to see a sine curve
plt.plot(x, y)

# Without the line below, the figure won't show
plt.show()

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

Check Safari developer reference on Touch class.

According to this, pageX/Y should be available - maybe you should check spelling? make sure it's pageX and not PageX

Fix footer to bottom of page

Set

html, body {
    height: 100%;
}

Wrap the entire content before the footer in a div.

.wrapper {
    height:auto !important;
    min-height:100%;
}

You can adjust min-height as you like based on how much of the footer you want to show in the bottom of the browser window. If set it to 90%, 10% of the footer will show before scrolling.

set the iframe height automatically

Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.

.iframe-embed {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.iframe-embed-wrapper {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.iframe-embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
    <iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>

How to create a checkbox with a clickable label?

It works too :

<form>
    <label for="male"><input type="checkbox" name="male" id="male" />Male</label><br />
    <label for="female"><input type="checkbox" name="female" id="female" />Female</label>
</form>

How do I revert to a previous package in Anaconda?

For the case that you wish to revert a recently installed package that made several changes to dependencies (such as tensorflow), you can "roll back" to an earlier installation state via the following method:

conda list --revisions
conda install --revision [revision number]

The first command shows previous installation revisions (with dependencies) and the second reverts to whichever revision number you specify.

Note that if you wish to (re)install a later revision, you may have to sequentially reinstall all intermediate versions. If you had been at revision 23, reinstalled revision 20 and wish to return, you may have to run each:

conda install --revision 21
conda install --revision 22
conda install --revision 23

C# Encoding a text string with line breaks

Try this :

string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)

Cross-browser custom styling for file upload button

I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.

the directive

angular.module('myCoolApp')
  .directive('fileButton', function () {
    return {
      templateUrl: 'components/directives/fileButton/fileButton.html',
      restrict: 'E',
      link: function (scope, element, attributes) {

        var container = angular.element('.file-upload-container');
        var button = angular.element('.file-upload-button');

        container.css({
            position: 'relative',
            overflow: 'hidden',
            width: button.offsetWidth,
            height: button.offsetHeight
        })

      }

    };
  });

a jade template if you are using jade

div(class="file-upload-container") 
    button(class="file-upload-button") +
    input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")  

the same template in html if you are using html

<div class="file-upload-container">
   <button class="file-upload-button"></button>
   <input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" /> 
</div>

the css

.file-upload-button {
    margin-top: 40px;
    padding: 30px;
    border: 1px solid black;
    height: 100px;
    width: 100px;
    background: transparent;
    font-size: 66px;
    padding-top: 0px;
    border-radius: 5px;
    border: 2px solid rgb(255, 228, 0); 
    color: rgb(255, 228, 0);
}

.file-upload-input {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

Local file access with JavaScript

NW.js allows you to create desktop applications using Javascript without all the security restrictions usually placed on the browser. So you can run executables with a function, or create/edit/read/write/delete files. You can access the hardware, such as current CPU usage or total ram in use, etc.

You can create a windows, linux, or mac desktop application with it that doesn't require any installation.

Format y axis as percent

For those who are looking for the quick one-liner:

plt.gca().set_yticklabels(['{:.0f}%'.format(x*100) for x in plt.gca().get_yticks()]) 

Or if you are using Latex as the axis text formatter, you have to add one backslash '\'

plt.gca().set_yticklabels(['{:.0f}\%'.format(x*100) for x in plt.gca().get_yticks()]) 

How to send an email with Gmail as provider using Python?

great answer from @David, here is for Python 3 without the generic try-except:

def send_email(user, password, recipient, subject, body):

    gmail_user = user
    gmail_pwd = password
    FROM = user
    TO = recipient if type(recipient) is list else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.ehlo()
    server.starttls()
    server.login(gmail_user, gmail_pwd)
    server.sendmail(FROM, TO, message)
    server.close()

java: run a function after a specific number of seconds

new java.util.Timer().schedule( 
        new java.util.TimerTask() {
            @Override
            public void run() {
                // your code here
            }
        }, 
        5000 
);

EDIT:

javadoc says:

After the last live reference to a Timer object goes away and all outstanding tasks have completed execution, the timer's task execution thread terminates gracefully (and becomes subject to garbage collection). However, this can take arbitrarily long to occur.

How to stop VBA code running?

Or, if you want to avoid the use of a global variable you could use the rarely used .Tag property of the userform:

Private Sub CommandButton1_Click()
    Me.CommandButton1.Enabled = False 'Disabling button so user cannot push it
                                      'multiple times
    Me.CommandButton1.caption = "Wait..." 'Jamie's suggestion
    Me.Tag = "Cancel"
End Sub

Private Sub SomeVBASub
    If LCase(UserForm1.Tag) = "cancel" Then
        GoTo StopProcess
    Else
        'DoStuff
    End If

Exit Sub
StopProcess:
    'Here you can do some steps to be able to cancel process adequately
    'i.e. setting collections to "Nothing" deleting some files...
End Sub

How to create helper file full of functions in react native?

Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

export function HelloChandu() {

}

export function HelloTester() {

}

Then import them like so:

import { HelloChandu } from './helpers'

or...

import functions from './helpers' then functions.HelloChandu

Angularjs $q.all

The issue seems to be that you are adding the deffered.promise when deffered is itself the promise you should be adding:

Try changing to promises.push(deffered); so you don't add the unwrapped promise to the array.

 UploadService.uploadQuestion = function(questions){

            var promises = [];

            for(var i = 0 ; i < questions.length ; i++){

                var deffered  = $q.defer();
                var question  = questions[i]; 

                $http({

                    url   : 'upload/question',
                    method: 'POST',
                    data  : question
                }).
                success(function(data){
                    deffered.resolve(data);
                }).
                error(function(error){
                    deffered.reject();
                });

                promises.push(deffered);
            }

            return $q.all(promises);
        }

Git reset single file in feature branch to be the same as in master

you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:

git checkout master -- filename

Note that the differences will be cached; so if you want to see the differences you obtained; use

git diff --cached

C compile : collect2: error: ld returned 1 exit status

sometimes this error came beacause failed to compile in middlest of any build. The best way to try is by doing make clean and again make the whole code .

Using Pip to install packages to Anaconda Environment

I solved this problem the following way:

If you have a non-conda pip as your default pip but conda python is your default python (as below)

>which -a pip
/home/<user>/.local/bin/pip   
/home/<user>/.conda/envs/newenv/bin/pip
/usr/bin/pip

>which -a python
/home/<user>/.conda/envs/newenv/bin/python
/usr/bin/python

Then instead of just calling pip install <package>, you can use the module flag -m with python so that it uses the anaconda python for the installation

python -m pip install <package>

This installs the package to the anaconda library directory rather than to the library directory associated with (the non-anaconda) pip

jQuery: Scroll down page a set increment (in pixels) on click?

var y = $(window).scrollTop();  //your current y position on the page
$(window).scrollTop(y+150);

Re-order columns of table in Oracle

Use the View for your efforts in altering the position of the column: CREATE VIEW CORRECTED_POSITION AS SELECT co1_1, col_3, col_2 FROM UNORDERDED_POSITION should help.

This requests are made so some reports get produced where it is using SELECT * FROM [table_name]. Or, some business has a hierarchy approach of placing the information in order for better readability from the back end.

Thanks Dilip

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are using bootstrap-datepicker you may use this style:

$('#datepicker').datepicker('setStartDate', "01-01-1900");

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

Well you're casting OrdersPerHour to an int?

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

Yet your method signature is int:

static int OrdersPerHour(string User)

The two have to match.


Also a quick suggestion -> Use parameters in your query, something like:

string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > ? AND User = ? AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered')";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.Add(curTime.AddHours(-1));
dbcommand.Parameters.Add(User);

Best PHP IDE for Mac? (Preferably free!)

Komodo is wonderful, and it runs on OS X; they have a free version, Komodo Edit.

UPDATE from 2015: I've switched to PHPStorm from Jetbrains, the same folks that built IntelliJ IDEA and Resharper. It's better. Not just better. It's well worth the money.

Setting Inheritance and Propagation flags with set-acl and powershell

Just because you're in PowerShell don't forgot about good ol' exes. Sometimes they can provide the easiest solution e.g.:

icacls.exe $folder /grant 'domain\user:(OI)(CI)(M)'

Smart cast to 'Type' is impossible, because 'variable' is a mutable property that could have been changed by this time

The practical reason why this doesn't work is not related to threads. The point is that node.left is effectively translated into node.getLeft().

This property getter might be defined as:

val left get() = if (Math.random() < 0.5) null else leftPtr

Therefore two calls might not return the same result.

How to convert image to byte array

If you don't reference the imageBytes to carry bytes in the stream, the method won't return anything. Make sure you reference imageBytes = m.ToArray();

    public static byte[] SerializeImage() {
        MemoryStream m;
        string PicPath = pathToImage";

        byte[] imageBytes;
        using (Image image = Image.FromFile(PicPath)) {
            
            using ( m = new MemoryStream()) {

                image.Save(m, image.RawFormat);
                imageBytes = new byte[m.Length];
               //Very Important    
               imageBytes = m.ToArray();
                
            }//end using
        }//end using

        return imageBytes;
    }//SerializeImage

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

The first line of a paragraph is indented by default, thus whether or not you have \indent there won't make a difference. \indent and \noindent can be used to override default behavior. You can see this by replacing your line with the following:

Now we are engaged in a great civil war.\\
\indent this is indented\\
this isn't indented


\noindent override default indentation (not indented)\\
asdf 

Can I automatically increment the file build version when using Visual Studio?

Cake supports AssemblyInfo files patching. With cake in hands you have infinite ways to implement automatic version incrementing.

Simple example of incrementing version like C# compiler does:

Setup(() =>
{
    // Executed BEFORE the first task.
    var datetimeNow = DateTime.Now;
    var daysPart = (datetimeNow - new DateTime(2000, 1, 1)).Days;
    var secondsPart = (long)datetimeNow.TimeOfDay.TotalSeconds/2;
    var assemblyInfo = new AssemblyInfoSettings
    {
        Version = "3.0.0.0",
        FileVersion = string.Format("3.0.{0}.{1}", daysPart, secondsPart)
    };
    CreateAssemblyInfo("MyProject/Properties/AssemblyInfo.cs", assemblyInfo);
});

Here:

  • Version - is assembly version. Best practice is to lock major version number and leave remaining with zeroes (like "1.0.0.0").
  • FileVersion - is assembly file version.

Note that you can patch not only versions but also all other necessary information.

What's the UIScrollView contentInset property for?

It's used to add padding in UIScrollView

Without contentInset, a table view is like this:

enter image description here

Then set contentInset:

tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

The effect is as below:

enter image description here

Seems to be better, right?

And I write a blog to study the contentInset, criticism is welcome.

how to get file path from sd card in android

maybe you are having the same problem i had, my tablet has a SD card on it, in /mnt/sdcard and the sd card external was in /mnt/extcard, you can look it on the android file manager, going to your sd card and see the path to it.

Hope it helps.

cmake - find_library - custom library location

I saw that two people put that question to their favorites so I will try to answer the solution which works for me: Instead of using find modules I'm writing configuration files for all libraries which are installed. Those files are extremly simple and can also be used to set non-standard variables. CMake will (at least on windows) search for those configuration files in

CMAKE_PREFIX_PATH/<<package_name>>-<<version>>/<<package_name>>-config.cmake

(which can be set through an environment variable). So for example the boost configuration is in the path

CMAKE_PREFIX_PATH/boost-1_50/boost-config.cmake

In that configuration you can set variables. My config file for boost looks like that:

set(boost_INCLUDE_DIRS ${boost_DIR}/include)
set(boost_LIBRARY_DIR ${boost_DIR}/lib)
foreach(component ${boost_FIND_COMPONENTS}) 
    set(boost_LIBRARIES ${boost_LIBRARIES} debug ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-gd-1_50.lib)
    set(boost_LIBRARIES ${boost_LIBRARIES} optimized ${boost_LIBRARY_DIR}/libboost_${component}-vc110-mt-1_50.lib)
endforeach()
add_definitions( -D_WIN32_WINNT=0x0501 )

Pretty straight forward + it's possible to shrink the size of the config files even more when you write some helper functions. The only issue I have with this setup is that I havn't found a way to give config files a priority over find modules - so you need to remove the find modules.

Hope this this is helpful for other people.

Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

What does "select count(1) from table_name" on any database tables mean?

This is similar to the difference between

SELECT * FROM table_name and SELECT 1 FROM table_name.  

If you do

SELECT 1 FROM table_name

it will give you the number 1 for each row in the table. So yes count(*) and count(1) will provide the same results as will count(8) or count(column_name)

Excel VBA select range at last row and column

Another simple way:

ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).Select    
Selection.EntireRow.Delete

or simpler:

ActiveSheet.Rows(ActiveSheet.UsedRange.Rows.Count+1).EntireRow.Delete

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

SQL How to Select the most recent date item

Select * 
FROM test_table 
WHERE user_id = value 
AND date_added = (select max(date_added) 
   from test_table 
   where user_id = value)

jQuery Validate Required Select

You can write your own rule!

 // add the rule here
 $.validator.addMethod("valueNotEquals", function(value, element, arg){
  return arg !== value;
 }, "Value must not equal arg.");

 // configure your validation
 $("form").validate({
  rules: {
   SelectName: { valueNotEquals: "default" }
  },
  messages: {
   SelectName: { valueNotEquals: "Please select an item!" }
  }  
 });

How to generate a HTML page dynamically using PHP?

You dont need to generate any dynamic html page, just use .htaccess file and rewrite the URL.

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

This is all i can find out. Not sure if it helps, but thought I'd add it to the mix.

WORD-WRAP

This property specifies whether the current rendered line should break if the content exceeds the boundary of the specified rendering box for an element (this is similar in some ways to the ‘clip’ and ‘overflow’ properties in intent.) This property should only apply if the element has a visual rendering, is an inline element with explicit height/width, is absolutely positioned and/or is a block element.

WORD-BREAK

This property controls the line breaking behavior within words. It is especially useful in cases where multiple languages are used within an element.

Compile to a stand-alone executable (.exe) in Visual Studio

Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.

Create a simple 10 second countdown

This does it in text.

_x000D_
_x000D_
<p> The download will begin in <span id="countdowntimer">10 </span> Seconds</p>_x000D_
_x000D_
<script type="text/javascript">_x000D_
    var timeleft = 10;_x000D_
    var downloadTimer = setInterval(function(){_x000D_
    timeleft--;_x000D_
    document.getElementById("countdowntimer").textContent = timeleft;_x000D_
    if(timeleft <= 0)_x000D_
        clearInterval(downloadTimer);_x000D_
    },1000);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Regex pattern inside SQL Replace function?

If you are doing this just for a parameter coming into a Stored Procedure, you can use the following:

declare @badIndex int
set @badIndex = PatIndex('%[^0-9]%', @Param)
while @badIndex > 0
    set @Param = Replace(@Param, Substring(@Param, @badIndex, 1), '')
    set @badIndex = PatIndex('%[^0-9]%', @Param)

How to execute a command in a remote computer?

IMO, in your case you can try this:

  1. Map the shared folder to a drive or folder on your machine. (here's how)
  2. Access the mapped drive/folder as you normally would local files.

Nothing needs to be installed. No services need to be running except those that enable folder sharing.

If you can access the shared folder and maps it on your machine, most things should work just like local files, including command prompts and all explorer-enhancement tools.

This is different from using PsExec (or RDP-ing in) in that you do not need to have administrative rights and/or remote desktop/terminal services connection rights on the remote server, you just need to be able to access those shared folders.

Also make sure you have all the necessary security permissions to run whatever commands/tools you want to run on those shared folders as well.


If, however you wish the processing to be done on the target machine, then you can try PsExec as @divo and @recursive pointed out, something alongs:

PsExec \\yourServerName -u yourUserName cmd.exe

Which will brings gives you a command prompt at the remote machine. And from there you can execute whatever you want.

I am not sure but I think you need either the Server (lanmanserver) or the Terminal Services (TermService) service to be running (which should have already be running).

What's the difference between git clone --mirror and git clone --bare

The difference is that when using --mirror, all refs are copied as-is. This means everything: remote-tracking branches, notes, refs/originals/* (backups from filter-branch). The cloned repo has it all. It's also set up so that a remote update will re-fetch everything from the origin (overwriting the copied refs). The idea is really to mirror the repository, to have a total copy, so that you could for example host your central repo in multiple places, or back it up. Think of just straight-up copying the repo, except in a much more elegant git way.

The new documentation pretty much says all this:

--mirror

Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

My original answer also noted the differences between a bare clone and a normal (non-bare) clone - the non-bare clone sets up remote tracking branches, only creating a local branch for HEAD, while the bare clone copies the branches directly.

Suppose origin has a few branches (master (HEAD), next, pu, and maint), some tags (v1, v2, v3), some remote branches (devA/master, devB/master), and some other refs (refs/foo/bar, refs/foo/baz, which might be notes, stashes, other devs' namespaces, who knows).

  • git clone origin-url (non-bare): You will get all of the tags copied, a local branch master (HEAD) tracking a remote branch origin/master, and remote branches origin/next, origin/pu, and origin/maint. The tracking branches are set up so that if you do something like git fetch origin, they'll be fetched as you expect. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --bare origin-url: You will get all of the tags copied, local branches master (HEAD), next, pu, and maint, no remote tracking branches. That is, all branches are copied as is, and it's set up completely independent, with no expectation of fetching again. Any remote branches (in the cloned remote) and other refs are completely ignored.

  • git clone --mirror origin-url: Every last one of those refs will be copied as-is. You'll get all the tags, local branches master (HEAD), next, pu, and maint, remote branches devA/master and devB/master, other refs refs/foo/bar and refs/foo/baz. Everything is exactly as it was in the cloned remote. Remote tracking is set up so that if you run git remote update all refs will be overwritten from origin, as if you'd just deleted the mirror and recloned it. As the docs originally said, it's a mirror. It's supposed to be a functionally identical copy, interchangeable with the original.

Unzipping files in Python

from zipfile import ZipFile
ZipFile("YOURZIP.zip").extractall("YOUR_DESTINATION_DIRECTORY")

The directory where you will extract your files doesn't need to exist before, you name it at this moment

YOURZIP.zip is the name of the zip if your project is in the same directory. If not, use the PATH i.e : C://....//YOURZIP.zip

Think to escape the / by an other / in the PATH If you have a permission denied try to launch your ide (i.e: Anaconda) as administrator

YOUR_DESTINATION_DIRECTORY will be created in the same directory than your project

Why and when to use angular.copy? (Deep Copy)

I am just sharing my experience here, I used angular.copy() for comparing two objects properties. I was working on a number of inputs without form element, I was wondering how to compare two objects properties and based on result I have to enable and disable the save button. So I used as below.

I assigned an original server object user values to my dummy object to say userCopy and used watch to check changes to the user object.

My server API which gets me data from the server:

var req = {
    method: 'GET',
    url: 'user/profile/' + id,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
$http(req).success(function(data) {
    $scope.user = data;
    $scope.userCopy = angular.copy($scope.user);
    $scope.btnSts=true;
}).error(function(data) {
    $ionicLoading.hide();
});

//initially my save button is disabled because objects are same, once something 
//changes I am activating save button

$scope.btnSts = true;
$scope.$watch('user', function(newVal, oldVal) {
    console.log($scope.userCopy.name);

    if ($scope.userCopy.name !== $scope.user.name || $scope.userCopy.email !== $scope.user.email) {
        console.log('Changed');
        $scope.btnSts = false;
    } else {
        console.log('Unchanged');
        $scope.btnSts = true;
    }    
}, true);

I am not sure but comparing two objects was really headache for me always but with angular.copy() it went smoothly.

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

A key issue here is that this loop iterates over the rows (1st dimension) of B:

In [258]: B
Out[258]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In [259]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b += 1
     ...:     print(b)
     ...:     
[0 1 2] =>[1 2 3]
[3 4 5] =>[4 5 6]
[6 7 8] =>[7 8 9]
[ 9 10 11] =>[10 11 12]

Thus the += is acting on a mutable object, an array.

This is implied in the other answers, but easily missed if your focus is on the a = a+1 reassignment.

I could also make an in-place change to b with [:] indexing, or even something fancier, b[1:]=0:

In [260]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b[:] = b * 2

[1 2 3] =>[2 4 6]
[4 5 6] =>[ 8 10 12]
[7 8 9] =>[14 16 18]
[10 11 12] =>[20 22 24]

Of course with a 2d array like B we usually don't need to iterate on the rows. Many operations that work on a single of B also work on the whole thing. B += 1, B[1:] = 0, etc.

Creating a triangle with for loops

  for (int i=0; i<6; i++)
  {
     for (int k=0; k<6-i; k++)
     {
        System.out.print(" ");
     }
     for (int j=0; j<i*2+1; j++)
     {
        System.out.print("*");
     }
     System.out.println("");
  }

Expansion of variables inside single quotes in a command in Bash

Does this work for you?

eval repo forall -c '....$variable'

Minimal web server using netcat

while true; do (echo -e 'HTTP/1.1 200 OK\r\nConnection: close\r\n';) | timeout 1  nc -lp 8080 ; done

Closes connection after 1 sec, so curl doesn't hang on it.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

The reason that you get this error on OSX is the rvm-installed ruby.

If you run into this issue on OSX you can find a really broad explanation of it in this blog post:

http://toadle.me/2015/04/16/fixing-failing-ssl-verification-with-rvm.html

The short version is that, for some versions of Ruby, RVM downloads pre-compiled binaries, which look for certificates in the wrong location. By forcing RVM to download the source and compile on your own machine, you ensure that the configuration for the certificate location is correct.

The command to do this is:

rvm install 2.2.0 --disable-binary

if you already have the version in question, you can re-install it with:

rvm reinstall 2.2.0 --disable-binary

(obviously, substitute your ruby version as needed).

Make elasticsearch only return certain fields?

here you can specify whichever field you want in your output and also which you don't.
  
  POST index_name/_search
    {
        "_source": {
            "includes": [ "field_name", "field_name" ],
            "excludes": [ "field_name" ]
        },
        "query" : {
            "match" : { "field_name" : "value" }
        }
    }

How Do I Take a Screen Shot of a UIView?

CGImageRef UIGetScreenImage();

Apple now allows us to use it in a public application, even though it's a private API

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

What does "var" mean in C#?

It declares a type based on what is assigned to it in the initialisation.

A simple example is that the code:

var i = 53;

Will examine the type of 53, and essentially rewrite this as:

int i = 53;

Note that while we can have:

long i = 53;

This won't happen with var. Though it can with:

var i = 53l; // i is now a long

Similarly:

var i = null; // not allowed as type can't be inferred.
var j = (string) null; // allowed as the expression (string) null has both type and value.

This can be a minor convenience with complicated types. It is more important with anonymous types:

var i = from x in SomeSource where x.Name.Length > 3 select new {x.ID, x.Name};
foreach(var j in i)
  Console.WriteLine(j.ID.ToString() + ":" + j.Name);

Here there is no other way of defining i and j than using var as there is no name for the types that they hold.

SQL Error: ORA-00936: missing expression

In the above query when we are trying to combine two or more tables it is necessary to use joins and specify the alias name for description and date (that means, the table from which you are fetching the description and date values)

SELECT DISTINCT Description, Date as treatmentDate  
FROM doothey.Patient P  
INNER JOIN doothey.Account A ON P.PatientID = A.PatientID  
INNER JOIN doothey.AccountLine AL ON A.AccountNo = AL.AccountNo  
INNER JOIN doothey.Item I ON AL.ItemNo = I.ItemNo  
WHERE p.FamilyName = 'Stange' AND p.GivenName = 'Jessie';

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

getting the ng-object selected with ng-change

You can also directly get selected value using following code

 <select ng-options='t.name for t in templates'
                  ng-change='selectedTemplate(t.url)'></select>

script.js

 $scope.selectedTemplate = function(pTemplate) {
    //Your logic
    alert('Template Url is : '+pTemplate);
}

How to replace blank (null ) values with 0 for all records?

If you're trying to do this with a query, then here is your answer:

SELECT ISNULL([field], 0) FROM [table]

Edit

ISNULL function was used incorrectly - this modified version uses IIF

SELECT IIF(ISNULL([field]), 0, [field]) FROM [table]

If you want to replace the actual values in the table, then you'll need to do it this way:

UPDATE [table] SET [FIELD] = 0 WHERE [FIELD] IS NULL

Javascript - Track mouse position

Irrespective of the browser, below lines worked for me to fetch correct mouse position.

event.clientX - event.currentTarget.getBoundingClientRect().left event.clientY - event.currentTarget.getBoundingClientRect().top