Programs & Examples On #Bloom filter

Bloom filter is a probabilistic data structure that tells you if a value might be in the set.

It says that TypeError: document.getElementById(...) is null

It means that element with id passed to getElementById() does not exist.

How to run Python script on terminal?

This Depends on what version of python is installed on you system. See below.

If You have Python 2.* version you have to run this command

python gameover.py

But if you have Python 3.* version you have to run this command

python3 gameover.py

Because for MAC with Python version 3.* you will get command not found error

if you run "python gameover.py"

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

I had this error message with boot2docker on windows with the docker-oracle-xe-11g image (https://registry.hub.docker.com/u/wnameless/oracle-xe-11g/).

The reason was that the virtual box disk was full (check with boot2docker.exe ssh df). Deleting old images and restarting the container solved the problem.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Is it possible to specify a different ssh port when using rsync?

Another option, in the host you run rsync from, set the port in the ssh config file, ie:

cat ~/.ssh/config
Host host
    Port 2222

Then rsync over ssh will talk to port 2222:

rsync -rvz --progress --remove-sent-files ./dir user@host:/path

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

Performance of FOR vs FOREACH in PHP

I'm not sure this is so surprising. Most people who code in PHP are not well versed in what PHP is actually doing at the bare metal. I'll state a few things, which will be true most of the time:

  1. If you're not modifying the variable, by-value is faster in PHP. This is because it's reference counted anyway and by-value gives it less to do. It knows the second you modify that ZVAL (PHP's internal data structure for most types), it will have to break it off in a straightforward way (copy it and forget about the other ZVAL). But you never modify it, so it doesn't matter. References make that more complicated with more bookkeeping it has to do to know what to do when you modify the variable. So if you're read-only, paradoxically it's better not the point that out with the &. I know, it's counter intuitive, but it's also true.

  2. Foreach isn't slow. And for simple iteration, the condition it's testing against — "am I at the end of this array" — is done using native code, not PHP opcodes. Even if it's APC cached opcodes, it's still slower than a bunch of native operations done at the bare metal.

  3. Using a for loop "for ($i=0; $i < count($x); $i++) is slow because of the count(), and the lack of PHP's ability (or really any interpreted language) to evaluate at parse time whether anything modifies the array. This prevents it from evaluating the count once.

  4. But even once you fix it with "$c=count($x); for ($i=0; $i<$c; $i++) the $i<$c is a bunch of Zend opcodes at best, as is the $i++. In the course of 100000 iterations, this can matter. Foreach knows at the native level what to do. No PHP opcodes needed to test the "am I at the end of this array" condition.

  5. What about the old school "while(list(" stuff? Well, using each(), current(), etc. are all going to involve at least 1 function call, which isn't slow, but not free. Yes, those are PHP opcodes again! So while + list + each has its costs as well.

For these reasons foreach is understandably the best option for simple iteration.

And don't forget, it's also the easiest to read, so it's win-win.

When should I use Lazy<T>?

Just to point onto the example posted by Mathew

public sealed class Singleton
{
    // Because Singleton's constructor is private, we must explicitly
    // give the Lazy<Singleton> a delegate for creating the Singleton.
    private static readonly Lazy<Singleton> instanceHolder =
        new Lazy<Singleton>(() => new Singleton());

    private Singleton()
    {
        ...
    }

    public static Singleton Instance
    {
        get { return instanceHolder.Value; }
    }
}

before the Lazy was born we would have done it this way:

private static object lockingObject = new object();
public static LazySample InstanceCreation()
{
    if(lazilyInitObject == null)
    {
         lock (lockingObject)
         {
              if(lazilyInitObject == null)
              {
                   lazilyInitObject = new LazySample ();
              }
         }
    }
    return lazilyInitObject ;
}

How do I use a delimiter with Scanner.useDelimiter in Java?

The scanner can also use delimiters other than whitespace.

Easy example from Scanner API:

 String input = "1 fish 2 fish red fish blue fish";

 // \\s* means 0 or more repetitions of any whitespace character 
 // fish is the pattern to find
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");

 System.out.println(s.nextInt());   // prints: 1
 System.out.println(s.nextInt());   // prints: 2
 System.out.println(s.next());      // prints: red
 System.out.println(s.next());      // prints: blue

 // don't forget to close the scanner!!
 s.close(); 

The point is to understand the regular expressions (regex) inside the Scanner::useDelimiter. Find an useDelimiter tutorial here.


To start with regular expressions here you can find a nice tutorial.

Notes

abc…    Letters
123…    Digits
\d      Any Digit
\D      Any Non-digit character
.       Any Character
\.      Period
[abc]   Only a, b, or c
[^abc]  Not a, b, nor c
[a-z]   Characters a to z
[0-9]   Numbers 0 to 9
\w      Any Alphanumeric character
\W      Any Non-alphanumeric character
{m}     m Repetitions
{m,n}   m to n Repetitions
*       Zero or more repetitions
+       One or more repetitions
?       Optional character
\s      Any Whitespace
\S      Any Non-whitespace character
^…$     Starts and ends
(…)     Capture Group
(a(bc)) Capture Sub-group
(.*)    Capture all
(ab|cd) Matches ab or cd

Run a task every x-minutes with Windows Task Scheduler

After you select the minimum repeat option (5 minutes or 10 minutes) you can highlight the number and write whatever number you want

Failed to resolve: com.android.support:appcompat-v7:28.0

Run

gradlew -q app:dependencies

It will remove what is wrong.

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

How to set timeout on python's socket recv method?

Shout out to: https://boltons.readthedocs.io/en/latest/socketutils.html

It provides a buffered socket, this provides a lot of very useful functionality such as:

.recv_until()    #recv until occurrence of bytes
.recv_closed()   #recv until close
.peek()          #peek at buffer but don't pop values
.settimeout()    #configure timeout (including recv timeout)

How to add anchor tags dynamically to a div in Javascript?

With jquery

  $("div#id").append('<a href=#>Your LINK TITLE</a>')

With javascript

   var new_a = document.createElement('a');
   new_a.setAttribute("href", "link url here");
   new_a.innerHTML = "your link text";
   //add new link to the DOM
   document.appendChild(new_a);

Pandas: sum DataFrame rows for given columns

Create a list of column names you want to add up.

df['total']=df.loc[:,list_name].sum(axis=1)

If you want the sum for certain rows, specify the rows using ':'

Html.Textbox VS Html.TextboxFor

Html.TextBox amd Html.DropDownList are not strongly typed and hence they doesn't require a strongly typed view. This means that we can hardcode whatever name we want. On the other hand, Html.TextBoxFor and Html.DropDownListFor are strongly typed and requires a strongly typed view, and the name is inferred from the lambda expression.

Strongly typed HTML helpers also provide compile time checking.

Since, in real time, we mostly use strongly typed views, prefer to use Html.TextBoxFor and Html.DropDownListFor over their counterparts.

Whether, we use Html.TextBox & Html.DropDownList OR Html.TextBoxFor & Html.DropDownListFor, the end result is the same, that is they produce the same HTML.

Strongly typed HTML helpers are added in MVC2.

How to clear a chart from a canvas so that hover events cannot be triggered?

First put chart in some variable then history it next time before init

#Check if myChart object exist then distort it

    if($scope.myChart) {
      $scope.myChart.destroy();
    }

    $scope.myChart  = new Chart(targetCanvas

Best programming based games

I'd say the most famous programming game there has been is the core wars. I don't know if you can still find active "rings" although there was a lot when I tried it some time ago (4 or 5 years).

Why is processing a sorted array faster than processing an unsorted array?

In the same line (I think this was not highlighted by any answer) it's good to mention that sometimes (specially in software where the performance matters—like in the Linux kernel) you can find some if statements like the following:

if (likely( everything_is_ok ))
{
    /* Do something */
}

or similarly:

if (unlikely(very_improbable_condition))
{
    /* Do something */    
}

Both likely() and unlikely() are in fact macros that are defined by using something like the GCC's __builtin_expect to help the compiler insert prediction code to favour the condition taking into account the information provided by the user. GCC supports other builtins that could change the behavior of the running program or emit low level instructions like clearing the cache, etc. See this documentation that goes through the available GCC's builtins.

Normally this kind of optimizations are mainly found in hard-real time applications or embedded systems where execution time matters and it's critical. For example, if you are checking for some error condition that only happens 1/10000000 times, then why not inform the compiler about this? This way, by default, the branch prediction would assume that the condition is false.

Passing $_POST values with cURL

<?php
    function executeCurl($arrOptions) {

        $mixCH = curl_init();

        foreach ($arrOptions as $strCurlOpt => $mixCurlOptValue) {
            curl_setopt($mixCH, $strCurlOpt, $mixCurlOptValue);
        }

        $mixResponse = curl_exec($mixCH);
        curl_close($mixCH);
        return $mixResponse;
    }

    // If any HTTP authentication is needed.
    $username = 'http-auth-username';
    $password = 'http-auth-password';

    $requestType = 'POST'; // This can be PUT or POST

    // This is a sample array. You can use $arrPostData = $_POST
    $arrPostData = array(
        'key1'  => 'value-1-for-k1y-1',
        'key2'  => 'value-2-for-key-2',
        'key3'  => array(
                'key31'   => 'value-for-key-3-1',
                'key32'   => array(
                    'key321' => 'value-for-key321'
                )
        ),
        'key4'  => array(
            'key'   => 'value'
        )
    );

    // You can set your post data
    $postData = http_build_query($arrPostData); // Raw PHP array

    $postData = json_encode($arrPostData); // Only USE this when request JSON data.

    $mixResponse = executeCurl(array(
        CURLOPT_URL => 'http://whatever-your-request-url.com/xyz/yii',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPGET => true,
        CURLOPT_VERBOSE => true,
        CURLOPT_AUTOREFERER => true,
        CURLOPT_CUSTOMREQUEST => $requestType,
        CURLOPT_POSTFIELDS  => $postData,
        CURLOPT_HTTPHEADER  => array(
            "X-HTTP-Method-Override: " . $requestType,
            'Content-Type: application/json', // Only USE this when requesting JSON data
        ),

        // If HTTP authentication is required, use the below lines.
        CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
        CURLOPT_USERPWD  => $username. ':' . $password
    ));

    // $mixResponse contains your server response.

JSON Array iteration in Android/Java

While iterating over a JSON array (org.json.JSONArray, built into Android), watch out for null objects; for example, you may get "null" instead of a null string.

A check may look like:

s[i] = array.isNull(i) ? null : array.getString(i);

Ruby: character to ascii from a string

You could also just call to_a after each_byte or even better String#bytes

=> 'hello world'.each_byte.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

=> 'hello world'.bytes
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]

Javascript to stop HTML5 video playback on modal window close

When you close the video you just need to pause it.

$("#closeSimple").click(function() {
    $("div#simpleModal").removeClass("show");
    $("#videoContainer")[0].pause();
    return false;                   
});

<video id="videoContainer" width="320" height="240" src="Davis_5109iPadFig3.m4v" controls="controls"> </video>

Also, for reference, here's the Opera documentation for scripting video controls.

How to add a spinner icon to button when it's in the Loading state?

A lazy way to do this is with the UTF-8 entity code for a half circle \25E0 (aka &#x25e0;), which looks like ? and then keyframe animate it. It's a simple as:

_x000D_
_x000D_
.busy
{
animation: spin 1s infinite linear;
display:inline-block;
font-weight: bold;
font-family: sans-serif;
font-size: 35px;
font-style:normal;
color:#555;
}

.busy::before
{
content:"\25E0";
}

@keyframes spin
{
0% {transform: rotate(0deg);}
100% {transform: rotate(359deg);}
}
_x000D_
<i class="busy"></i>
_x000D_
_x000D_
_x000D_

MVC4 Passing model from view to controller

I hope this complete example will help you.

This is the TaxiInfo class which holds information about a taxi ride:

namespace Taxi.Models
{
    public class TaxiInfo
    {
        public String Driver { get; set; }
        public Double Fare { get; set; }
        public Double Distance { get; set; }
        public String StartLocation { get; set; }
        public String EndLocation { get; set; }
    }
}

We also have a convenience model which holds a List of TaxiInfo(s):

namespace Taxi.Models
{
    public class TaxiInfoSet
    {
        public List<TaxiInfo> TaxiInfoList { get; set; }

        public TaxiInfoSet(params TaxiInfo[] TaxiInfos)
        {
            TaxiInfoList = new List<TaxiInfo>();

            foreach(var TaxiInfo in TaxiInfos)
            {
                TaxiInfoList.Add(TaxiInfo);
            }
        }
    }
}

Now in the home controller we have the default Index action which for this example makes two taxi drivers and adds them to the list contained in a TaxiInfo:

public ActionResult Index()
{
    var taxi1 = new TaxiInfo() { Fare = 20.2, Distance = 15, Driver = "Billy", StartLocation = "Perth", EndLocation = "Brisbane" };
    var taxi2 = new TaxiInfo() { Fare = 2339.2, Distance = 1500, Driver = "Smith", StartLocation = "Perth", EndLocation = "America" };

    return View(new TaxiInfoSet(taxi1,taxi2));
}

The code for the view is as follows:

@model Taxi.Models.TaxiInfoSet
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@foreach(var TaxiInfo in Model.TaxiInfoList){
    <form>
        <h1>Cost: [email protected]</h1>
        <h2>Distance: @(TaxiInfo.Distance) km</h2>
        <p>
            Our diver, @TaxiInfo.Driver will take you from @TaxiInfo.StartLocation to @TaxiInfo.EndLocation
        </p>
        @Html.ActionLink("Home","Booking",TaxiInfo)
    </form>
}

The ActionLink is responsible for the re-directing to the booking action of the Home controller (and passing in the appropriate TaxiInfo object) which is defiend as follows:

    public ActionResult Booking(TaxiInfo Taxi)
    {
        return View(Taxi);
    }

This returns a the following view:

@model Taxi.Models.TaxiInfo

@{
    ViewBag.Title = "Booking";
}

<h2>Booking For</h2>
<h1>@Model.Driver, going from @Model.StartLocation to @Model.EndLocation (a total of @Model.Distance km) for [email protected]</h1>

A visual tour:

The Index view

The Booking view

Which equals operator (== vs ===) should be used in JavaScript comparisons?

Using the == operator (Equality)

true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2;  //true, because "2" is converted to 2 and then compared

Using the === operator (Identity)

true === 1; //false
"2" === 2;  //false

This is because the equality operator == does type coercion, meaning that the interpreter implicitly tries to convert the values before comparing.

On the other hand, the identity operator === does not do type coercion, and thus does not convert the values when comparing, and is therefore faster (as according to This JS benchmark test) as it skips one step.

JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?

This is what i've implemented:

$(window).resize(function(){ setTimeout(someFunction, 500); });

we can clear the setTimeout if we expect resize to happen less than 500ms

Good Luck...

How to emit an event from parent to child?

As far as I know, there are 2 standard ways you can do that.

1. @Input

Whenever the data in the parent changes, the child gets notified about this in the ngOnChanges method. The child can act on it. This is the standard way of interacting with a child.

Parent-Component
public inputToChild: Object;

Parent-HTML
<child [data]="inputToChild"> </child>       

Child-Component: @Input() data;

ngOnChanges(changes: { [property: string]: SimpleChange }){
   // Extract changes to the input property by its name
   let change: SimpleChange = changes['data']; 
// Whenever the data in the parent changes, this method gets triggered. You 
// can act on the changes here. You will have both the previous value and the 
// current value here.
}
  1. Shared service concept

Creating a service and using an observable in the shared service. The child subscribes to it and whenever there is a change, the child will be notified. This is also a popular method. When you want to send something other than the data you pass as the input, this can be used.

SharedService
subject: Subject<Object>;

Parent-Component
constructor(sharedService: SharedService)
this.sharedService.subject.next(data);

Child-Component
constructor(sharedService: SharedService)
this.sharedService.subject.subscribe((data)=>{

// Whenever the parent emits using the next method, you can receive the data 
in here and act on it.})

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

how to do "press enter to exit" in batch

pause

will display:

Press any key to continue . . .

Convert comma separated string to array in PL/SQL

declare 
    v_str varchar2(100) := '1,2,3,4,6,7,8,9,0,';
    v_str1 varchar2(100); 
    v_comma_pos number := 0;    
    v_start_pos number := 1;
begin             
    loop        
    v_comma_pos := instr(v_str,',',v_start_pos);   
    v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos)); 
    dbms_output.put_line(v_str1);     
    if  v_comma_pos = 0 then     
    v_str1 := substr(v_str,v_start_pos);  
    dbms_output.put_line(v_str1);    
    exit;
    end if;    
    v_start_pos := v_comma_pos + 1;  
    if  v_comma_pos = 0 then    
    exit;
    end if;       
    end loop; 
end;

How to increase editor font size?

By default, Android Studio doesn't allow the normal CTRL + Mouse scroll to zoom in or out. You can enable it in the settings, though it seems its location has changed over time. Mac users are well documented in other answers, but I use Windows.

For Windows users in Android Studio 3.4, you go to File -> Settings -> General, then check the box Change font size (Zoom) with Ctrl+Mouse Wheel. See below:

enter image description here

How To Check If A Key in **kwargs Exists?

if kwarg.__len__() != 0:
    print(kwarg)

AngularJS - Trigger when radio button is selected

Should use ngChange instead of ngClick if trigger source is not from click.

Is the below what you want ? what exactly doesn't work in your case ?

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.value = "none" ;
    $scope.isChecked = false;
    $scope.checkStuff = function () {
        $scope.isChecked = !$scope.isChecked;
    }
}


<div ng-controller="MyCtrl">
    <input type="radio" ng-model="value" value="one" ng-change="checkStuff()" />
    <span> {{value}} isCheck:{{isChecked}} </span>
</div>   

How to set all elements of an array to zero or any same value?

If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};

// file scope
int arr[4];
// equivalent to
int arr[4] = {0};

Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.

// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};

How to remove youtube branding after embedding video in web page?

 autoplay=1&autohide=2&border=0&wmode=opaque&enablejsapi=1&modestbranding=1&controls=2&showinfo=1    

That worked for me, it still showed subscribe and it showed share link, but no youtube button to take them off the page to another. So that's the line I will use that I think will keep traffic my site and not take off to all the other sites.

how get yesterday and tomorrow datetime in c#

You can find this info right in the API reference.

var today = DateTime.Today;
var tomorrow = today.AddDays(1);
var yesterday = today.AddDays(-1);

Xcode Error: "The app ID cannot be registered to your development team."

My problem was I was modifying the settings for the wrong version of my app.

enter image description here

I had "Debug" selected instead of "Release", so my bundle identifier was not accurate when it came time to Archive.

How to create a HTML Table from a PHP array?

echo "<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>";
foreach($shop as $v){
    echo "<tr>";
    foreach($v as $vv){
        echo "<td>{$vv}</td>";
    }
    echo "<tr>";
}
echo "</table>";

Sort an ArrayList based on an object field

Modify the DataNode class so that it implements Comparable interface.

public int compareTo(DataNode o)
{
     return(degree - o.degree);
}

then just use

Collections.sort(nodeList);

MySQL limit from descending order

yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Using the following ways using only two keys will be the easier:

control + Tab

or

Alt + Left/Right

Eclipse will not start and I haven't changed anything

I used eclipse -clean -clearPersistedState and that worked for me. You will lose your window layout configuration, but that seems minor to me.

For Linux systems try: ./eclipse -clean -clearPersistedState

See Eclipse JUNO doesn't start

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

What is the difference between HTML tags and elements?

This visualization can help us to find out difference between concept of element and tag (each indent means contain):

- element

        - content:

            - text 

            - other elements 

            - or empty

        - and its markup

            - tags (start or end tag)

                - element name

                - angle brackets < >

                - or attributes (just for start tag)

                - or slash / 

Adding Buttons To Google Sheets and Set value to Cells on clicking

It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.

You can use following code to insert an image through script.

  function insertImageOnSpreadsheet() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'https://developers.google.com/adwords/scripts/images/reports.png');
  var binaryData = response.getContent();

  // Insert the image in cell A1.
  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1);
}

Above example has been copied from this link. Check noogui's reply for details.

In case you need to insert image from Google Drive, please check this link for current updates.

Relationship between hashCode and equals method in Java

The problem you will have is with collections where unicity of elements is calculated according to both .equals() and .hashCode(), for instance keys in a HashMap.

As its name implies, it relies on hash tables, and hash buckets are a function of the object's .hashCode().

If you have two objects which are .equals(), but have different hash codes, you lose!

The part of the contract here which is important is: objects which are .equals() MUST have the same .hashCode().

This is all documented in the javadoc for Object. And Joshua Bloch says you must do it in Effective Java. Enough said.

How to change background color of cell in table using java script

Try this:

function btnClick() {
    var x = document.getElementById("mytable").getElementsByTagName("td");
    x[0].innerHTML = "i want to change my cell color";
    x[0].style.backgroundColor = "yellow";            
}

Set from JS, backgroundColor is the equivalent of background-color in your style-sheet.

Note also that the .cells collection belongs to a table row, not to the table itself. To get all the cells from all rows you can instead use getElementsByTagName().

Demo: http://jsbin.com/ekituv/edit#preview

One liner to check if element is in the list

I would use:

if (Stream.of("a","b","c").anyMatch("a"::equals)) {
    //Code to execute
};

or:

Stream.of("a","b","c")
    .filter("a"::equals)
    .findAny()
    .ifPresent(ignore -> /*Code to execute*/);

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

This ORA error is occurred because of violation of unique constraint.

ORA-00001: unique constraint (constraint_name) violated

This is caused because of trying to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index.

You can resolve this either by

  • changing the constraint to allow duplicates, or
  • drop the unique constraint or you can change your SQL to avoid duplicate inserts

Is there any way to install Composer globally on Windows?

Unfortunately, all the good answers here didn't work for me. So after installing composer on windows 10, I just had to set system variable in environment variables and it worked.

Windows 10 environment variable -> system variables

Comma separated results in SQL

If you're stuck with SQL Server <2017, you can use GroupConcat. The syntax and the performance is far better than the FOR XML PATH sollution.

Installation:

-- https://codeplexarchive.blob.core.windows.net/archive/projects/groupconcat/groupconcat.zip
create assembly [GroupConcat] from 0x4D5A90000300000004000000FFFF0000B800000000000000400000000000000000000000000000000000000000000000000000000000000000000000800000000E1FBA0E00B409CD21B8014CCD21546869732070726F6772616D2063616E6E6F742062652072756E20696E20444F53206D6F64652E0D0D0A2400000000000000504500004C01030058898C510000000000000000E00002210B010B00001E000000080000000000007E3D0000002000000040000000000010002000000002000004000000000000000400000000000000008000000002000000000000030040850000100000100000000010000010000000000000100000000000000000000000243D000057000000004000003804000000000000000000000000000000000000006000000C00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000080000000000000000000000082000004800000000000000000000002E74657874000000841D000000200000001E000000020000000000000000000000000000200000602E7273726300000038040000004000000006000000200000000000000000000000000000400000402E72656C6F6300000C0000000060000000020000002600000000000000000000000000004000004200000000000000000000000000000000603D0000000000004800000002000500C02C00006410000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003202731100000A7D010000042A0000001330040047000000010000110F01281200000A2D3D0F01281300000A0A027B01000004066F1400000A2C1A027B01000004250B06250C07086F1500000A17586F1600000A2A027B0100000406176F1700000A2A001B30050089000000020000110F017B010000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B01000004076F1400000A2C29027B01000004250D072513040911046F1500000A0F017B01000004076F1500000A586F1600000A2B19027B01000004070F017B01000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0000000110000002000D006D7A000E000000001B3003009B00000003000011027B010000043989000000027B010000046F1D00000A16317B731E00000A0A027B010000046F1800000A0D2B341203281900000A0B160C2B1E061201281A00000A6F1F00000A260672010000706F1F00000A260817580C081201282000000A32D81203281B00000A2DC3DE0E1203FE160300001B6F1C00000ADC06066F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A000110000002002B00416C000E00000000133003003900000004000011036F2500000A0A0206732600000A7D01000004160B2B1B027B01000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF2A0000001B3002005B0000000500001103027B010000046F1D00000A6F2800000A027B010000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0300000406282A00000A2C0702067D030000042A5E02731100000A7D02000004027E2B00000A7D030000042A133004004F000000010000110F01281200000A2D450F01281300000A0A027B02000004066F1400000A2C1B027B02000004250B06250C07086F1500000A17586F1600000A2B0D027B0200000406176F1700000A020428070000062A001B300500A300000002000011027B03000004282C00000A2C0D020F017B030000047D030000040F017B020000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B02000004076F1400000A2C29027B02000004250D072513040911046F1500000A0F017B02000004076F1500000A586F1600000A2B19027B02000004070F017B02000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0001100000020027006D94000E000000001B300300B300000003000011027B0200000439A1000000027B020000046F1D00000A163E90000000731E00000A0A027B020000046F1800000A0D2B351203281900000A0B160C2B1F061201281A00000A6F1F00000A2606027B030000046F1F00000A260817580C081201282000000A32D71203281B00000A2DC2DE0E1203FE160300001B6F1C00000ADC06066F2100000A027B030000046F2D00000A59027B030000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A000110000002002E004270000E00000000133003004500000004000011036F2500000A0A0206732600000A7D02000004160B2B1B027B02000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D030000042A0000001B300200670000000500001103027B020000046F1D00000A6F2800000A027B020000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B030000046F2900000A2A000110000002001D002F4C000E000000001330020024000000060000110F01FE16060000016F2300000A0A027B0500000406282A00000A2C0702067D050000042AEA027B060000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D060000042A7A02731100000A7D04000004027E2B00000A7D0500000402167D060000042A00001330040056000000010000110F01281200000A2D4C0F01281300000A0A027B04000004066F1400000A2C1B027B04000004250B06250C07086F1500000A17586F1600000A2B0D027B0400000406176F1700000A0204280E0000060205280F0000062A00001B300500B800000002000011027B05000004282C00000A2C0D020F017B050000047D05000004027B060000042D0D020F017B060000047D060000040F017B040000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B04000004076F1400000A2C29027B04000004250D072513040911046F1500000A0F017B04000004076F1500000A586F1600000A2B19027B04000004070F017B04000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A0110000002003C006DA9000E000000001B300300D700000007000011027B0400000439C5000000027B040000046F1D00000A163EB4000000731E00000A0B027B06000004183313027B04000004731E000006733100000A0A2B0C027B04000004733200000A0A066F3300000A13042B351204283400000A0C160D2B1F071202281A00000A6F1F00000A2607027B050000046F1F00000A260917580D091202282000000A32D71204283500000A2DC2DE0E1204FE160600001B6F1C00000ADC07076F2100000A027B050000046F2D00000A59027B050000046F2D00000A6F2200000A6F2300000A282400000A2A14282400000A2A0001100000020052004294000E00000000133003005100000004000011036F2500000A0A0206732600000A7D04000004160B2B1B027B04000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F2700000A7D0500000402036F3600000A7D060000042A0000001B300200730000000500001103027B040000046F1D00000A6F2800000A027B040000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B050000046F2900000A03027B060000046F3700000A2A000110000002001D002F4C000E00000000EA027B080000042D310F01282E00000A172E150F01282E00000A182E0B7205000070732F00000A7A020F01282E00000A283000000A7D080000042A4E02731100000A7D0700000402167D080000042A00133004004F000000010000110F01281200000A2D450F01281300000A0A027B07000004066F1400000A2C1B027B07000004250B06250C07086F1500000A17586F1600000A2B0D027B0700000406176F1700000A020428160000062A001B3005009E00000002000011027B080000042D0D020F017B080000047D080000040F017B070000046F1800000A0C2B601202281900000A0A1200281A00000A0B027B07000004076F1400000A2C29027B07000004250D072513040911046F1500000A0F017B07000004076F1500000A586F1600000A2B19027B07000004070F017B07000004076F1500000A6F1700000A1202281B00000A2D97DE0E1202FE160300001B6F1C00000ADC2A000001100000020022006D8F000E000000001B300300C800000008000011027B0700000439B6000000027B070000046F1D00000A163EA5000000731E00000A0B027B08000004183313027B07000004731E000006733100000A0A2B0C027B07000004733200000A0A066F3300000A13052B3A1205283400000A0C1202281A00000A0D1613042B1A07096F1F00000A260772010000706F1F00000A2611041758130411041202282000000A32DB1205283500000A2DBDDE0E1205FE160600001B6F1C00000ADC07076F2100000A1759176F2200000A6F2300000A282400000A2A14282400000A2A01100000020052004799000E00000000133003004500000004000011036F2500000A0A0206732600000A7D07000004160B2B1B027B07000004036F2700000A036F2500000A6F1700000A0717580B0706175931DF02036F3600000A7D080000042A0000001B300200670000000500001103027B070000046F1D00000A6F2800000A027B070000046F1800000A0B2B221201281900000A0A031200281A00000A6F2900000A031200282000000A6F2800000A1201281B00000A2DD5DE0E1201FE160300001B6F1C00000ADC03027B080000046F3700000A2A000110000002001D002F4C000E000000002204036F3800000A2A1E02283900000A2A00000042534A4201000100000000000C00000076322E302E35303732370000000005006C000000C4060000237E0000300700006405000023537472696E677300000000940C00006C00000023555300000D0000100000002347554944000000100D00005403000023426C6F6200000000000000020000015717A2090900000000FA253300160000010000002500000006000000080000001E0000001E0000000500000039000000180000000800000003000000040000000400000006000000010000000300000000000A00010000000000060081007A000A00B20097000600C3007A000600E500CA000600F100CA000A001F010A0106004E0144010600600144010A009C010A010A00CA01970006001702050206002E02050206004B02050206006A02050206008302050206009C0205020600B70205020600D202050206000A03EB0206001E030502060057033703060077033703060095037A000A00AB0397000A00CC0397000600D303EB020600E903EB0217002B04000006004404CA00060070047A0006009A048E040600EB047A00060014057A0006001E057A000E002D05CA0006004005CA008F002B0400000000000001000000000001000100092110001A00270005000100010009211000330027000500020007000921100042002700050004000E00092110005200270005000700160001001000610027000D0009001D000100FE0010000100FE0010000100730139000100FE001000010073013900010095014F000100FE001000010095014F005020000000008600050118000100602000000000860029011C000100B4200000000086003401220002005C210000000086003A0128000300142200000000E6015B012D0004005C2200000000E6016D0133000500D4220000000081087D011C00060004230000000086000501180007001C2300000000860029013C000700782300000000860034014400090038240000000086003A0128000A00082500000000E6015B012D000B005C2500000000E6016D0133000C00E0250000000081087D011C000D001026000000008108A40152000E004B26000000008600050118000F006C26000000008600290158000F00D026000000008600340162001200A4270000000086003A0128001300982800000000E6015B012D001400F82800000000E6016D01330015008829000000008108A40152001600C329000000008600050118001700D82900000000860029016D001700342A000000008600340175001900F02A0000000086003A0128001A00D42B00000000E6015B012D001B00282C00000000E6016D0133001C00AC2C00000000E601B6017B001D00B52C000000008618BE0118001F0000000100C40100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200EC0100000100DC0100000000000000000100E20100000100E40100000100E60100000100E60100000100C40100000200EC0100000300F60100000100DC0100000000000000000100E20100000100E40100000100E60100000100C40100000200F60100000100DC0100000000000000000100E20100000100E40100000100010200000200030202000900030009000400090005000900060006005100BE0118005900BE01BA006100BE01BA006900BE01BA007100BE01BA007900BE01BA008100BE01BA008900BE01BA009100BE01BA009900BE01BF00A100BE01BA00A900BE01C400B100BE011800B900BE011800C100BE01C900D100BE0142011400BE0118003100F4034F013100FF035301140009045701140015045D0114001E0464011400270464011400360477011C005304890124005F049B011C0067044F01F1007C04180014008404B701F900BE011800F900A804BB012400FF03C101F900AF04B701F900BA04C6011900C10453013100CA04CD013900D604B7011400BE01C4003900E004530141006D01C40041006D01BA000101F204F9010101000539000101060503020101AF04B7014900FF0308020901BE01BA00110126050C022C00BE0119022C00BE012C022C0036043902340053048901340067044F0139004E05080241006D0167020101570587021900BE01180024000B0081002E006B0035032E002B000E032E0013008C022E001B009D022E0023000E032E003B0014032E0033008C022E0043000E032E0053000E032E0063002C0343007B00CF0063007B00CF0064000B00940083007B00CF00A3007B00CF00E4000B00810004010B00A70044010B009400E4010B00810004020B00A70064020B009400E4020B00810044030B0094006C01A001D301E501EA01FF014D026C0203000100040002000500040000008B014A0000008B014A000000AF0168000000AF01680001000700030001000E00050001000F0007000100160009000A004801820194011102450204800000010000000D13F49F00000000000027000000020000000000000000000000010071000000000002000000000000000000000001008B000000000002000000000000000000000001007A000000000000000000003C4D6F64756C653E0047726F7570436F6E6361742E646C6C0047524F55505F434F4E4341540047726F7570436F6E6361740047524F55505F434F4E4341545F440047524F55505F434F4E4341545F44530047524F55505F434F4E4341545F530052657665727365436F6D7061726572006D73636F726C69620053797374656D0056616C7565547970650053797374656D2E44617461004D6963726F736F66742E53716C5365727665722E536572766572004942696E61727953657269616C697A65004F626A6563740053797374656D2E436F6C6C656374696F6E732E47656E657269630049436F6D706172657260310044696374696F6E61727960320076616C75657300496E69740053797374656D2E446174612E53716C54797065730053716C537472696E6700416363756D756C617465004D65726765005465726D696E6174650053797374656D2E494F0042696E61727952656164657200526561640042696E6172795772697465720057726974650064656C696D69746572007365745F44656C696D697465720044656C696D6974657200736F727442790053716C42797465007365745F536F7274427900536F7274427900436F6D70617265002E63746F720056414C55450053716C46616365744174747269627574650047726F7570007200770076616C75650044454C494D4954455200534F52545F4F52444552007800790053797374656D2E5265666C656374696F6E00417373656D626C795469746C6541747472696275746500417373656D626C794465736372697074696F6E41747472696275746500417373656D626C79436F6E66696775726174696F6E41747472696275746500417373656D626C79436F6D70616E7941747472696275746500417373656D626C7950726F6475637441747472696275746500417373656D626C79436F7079726967687441747472696275746500417373656D626C7954726164656D61726B41747472696275746500417373656D626C7943756C747572654174747269627574650053797374656D2E52756E74696D652E496E7465726F70536572766963657300436F6D56697369626C6541747472696275746500417373656D626C7956657273696F6E4174747269627574650053797374656D2E52756E74696D652E436F6D70696C6572536572766963657300436F6D70696C6174696F6E52656C61786174696F6E734174747269627574650052756E74696D65436F6D7061746962696C6974794174747269627574650053657269616C697A61626C654174747269627574650053716C55736572446566696E656441676772656761746541747472696275746500466F726D6174005374727563744C61796F7574417474726962757465004C61796F75744B696E64006765745F49734E756C6C006765745F56616C756500436F6E7461696E734B6579006765745F4974656D007365745F4974656D0041646400456E756D657261746F7200476574456E756D657261746F72004B657956616C7565506169726032006765745F43757272656E74006765745F4B6579004D6F76654E6578740049446973706F7361626C6500446973706F7365006765745F436F756E740053797374656D2E5465787400537472696E674275696C64657200417070656E64006765745F4C656E6774680052656D6F766500546F537472696E67006F705F496D706C696369740052656164496E7433320052656164537472696E6700537472696E67006F705F496E657175616C69747900456D7074790049734E756C6C4F72456D70747900457863657074696F6E00436F6E7665727400546F4279746500536F7274656444696374696F6E6172796032004944696374696F6E617279603200526561644279746500436F6D70617265546F0000000000032C00006549006E00760061006C0069006400200053006F0072007400420079002000760061006C00750065003A00200075007300650020003100200066006F007200200041005300430020006F00720020003200200066006F007200200044004500530043002E0000008002D97266C26949A672EA780F71C8980008B77A5C561934E08905151211010E0706151215020E0803200001052001011119052001011108042000111905200101121D05200101122102060E072002011119111905200101110C04280011190206050520010111250920030111191119112505200101111004280011250720020111191125052001011114052002080E0E12010001005408074D617853697A65A00F000012010001005408074D617853697A65FFFFFFFF12010001005408074D617853697A6504000000042001010E0420010102042001010805200101116572010002000000050054080B4D61784279746553697A65FFFFFFFF5402124973496E76617269616E74546F4E756C6C73015402174973496E76617269616E74546F4475706C696361746573005402124973496E76617269616E74546F4F726465720154020D49734E756C6C4966456D7074790105200101116D06151215020E08032000020320000E0520010213000620011301130007200201130013010A07030E151215020E080E0A2000151171021300130106151171020E080A2000151175021300130106151175020E080420001300160705151175020E080E151171020E08151215020E080E03200008052001127D0E0420001301062002127D080805000111190E110704127D151175020E0808151171020E0804070208080E0702151175020E08151171020E08050002020E0E0307010E040001020E032000050400010505071512808D020E08122002011512809102130013011512110113000C2001011512809102130013010B20001511809502130013010715118095020E081907051512808D020E08127D151175020E080815118095020E0804200101051A07061512808D020E08127D151175020E080E0815118095020E08042001080E1001000B47726F7570436F6E63617400007001006B537472696E6720636F6E636174656E6174696F6E2061676772656761746520666F722053514C205365727665722E2044726F702D696E207265706C6163656D656E7420666F72206275696C742D696E204D7953514C2047524F55505F434F4E4341542066756E74696F6E2E000005010000000017010012436F7079726967687420C2A920203230313100000801000800000000001E01000100540216577261704E6F6E457863657074696F6E5468726F7773014C3D000000000000000000006E3D0000002000000000000000000000000000000000000000000000603D00000000000000000000000000000000000000005F436F72446C6C4D61696E006D73636F7265652E646C6C0000000000FF25002000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100100000001800008000000000000000000000000000000100010000003000008000000000000000000000000000000100000000004800000058400000E00300000000000000000000E00334000000560053005F00560045005200530049004F004E005F0049004E0046004F0000000000BD04EFFE0000010000000100F49F0D1300000100F49F0D133F000000000000000400000002000000000000000000000000000000440000000100560061007200460069006C00650049006E0066006F00000000002400040000005400720061006E0073006C006100740069006F006E00000000000000B00440030000010053007400720069006E006700460069006C00650049006E0066006F0000001C0300000100300030003000300030003400620030000000F0006C00010043006F006D006D0065006E0074007300000053007400720069006E006700200063006F006E0063006100740065006E006100740069006F006E002000610067006700720065006700610074006500200066006F0072002000530051004C0020005300650072007600650072002E002000440072006F0070002D0069006E0020007200650070006C006100630065006D0065006E007400200066006F00720020006200750069006C0074002D0069006E0020004D007900530051004C002000470052004F00550050005F0043004F004E004300410054002000660075006E00740069006F006E002E00000040000C000100460069006C0065004400650073006300720069007000740069006F006E0000000000470072006F007500700043006F006E00630061007400000040000F000100460069006C006500560065007200730069006F006E000000000031002E0030002E0034003800370037002E00340030003900340038000000000040001000010049006E007400650072006E0061006C004E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C0000004800120001004C006500670061006C0043006F007000790072006900670068007400000043006F0070007900720069006700680074002000A90020002000320030003100310000004800100001004F0072006900670069006E0061006C00460069006C0065006E0061006D0065000000470072006F007500700043006F006E006300610074002E0064006C006C00000038000C000100500072006F0064007500630074004E0061006D00650000000000470072006F007500700043006F006E00630061007400000044000F000100500072006F006400750063007400560065007200730069006F006E00000031002E0030002E0034003800370037002E00340030003900340038000000000048000F00010041007300730065006D0062006C0079002000560065007200730069006F006E00000031002E0030002E0034003800370037002E003400300039003400380000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003000000C000000803D00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 with permission_set = safe;
create aggregate [dbo].[GROUP_CONCAT]    (@VALUE [nvarchar](4000))                                                      returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT];
create aggregate [dbo].[GROUP_CONCAT_D]  (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4))                            returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_D];
create aggregate [dbo].[GROUP_CONCAT_DS] (@VALUE [nvarchar](4000), @DELIMITER [nvarchar](4), @SORT_ORDER [tinyint])     returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_DS];
create aggregate [dbo].[GROUP_CONCAT_S]  (@VALUE [nvarchar](4000), @SORT_ORDER [tinyint])                               returns[nvarchar](max) external name [GroupConcat].[GroupConcat.GROUP_CONCAT_S];

go

Usage:

declare @liststr varchar(max)
select @liststr = dbo.group_concat_d(institutionname, ',')
from education
where studentnumber = '111'
group by studentnumber;
select @liststr

GroupConcat does not support ordering, though. You could use PIVOT, CTE's and windows functions if you need ordering:

drop table if exists #students;
create table #students (
    name        varchar(20),
    institution varchar(20),
    year        int -- order by year
)
go

insert into #students(name, institution, year)
values
    ('Simon', 'INSTITUTION1', 2005),
    ('Simon', 'INSTITUTION2', 2008);

with cte as (
    select name,
           institution,
           rn = row_number() over (partition by name order by year)
    from #students
)
select name,
       [1] +
       isnull((',' + [2]), '') +
       isnull((',' + [3]), '') +
       isnull((',' + [4]), '') +
       isnull((',' + [5]), '') +
       isnull((',' + [6]), '') +
       isnull((',' + [7]), '') +
       isnull((',' + [8]), '') +
       isnull((',' + [9]), '') +
       isnull((',' + [10]), '') +
       isnull((',' + [11]), '') +
       isnull((',' + [12]), '') +
       isnull((',' + [13]), '') +
       isnull((',' + [14]), '') +
       isnull((',' + [15]), '') +
       isnull((',' + [16]), '') +
       isnull((',' + [17]), '') +
       isnull((',' + [18]), '') +
       isnull((',' + [19]), '') +
       isnull((',' + [20]), '')
from cte
    pivot (
    max(institution)
    for rn in ([1], [2], [3], [4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20])
    ) as piv

How to use Google fonts in React.js?

If you are using Create React App environment simply add @import rule to index.css as such:

@import url('https://fonts.googleapis.com/css?family=Anton');

Import index.css in your main React app:

import './index.css'

React gives you a choice of Inline styling, CSS Modules or Styled Components in order to apply CSS:

font-family: 'Anton', sans-serif;

How can I avoid running ActiveRecord callbacks?

# for rails 3
  if !ActiveRecord::Base.private_method_defined? :update_without_callbacks
    def update_without_callbacks
      attributes_with_values = arel_attributes_values(false, false, attribute_names)
      return false if attributes_with_values.empty?
      self.class.unscoped.where(self.class.arel_table[self.class.primary_key].eq(id)).arel.update(attributes_with_values)
    end
  end

Convert a object into JSON in REST service by Spring MVC


The Json conversion should work out-of-the box. In order this to happen you need add some simple configurations:
First add a contentNegotiationManager into your spring config file. It is responsible for negotiating the response type:

<bean id="contentNegotiationManager"
      class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
    <property name="favorPathExtension" value="false" />
    <property name="favorParameter" value="true" />
    <property name="ignoreAcceptHeader" value="true" />
    <property name="useJaf" value="false" />
     <property name="defaultContentType" value="application/json" />

      <property name="mediaTypes">
         <map>
            <entry key="json" value="application/json" />
            <entry key="xml" value="application/xml" />
         </map>
      </property>
   </bean>

   <mvc:annotation-driven
      content-negotiation-manager="contentNegotiationManager" />

   <context:annotation-config />

Then add Jackson2 jars (jackson-databind and jackson-core) in the service's class path. Jackson is responsible for the data serialization to JSON. Spring will detect these and initialize the MappingJackson2HttpMessageConverter automatically for you. Having only this configured I have my automatic conversion to JSON working. The described config has an additional benefit of giving you the possibility to serialize to XML if you set accept:application/xml header.

Get all LI elements in array

QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li tag) to get all of the li present inside the div with navbar element.

_x000D_
_x000D_
    let navbar = document_x000D_
      .getElementById("navbar")_x000D_
      .querySelectorAll('li');_x000D_
_x000D_
    navbar.forEach((item, index) => {_x000D_
      console.log({ index, item })_x000D_
    });
_x000D_
   _x000D_
<div id="navbar">_x000D_
 <ul>_x000D_
  <li id="navbar-One">One</li>_x000D_
  <li id="navbar-Two">Two</li>_x000D_
  <li id="navbar-Three">Three</li>_x000D_
  <li id="navbar-Four">Four</li>_x000D_
  <li id="navbar-Five">Five</li>_x000D_
 </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Google Colab: how to read data from my google drive?

What I have done is first:

from google.colab import drive
drive.mount('/content/drive/')

Then

%cd /content/drive/My Drive/Colab Notebooks/

After I can for example read csv files with

df = pd.read_csv("data_example.csv")

If you have different locations for the files just add the correct path after My Drive

Google Maps API Multiple Markers with Infowindows

function setMarkers(map,locations){

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

 var loan = locations[i][0];
 var lat = locations[i][1];
 var long = locations[i][2];
 var add =  locations[i][3];

 latlngset = new google.maps.LatLng(lat, long);

 var marker = new google.maps.Marker({  
          map: map, title: loan , position: latlngset  
 });
 map.setCenter(marker.getPosition());


 marker.content = "<h3>Loan Number: " + loan +  '</h3>' + "Address: " + add;


 google.maps.events.addListener(marker,'click', function(map,marker){
          map.infowindow.setContent(marker.content);
          map.infowindow.open(map,marker);

 });

 }
}

Then move var infowindow = new google.maps.InfoWindow() to the initialize() function:

function initialize() {

    var myOptions = {
      center: new google.maps.LatLng(33.890542, 151.274856),
      zoom: 8,
      mapTypeId: google.maps.MapTypeId.ROADMAP

    };
    var map = new google.maps.Map(document.getElementById("default"),
        myOptions);
    map.infowindow = new google.maps.InfoWindow();

    setMarkers(map,locations)

  }

Save the console.log in Chrome to a file

There is an open-source javascript plugin that does just that, but for any browser - debugout.js

Debugout.js records and save console.logs so your application can access them. Full disclosure, I wrote it. It formats different types appropriately, can handle nested objects and arrays, and can optionally put a timestamp next to each log. You can also toggle live-logging in one place, and without having to remove all your logging statements.

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

What's the difference between "static" and "static inline" function?

From my experience with GCC I know that static and static inline differs in a way how compiler issue warnings about unused functions. More precisely when you declare static function and it isn't used in current translation unit then compiler produce warning about unused function, but you can inhibit that warning with changing it to static inline.

Thus I tend to think that static should be used in translation units and benefit from extra check compiler does to find unused functions. And static inline should be used in header files to provide functions that can be in-lined (due to absence of external linkage) without issuing warnings.

Unfortunately I cannot find any evidence for that logic. Even from GCC documentation I wasn't able to conclude that inline inhibits unused function warnings. I'd appreciate if someone will share links to description of that.

What is the cleanest way to disable CSS transition effects temporarily?

If you want to remove CSS transitions, transformations and animations from the current webpage you can just execute this little script I wrote (inside your browsers console):

let filePath = "https://dl.dropboxusercontent.com/s/ep1nzckmvgjq7jr/remove_transitions_from_page.css";
let html = `<link rel="stylesheet" type="text/css" href="${filePath}">`;
document.querySelector("html > head").insertAdjacentHTML("beforeend", html);

It uses vanillaJS to load this css-file. Heres also a github repo in case you want to use this in the context of a scraper (Ruby-Selenium): remove-CSS-animations-repo

How can I trigger a JavaScript event click

.click() does not work with Android (look at mozilla docs, at mobile section). You can trigger the click event with this method:

function fireClick(node){
    if (document.createEvent) {
        var evt = document.createEvent('MouseEvents');
        evt.initEvent('click', true, false);
        node.dispatchEvent(evt);    
    } else if (document.createEventObject) {
        node.fireEvent('onclick') ; 
    } else if (typeof node.onclick == 'function') {
        node.onclick(); 
    }
}

From this post

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

Service Temporarily Unavailable Magento?

I had the same issue but have not found the maintenance.flag file in my Magento root. I simply deleted cache and sessions files and all worked again.

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

To send an mms for Android 4.0 api 14 or higher without permission to write apn settings, you can use this library: Retrieve mnc and mcc codes from android, then call

Carrier c = Carrier.getCarrier(mcc, mnc);
if (c != null) {
    APN a = c.getAPN();
    if (a != null) {
        String mmsc = a.mmsc;
        String mmsproxy = a.proxy; //"" if none
        int mmsport = a.port; //0 if none
    }
}

To use this, add Jsoup and droid prism jar to the build path, and import com.droidprism.*;

Java: Retrieving an element from a HashSet

The idea that you need to get the reference to the object that is contained inside a Set object is common. It can be archived by 2 ways:

  1. Use HashSet as you wanted, then:

    public Object getObjectReference(HashSet<Xobject> set, Xobject obj) {
        if (set.contains(obj)) {
            for (Xobject o : set) {
                if (obj.equals(o))
                    return o;
            }
        }
        return null;
    }
    

For this approach to work, you need to override both hashCode() and equals(Object o) methods In the worst scenario we have O(n)

  1. Second approach is to use TreeSet

    public Object getObjectReference(TreeSet<Xobject> set, Xobject obj) {
        if (set.contains(obj)) {
            return set.floor(obj);
        }
        return null;
    }
    

This approach gives O(log(n)), more efficient. You don't need to override hashCode for this approach but you have to implement Comparable interface. ( define function compareTo(Object o)).

How can I get the class name from a C++ object?

Just write simple template:

template<typename T>
const char* getClassName(T) {
  return typeid(T).name();
}

struct A {} a;

void main() {
   std::cout << getClassName(a);
}

Could not find default endpoint element

"This error can arise if you are calling the service in a class library and calling the class library from another project."

"In this case you will need to include the WS configuration settings into the main projects app.config if its a winapp or web.config if its a web app. This is the way to go even with PRISM and WPF/Silverlight."

Yes, but if you can't change main project (Orchard CMS for example), you can keep WCF service config in your project.

You need to create a service helper with client generation method:

public static class ServiceClientHelper
{
    public static T GetClient<T>(string moduleName) where T : IClientChannel
    {
        var channelType = typeof(T);
        var contractType = channelType.GetInterfaces().First(i => i.Namespace == channelType.Namespace);
        var contractAttribute = contractType.GetCustomAttributes(typeof(ServiceContractAttribute), false).First() as ServiceContractAttribute;

        if (contractAttribute == null)
            throw new Exception("contractAttribute not configured");

        //path to your lib app.config (mark as "Copy Always" in properties)
        var configPath = HostingEnvironment.MapPath(String.Format("~/Modules/{0}/bin/{0}.dll.config", moduleName)); 

        var configuration = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap { ExeConfigFilename = configPath }, ConfigurationUserLevel.None);
        var serviceModelSectionGroup = ServiceModelSectionGroup.GetSectionGroup(configuration);

        if (serviceModelSectionGroup == null)
            throw new Exception("serviceModelSectionGroup not configured");

        var endpoint = serviceModelSectionGroup.Client.Endpoints.OfType<ChannelEndpointElement>().First(e => e.Contract == contractAttribute.ConfigurationName);
        var channelFactory = new ConfigurationChannelFactory<T>(endpoint.Name, configuration, null);
        var client = channelFactory.CreateChannel();
        return client;
    }
}

and use it:

using (var client = ServiceClientHelper.GetClient<IDefaultNameServiceChannel>(yourLibName)) {
                ... get data from service ...
            }

See details in this article.

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

HTML: How to limit file upload to be only images?

HTML5 says <input type="file" accept="image/*">. Of course, never trust client-side validation: Always check again on the server-side...

How to develop Desktop Apps using HTML/CSS/JavaScript?

Awesomium makes it easy to use HTML UI in your C++ or .NET app

Update

My previous answer is now outdated. These days you would be crazy not to look into using Electron for this. Many popular desktop apps have been developed on top of it.

Export HTML table to pdf using jspdf

You can also use the jsPDF-AutoTable plugin. You can check out a demo here that uses the following code.

var doc = new jsPDF('p', 'pt');
var elem = document.getElementById("basic-table");
var res = doc.autoTableHtmlToJson(elem);
doc.autoTable(res.columns, res.data);
doc.save("table.pdf");

What is the meaning of CTOR?

To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()

internal sealed class CtorExplorer
{
   protected int a = 0;
   protected static int b = 0;
}

How can I expose more than 1 port with Docker?

If you are creating a container from an image and like to expose multiple ports (not publish) you can use the following command:

docker create --name `container name` --expose 7000 --expose 7001 `image name`

Now, when you start this container using the docker start command, the configured ports above will be exposed.

Best way to define private methods for a class in Objective-C

As other people said defining private methods in the @implementation block is OK for most purposes.

On the topic of code organization - I like to keep them together under pragma mark private for easier navigation in Xcode

@implementation MyClass 
// .. public methods

# pragma mark private 
// ...

@end

extract the date part from DateTime in C#

DateTime d = DateTime.Today.Date;
Console.WriteLine(d.ToShortDateString()); // outputs just date

if you want to compare dates, ignoring the time part, make an use of DateTime.Year and DateTime.DayOfYear properties.

code snippet

DateTime d1 = DateTime.Today;
DateTime d2 = DateTime.Today.AddDays(3);
if (d1.Year < d2.Year)
    Console.WriteLine("d1 < d2");
else
    if (d1.DayOfYear < d2.DayOfYear)
        Console.WriteLine("d1 < d2");

How to create JNDI context in Spring Boot with Embedded Tomcat Container

After all i got the answer thanks to wikisona, first the beans:

@Bean
public TomcatEmbeddedServletContainerFactory tomcatFactory() {
    return new TomcatEmbeddedServletContainerFactory() {

        @Override
        protected TomcatEmbeddedServletContainer getTomcatEmbeddedServletContainer(
                Tomcat tomcat) {
            tomcat.enableNaming();
            return super.getTomcatEmbeddedServletContainer(tomcat);
        }

        @Override
        protected void postProcessContext(Context context) {
            ContextResource resource = new ContextResource();
            resource.setName("jdbc/myDataSource");
            resource.setType(DataSource.class.getName());
            resource.setProperty("driverClassName", "your.db.Driver");
            resource.setProperty("url", "jdbc:yourDb");

            context.getNamingResources().addResource(resource);
        }
    };
}

@Bean(destroyMethod="")
public DataSource jndiDataSource() throws IllegalArgumentException, NamingException {
    JndiObjectFactoryBean bean = new JndiObjectFactoryBean();
    bean.setJndiName("java:comp/env/jdbc/myDataSource");
    bean.setProxyInterface(DataSource.class);
    bean.setLookupOnStartup(false);
    bean.afterPropertiesSet();
    return (DataSource)bean.getObject();
}

the full code it's here: https://github.com/wilkinsona/spring-boot-sample-tomcat-jndi

Creating temporary files in bash

Is there any advantage in creating a temporary file in a more careful way

The temporary files are usually created in the temporary directory (such as /tmp) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).


You could use the following approach to create the temporary directory:

TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"

or temporary file:

TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"

However it is still predictable and not considered safe.

As per man mktemp, we can read:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.

So to be safe, it is recommended to use mktemp command to create unique temporary file or directory (-d).

What exactly is the meaning of an API?

Well, in addition to all the answers, I am just adding an example.

As others said API stands for Application Programming Interface through which softwares can interact with each other. Note, not a human interaction.

Where it is used

An example: You are buying an item online through your credit card. You will provide credit card details and press 'continue' button. It will tell you whether your information is correct or not. To provide these results, there are lot of things in the background.

The application will send your credit card details to a remote application which will validate your information and send the result back to your application. API is used in this scenario.

I hope it helps for the beginners who don't understand really what API is.

ANOTHER EXAMPLE

Weather application

Without API - Weather application must open weather.com site and read the details as a human does.

With API - Weather application will send a message to weather.com and receive the result and then display it.

SOURCE - Various online resources

How to disable submit button once it has been clicked?

the trick is to delayed the button to be disabled, and submit the form you can use window.setTimeout('this.disabled=true',0); yes even with 0 MS is working

GUI Tool for PostgreSQL

Postgres Enterprise Manager from EnterpriseDB is probably the most advanced you'll find. It includes all the features of pgAdmin, plus monitoring of your hosts and database servers, predictive reporting, alerting and a SQL Profiler.

http://www.enterprisedb.com/products-services-training/products/postgres-enterprise-manager

Ninja edit disclaimer/notice: it seems that this user is affiliated with EnterpriseDB, as the linked Postgres Enterprise Manager website contains a video of one Dave Page.

Asynchronous method call in Python?

Is there any reason not to use threads? You can use the threading class. Instead of finished() function use the isAlive(). The result() function could join() the thread and retrieve the result. And, if you can, override the run() and __init__ functions to call the function specified in the constructor and save the value somewhere to the instance of the class.

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

You need to fix the source of the string in the first place.

A string in .NET is actually just an array of 16-bit unicode code-points, characters, so a string isn't in any particular encoding.

It's when you take that string and convert it to a set of bytes that encoding comes into play.

In any case, the way you did it, encoded a string to a byte array with one character set, and then decoding it with another, will not work, as you see.

Can you tell us more about where that original string comes from, and why you think it has been encoded wrong?

Why is semicolon allowed in this python snippet?

Python does let you use a semi-colon to denote the end of a statement if you are including more than one statement on a line.

How do I get a Date without time in Java?

It does not make sense to talk about a date without a timestamp with regards to the Date routines in the standard java runtime, as it essentially maps down to a specific millisecond and not a date. Said millisecond intrinsically has a time of day attached to it which makes it vulnerable to timezone problems like Daylight Savings Time and other calendar adjustments. See Why is subtracting these two times (in 1927) giving a strange result? for an interesting example.

If you want to work with dates instead of milliseconds, you need to use something else. For Java 8 there is a new set of methods providing exactly what you ask for. For Java 7 and earlier use http://www.joda.org/joda-time/

How to configure logging to syslog in Python?

I fix it on my notebook. The rsyslog service did not listen on socket service.

I config this line bellow in /etc/rsyslog.conf file and solved the problem:

$SystemLogSocketName /dev/log

Html helper for <input type="file" />

Or you could do it properly:

In your HtmlHelper Extension class:

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression)
    {
        return helper.FileFor(expression, null);
    }

public static MvcHtmlString FileFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes)
    {
        var builder = new TagBuilder("input");

        var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));
        builder.GenerateId(id);
        builder.MergeAttribute("name", id);
        builder.MergeAttribute("type", "file");

        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        // Render tag
        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
    }

This line:

var id = helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));

Generates an id unique to the model, you know in lists and stuff. model[0].Name etc.

Create the correct property in the model:

public HttpPostedFileBase NewFile { get; set; }

Then you need to make sure your form will send files:

@using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))

Then here's your helper:

@Html.FileFor(x => x.NewFile)

Does Notepad++ show all hidden characters?

Double check your text with the Hex Editor Plug-in. In your case there may have been some control characters which have crept into your text. Usually you'll look at the white-space, and it will say 32 32 32 32, or for Unicode 32 00 32 00 32 00 32 00. You may find the problem this way, providing there isn't masses of code.

Download the Hex Plugin from here; http://sourceforge.net/projects/npp-plugins/files/Hex%20Editor/

How can I select all options of multi-select select box on click?

I'm able to make it in a native way @ jsfiddle. Hope it will help.

Post improved answer when it work, and help others.

$(function () { 

    $(".example").multiselect({
                checkAllText : 'Select All',
            uncheckAllText : 'Deselect All',
            selectedText: function(numChecked, numTotal, checkedItems){
              return numChecked + ' of ' + numTotal + ' checked';
            },
            minWidth: 325
    });
    $(".example").multiselect("checkAll");    

});

http://jsfiddle.net/shivasakthi18/25uvnyra/

How do I automatically update a timestamp in PostgreSQL

You'll need to write an insert trigger, and possible an update trigger if you want it to change when the record is changed. This article explains it quite nicely:

http://www.revsys.com/blog/2006/aug/04/automatically-updating-a-timestamp-column-in-postgresql/

CREATE OR REPLACE FUNCTION update_modified_column()   
RETURNS TRIGGER AS $$
BEGIN
    NEW.modified = now();
    RETURN NEW;   
END;
$$ language 'plpgsql';

Apply the trigger like this:

CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON customer FOR EACH ROW EXECUTE PROCEDURE  update_modified_column();

ORA-01843 not a valid month- Comparing Dates

If you don't need to check exact timestamp, use

SELECT * FROM MYTABLE WHERE trunc(DATEIN) = TO_DATE('23-04-49','DD-MM-YY');

otherwise, you can use

SELECT * FROM MYTABLE WHERE DATEIN = TO_DATE('23-04-49 20:18:07','DD-MM-YY HH24:MI:SS');

Here, you use hard code date,if you directly compare then you must use DD-MM-YY HH24:MI:SS else you might get ORA-01849: hour must be between 1 and 12.

In HTML5, should the main navigation be inside or outside the <header> element?

It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.

The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?

Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.

Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.

add title attribute from css

You can't. CSS is a presentation language. It isn't designed to add content (except for the very trivial with :before and :after).

Unable to auto-detect email address

git config --global user.email "put your email address here" # user.email will still be there  
git config --global user.name "put your github username here" # user.name will still be there

Note: it might prompt you to enter your git username and password. This works fine for me.

The AWS Access Key Id does not exist in our records

This could happen because there's an issue with your AWS Secret Access Key. After messing around with AWS Amplify, I ran into this issue. The quickest way is to create a new pair of AWS Access Key ID and AWS Secret Access Key and run aws configure again. I works for me. I hope this helps.

Change Text Color of Selected Option in a Select Box

<html>
  <style>
.selectBox{
 color:White;
}
.optionBox{
  color:black;
}

</style>
<body>
<select class = "selectBox">
  <option class = "optionBox">One</option>
  <option class = "optionBox">Two</option>
  <option class = "optionBox">Three</option>
</select>

What is an unsigned char?

Because i feel it's really called for, i just want to state some rules of C and C++ (they are the same in this regard). First, all bits of unsigned char participate in determining the value if any unsigned char object. Second, unsigned char is explicitly stated unsigned.

Now, i had a discussion with someone about what happens when you convert the value -1 of type int to unsigned char. He refused the idea that the resulting unsigned char has all its bits set to 1, because he was worried about sign representation. But he don't have to. It's immediately following out of this rule that the conversion does what is intended:

If the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type. (6.3.1.3p2 in a C99 draft)

That's a mathematical description. C++ describes it in terms of modulo calculus, which yields to the same rule. Anyway, what is not guaranteed is that all bits in the integer -1 are one before the conversion. So, what do we have so we can claim that the resulting unsigned char has all its CHAR_BIT bits turned to 1?

  1. All bits participate in determining its value - that is, no padding bits occur in the object.
  2. Adding only one time UCHAR_MAX+1 to -1 will yield a value in range, namely UCHAR_MAX

That's enough, actually! So whenever you want to have an unsigned char having all its bits one, you do

unsigned char c = (unsigned char)-1;

It also follows that a conversion is not just truncating higher order bits. The fortunate event for two's complement is that it is just a truncation there, but the same isn't necessarily true for other sign representations.

Programmatically shut down Spring Boot application

The simplest way would be to inject the following object where you need to initiate the shutdown

ShutdownManager.java

import org.springframework.context.ApplicationContext;
import org.springframework.boot.SpringApplication;

@Component
class ShutdownManager {

    @Autowired
    private ApplicationContext appContext;

    /*
     * Invoke with `0` to indicate no error or different code to indicate
     * abnormal exit. es: shutdownManager.initiateShutdown(0);
     **/
    public void initiateShutdown(int returnCode){
        SpringApplication.exit(appContext, () -> returnCode);
    }
}

How to display Toast in Android?

I ran across the answers here, and was attracted by the fact that there seems to be someone poking around, believing that an Activity context is required. This is not the case. However, it is a requirement that a Toast is posted from the main event or UI Thread. So, getting this to work outside of an activity context is a little bit tricky. Here is an example that would work inside of a system service, or any potential class that ultimately inherits from Context.

public class MyService extends AccessibilityService {

    public void postToastMessage(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Note that we do not need access to an instance of Activity for this to work. Please stop suggesting this is the case! If Activity were required, the method signature wouldn't call for a Context.

What is the difference between ndarray and array in numpy?

Just a few lines of example code to show the difference between numpy.array and numpy.ndarray

Warm up step: Construct a list

a = [1,2,3]

Check the type

print(type(a))

You will get

<class 'list'>

Construct an array (from a list) using np.array

a = np.array(a)

Or, you can skip the warm up step, directly have

a = np.array([1,2,3])

Check the type

print(type(a))

You will get

<class 'numpy.ndarray'>

which tells you the type of the numpy array is numpy.ndarray

You can also check the type by

isinstance(a, (np.ndarray))

and you will get

True

Either of the following two lines will give you an error message

np.ndarray(a)                # should be np.array(a)
isinstance(a, (np.array))    # should be isinstance(a, (np.ndarray))

Enterprise app deployment doesn't work on iOS 7.1

If you happen to have AWS S3 that works like a charm also. Well. Relatively speaking :-)

Create a bucket for your ad hocs in AWS, add an index file (it can just be a blank index.html file) then using a client that can connect to S3 like CyberDuck or Coda (I used Coda - where you'd select Add Site to get a connection window) then set the connections like the attached:

Then build your enterprise ad hoc in XCode and make sure you use https://s3.amazonaws.com/your-bucket-name/your-ad-hoc-folder/your-app.ipa as the Application URL, and upload it to your new S3 bucket directory.

Your itms link should match, i.e. itms-services://?action=download-manifest&url=https://s3.amazonaws.com/your-bucket-name/your-ad-hoc-folder/your-app.plist

And voilá.

This is only for generic AWS URLs - I haven't tried with custom URLs on AWS so you might have to do a few things differently.

I was determined to try to make James Webster's solution above work, but I couldn't get it to work with Plesk.

An unhandled exception of type 'System.IO.FileNotFoundException' occurred in Unknown Module

What I would do is use this tool and step through where you are getting the exception

http://www.reflector.net/

Read this it will tell you how to create PDB's so you do not have to have all your references setup.

http://www.cplotts.com/2011/01/14/net-reflector-pro-debugging-the-net-framework-source-code/

It is a trial and I am not related to redgate at all I just use there software.

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

Java web start - Unable to load resource

Include your IP address in your host file (C:\Windows\System32\drivers\etc\host) for the respective server:

Sample Entry:

10.100.101.102 server1.us.vijay.com Vijay's Server

What is DOM element?

It's actually Document Object Model. HTML is used to build the DOM which is an in-memory representation of the page (while closely related to HTML, they are not exactly the same thing). Things like CSS and Javascript interact with the DOM.

How to check if a date is in a given range?

Convert them into dates or timestamp integers and then just check of $date_from_user is <= $end_date and >= $start_date

How to initialize a nested struct?

One gotcha arises when you want to instantiate a public type defined in an external package and that type embeds other types that are private.

Example:

package animals

type otherProps{
  Name string
  Width int
}

type Duck{
  Weight int
  otherProps
}

How do you instantiate a Duck in your own program? Here's the best I could come up with:

package main

import "github.com/someone/animals"

func main(){
  var duck animals.Duck
  // Can't instantiate a duck with something.Duck{Weight: 2, Name: "Henry"} because `Name` is part of the private type `otherProps`
  duck.Weight = 2
  duck.Width = 30
  duck.Name = "Henry"
}

how do you pass images (bitmaps) between android activities using bundles?

in first.java

Intent i = new Intent(this, second.class);
                    i.putExtra("uri",uri);
                    startActivity(i);

in second.java

Bundle bd = getIntent().getExtras();
        Uri uri = bd.getParcelable("uri");
        Log.e("URI", uri.toString());
        try {
            Bitmap bitmap = Media.getBitmap(this.getContentResolver(), uri);
            imageView.setImageBitmap(bitmap);

        } 
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

TortoiseGit save user authentication / credentials

For msysgit 1.8.0, download git-credential-wincred.exe from https://github.com/downloads/msysgit/git/git-credential-wincred.zip and put into C:\Program Files\Git\libexec\git-core

For msysgit 1.8.1 and later, the exe is built-in.

in git config, add the following settings.

[credential] helper = wincred

Check if object is a jQuery object

return el instanceof jQuery ? el.size() > 0 : (el && el.tagName);

generate random double numbers in c++

This solution requires C++11 (or TR1).

#include <random>

int main()
{
   double lower_bound = 0;
   double upper_bound = 10000;
   std::uniform_real_distribution<double> unif(lower_bound,upper_bound);
   std::default_random_engine re;
   double a_random_double = unif(re);

   return 0;
}

For more details see John D. Cook's "Random number generation using C++ TR1".

See also Stroustrup's "Random number generation".

"npm config set registry https://registry.npmjs.org/" is not working in windows bat file

You can change using the .bat make sure you run the call command prior, hopefully this helps anyone in future making similar .bat commands

call npm config set registry https://registry.npmjs.org/

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

go to your build.gradle file in project level you will find the following lines highlighted

dependencies {
    classpath 'com.android.tools.build:gradle:3.1.4'  //place your cursor over here 
    //and hit alt+enter and it will show you the appropriate version to select


    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

    classpath 'com.google.gms:google-services:4.0.2' //the same as previously
}

React ignores 'for' attribute of the label element

The for attribute is called htmlFor for consistency with the DOM property API. If you're using the development build of React, you should have seen a warning in your console about this.

How to force the browser to reload cached CSS and JavaScript files

This solution is written in PHP, but it should be easily adapted to other languages.

The original .htaccess regex can cause problems with files like json-1.3.js. The solution is to only rewrite if there are exactly 10 digits at the end. (Because 10 digits covers all timestamps from 9/9/2001 to 11/20/2286.)

First, we use the following rewrite rule in .htaccess:

RewriteEngine on
RewriteRule ^(.*)\.[\d]{10}\.(css|js)$ $1.$2 [L]

Now, we write the following PHP function:

/**
 *  Given a file, i.e. /css/base.css, replaces it with a string containing the
 *  file's mtime, i.e. /css/base.1221534296.css.
 *
 *  @param $file  The file to be loaded.  Must be an absolute path (i.e.
 *                starting with slash).
 */
function auto_version($file)
{
  if(strpos($file, '/') !== 0 || !file_exists($_SERVER['DOCUMENT_ROOT'] . $file))
    return $file;

  $mtime = filemtime($_SERVER['DOCUMENT_ROOT'] . $file);
  return preg_replace('{\\.([^./]+)$}', ".$mtime.\$1", $file);
}

Now, wherever you include your CSS, change it from this:

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

To this:

<link rel="stylesheet" href="<?php echo auto_version('/css/base.css'); ?>" type="text/css" />

This way, you never have to modify the link tag again, and the user will always see the latest CSS. The browser will be able to cache the CSS file, but when you make any changes to your CSS the browser will see this as a new URL, so it won't use the cached copy.

This can also work with images, favicons, and JavaScript. Basically anything that is not dynamically generated.

Accessing MP3 metadata with Python

I would suggest mp3-tagger. Best thing about this is it is distributed under MIT License and supports all the required attributes.

- artist;
- album;
- song;
- track;
- comment;
- year;
- genre;
- band;
- composer;
- copyright;
- url;
- publisher.

Example:

from mp3_tagger import MP3File

# Create MP3File instance.
mp3 = MP3File('File_Name.mp3')

# Get all tags.
tags = mp3.get_tags()
print(tags)

It supports set, get, update and delete attributes of mp3 files.

R: "Unary operator error" from multiline ggplot2 command

It looks like you might have inserted an extra + at the beginning of each line, which R is interpreting as a unary operator (like - interpreted as negation, rather than subtraction). I think what will work is

ggplot(combined.data, aes(x = region, y = expression, fill = species)) +
    geom_boxplot() +
    scale_fill_manual(values = c("yellow", "orange")) + 
    ggtitle("Expression comparisons for ACTB") + 
    theme(axis.text.x = element_text(angle=90, face="bold", colour="black"))

Perhaps you copy and pasted from the output of an R console? The console uses + at the start of the line when the input is incomplete.

Data was not saved: object references an unsaved transient instance - save the transient instance before flushing

You can't save things to Hibernate until you've also told Hibernate about all the other objects referenced by this newly saved object. So in this case, you're telling Hibernate about a User, but haven't told it about the Country.

You can solve problems like this in two ways.

Manually

Call session.save(country) before you save the User.

CascadeType

You can specify to Hibernate that this relationship should propagate some operations using CascadeType. In this case CascadeType.PERSIST would do the job, as would CascadeType.ALL.

Referencing existing countries

Based on your response to @zerocool though, you have a second problem, which is that when you have two User objects with the same Country, you are not making sure it's the same Country. To do this, you have to get the appropriate Country from the database, set it on the new user, and then save the User. Then, both of your User objects will refer to the same Country, not just two Country instances that happen to have the same name. Review the Criteria API as one way of fetching existing instances.

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

I did everything and didn't worked. I uninstalled Xcode 10 and installed Xcode 9.4 then it worked out of the box !

How to specify 64 bit integers in c

Append ll suffix to hex digits for 64-bit (long long int), or ull suffix for unsigned 64-bit (unsigned long long)

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

Upgrade python without breaking yum

I recommend, instead, updating the path in the associated script(s) (such as /usr/bin/yum) to point at your previous Python as the interpreter.

Ideally, you want to upgrade yum and its associated scripts so that they are supported by the default Python installed.

If that is not possible, the above is entirely workable and tested.

Change:

#!/usr/bin/python

to whatever the path is of your old version until you can make the above yum improvement.

Cases where you couldn't do the above are if you have an isolated machine, don't have the time to upgrade rpm manually or can't connect temporarily or permanently to a standard yum repository.

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

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 0);

How to add directory to classpath in an application run profile in IntelliJ IDEA?

I am using Idea 8. in your module dependancies tab (in the project structure dialog). Add a "Module Library". There you can select a Jar Directory to add. Then make sure the run profile is using the Classpath and JDK of the correct module when it runs (this is in the run config dialog.

What does %5B and %5D in POST requests stand for?

Well it's the usual url encoding

So they stand for [, respectively ]

How to Convert string "07:35" (HH:MM) to TimeSpan

You can convert the time using the following code.

TimeSpan _time = TimeSpan.Parse("07:35");

But if you want to get the current time of the day you can use the following code:

TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;

The result will be:

03:54:35.7763461

With a object cantain the Hours, Minutes, Seconds, Ticks and etc.

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

What is base 64 encoding used for?

From http://en.wikipedia.org/wiki/Base64

The term Base64 refers to a specific MIME content transfer encoding. It is also used as a generic term for any similar encoding scheme that encodes binary data by treating it numerically and translating it into a base 64 representation. The particular choice of base is due to the history of character set encoding: one can choose a set of 64 characters that is both part of the subset common to most encodings, and also printable. This combination leaves the data unlikely to be modified in transit through systems, such as email, which were traditionally not 8-bit clean.

Base64 can be used in a variety of contexts:

  • Evolution and Thunderbird use Base64 to obfuscate e-mail passwords[1]
  • Base64 can be used to transmit and store text that might otherwise cause delimiter collision
  • Base64 is often used as a quick but insecure shortcut to obscure secrets without incurring the overhead of cryptographic key management

  • Spammers use Base64 to evade basic anti-spamming tools, which often do not decode Base64 and therefore cannot detect keywords in encoded messages.

  • Base64 is used to encode character strings in LDIF files
  • Base64 is sometimes used to embed binary data in an XML file, using a syntax similar to ...... e.g. Firefox's bookmarks.html.
  • Base64 is also used when communicating with government Fiscal Signature printing devices (usually, over serial or parallel ports) to minimize the delay when transferring receipt characters for signing.
  • Base64 is used to encode binary files such as images within scripts, to avoid depending on external files.
  • Can be used to embed raw image data into a CSS property such as background-image.

JSONDecodeError: Expecting value: line 1 column 1

If you look at the output you receive from print() and also in your Traceback, you'll see the value you get back is not a string, it's a bytes object (prefixed by b):

b'{\n  "note":"This file    .....

If you fetch the URL using a tool such as curl -v, you will see that the content type is

Content-Type: application/json; charset=utf-8

So it's JSON, encoded as UTF-8, and Python is considering it a byte stream, not a simple string. In order to parse this, you need to convert it into a string first.

Change the last line of code to this:

info = json.loads(js.decode("utf-8"))

Viewing all `git diffs` with vimdiff

You can try git difftool, it is designed to do this stuff.

First, you need to config diff tool to vimdiff

git config diff.tool vimdiff

Then, when you want to diff, just use git difftool instead of git diff. It will work as you expect.

Giving UIView rounded corners

Do this programatically in obj c

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(20, 50,    200, 200)];

view.layer.backgroundColor = [UIColor whiteColor].CGColor;
view.layer.cornerRadius = 20.0;
view.layer.frame = CGRectInset(v.layer.frame, 20, 20);

[view.layer.shadowOffset = CGSizeMake(1, 0);
view.layer.shadowColor = [[UIColor blackColor] CGColor];
view.layer.shadowRadius = 5;
view.layer.shadowOpacity = .25;][1]

[self.view addSubview:view];

We Can Also do this from stoaryboard.

 layer.cornerRadius  Number  5

enter image description here

JS map return object

map rockets and add 10 to its launches:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
rockets.map((itm) => {_x000D_
    itm.launches += 10_x000D_
    return itm_x000D_
})_x000D_
console.log(rockets)
_x000D_
_x000D_
_x000D_

If you don't want to modify rockets you can do:

var plusTen = []
rockets.forEach((itm) => {
    plusTen.push({'country': itm.country, 'launches': itm.launches + 10})
})

glob exclude pattern

If the position of the character isn't important, that is for example to exclude manifests files (wherever it is found _) with glob and re - regular expression operations, you can use:

import glob
import re
for file in glob.glob('*.txt'):
    if re.match(r'.*\_.*', file):
        continue
    else:
        print(file)

Or with in a more elegant way - list comprehension

filtered = [f for f in glob.glob('*.txt') if not re.match(r'.*\_.*', f)]

for mach in filtered:
    print(mach)

Delete directory with files in it?

what's the easiest way to delete a directory with all it's files in it?

system("rm -rf ".escapeshellarg($dir));

Find where java class is loaded from

This is what we use:

public static String getClassResource(Class<?> klass) {
  return klass.getClassLoader().getResource(
     klass.getName().replace('.', '/') + ".class").toString();
}

This will work depending on the ClassLoader implementation: getClass().getProtectionDomain().getCodeSource().getLocation()

Exception: Serialization of 'Closure' is not allowed

As already stated: closures, out of the box, cannot be serialized.

However, using the __sleep(), __wakeup() magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection

This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.

How do I mock an open used in a with statement (using the Mock framework in Python)?

I might be a bit late to the game, but this worked for me when calling open in another module without having to create a new file.

test.py

import unittest
from mock import Mock, patch, mock_open
from MyObj import MyObj

class TestObj(unittest.TestCase):
    open_ = mock_open()
    with patch.object(__builtin__, "open", open_):
        ref = MyObj()
        ref.save("myfile.txt")
    assert open_.call_args_list == [call("myfile.txt", "wb")]

MyObj.py

class MyObj(object):
    def save(self, filename):
        with open(filename, "wb") as f:
            f.write("sample text")

By patching the open function inside the __builtin__ module to my mock_open(), I can mock writing to a file without creating one.

Note: If you are using a module that uses cython, or your program depends on cython in any way, you will need to import cython's __builtin__ module by including import __builtin__ at the top of your file. You will not be able to mock the universal __builtin__ if you are using cython.

How to get a path to a resource in a Java JAR file

Inside your ressources folder (java/main/resources) of your jar add your file (we assume that you have added an xml file named imports.xml), after that you inject ResourceLoader if you use spring like bellow

@Autowired
private ResourceLoader resourceLoader;

inside tour function write the bellow code in order to load file:

    Resource resource = resourceLoader.getResource("classpath:imports.xml");
    try{
        File file;
        file = resource.getFile();//will load the file
...
    }catch(IOException e){e.printStackTrace();}

Easiest way to copy a single file from host to Vagrant guest?

You can add entry in ~/.ssh/config:

Host vagrant
    User vagrant
    HostName localhost
    Port 2222
    IdentityFile /home/user_name/.vagrant.d/insecure_private_key

and the simplescp file vagrant:/path/. You can find path to identity file using the vagrant ssh-config command.

How to give a pandas/matplotlib bar graph custom colors

I found the easiest way is to use the colormap parameter in .plot() with one of the preset color gradients:

df.plot(kind='bar', stacked=True, colormap='Paired')

enter image description here

You can find a large list of preset colormaps here.

colormaps

How to set fake GPS location on IOS real device

I had a similar issue, but with no source code to run on Xcode.

So if you want to test an application on a real device with a fake location you should use a VPN application.

There are plenty in the App Store to choose from - free ones without the option to choose a specific country/city and free ones which assign you a random location or asks you to choose from a limited set of default options.

How can I change the value of the elements in a vector?

Your code works fine. When I ran it I got the output:

The values in the file input.txt are:
1
2
3
4
5
6
7
8
9
10
The sum of the values is: 55
The mean value is: 5.5

But it could still be improved.

You are iterating over the vector using indexes. This is not the "STL Way" -- you should be using iterators, to wit:

typedef vector<double> doubles;
for( doubles::const_iterator it = v.begin(), it_end = v.end(); it != it_end; ++it )
{
    total += *it;
    mean = total / v.size();
}

This is better for a number of reasons discussed here and elsewhere, but here are two main reasons:

  1. Every container provides the iterator concept. Not every container provides random-access (eg, indexed access).
  2. You can generalize your iteration code.

Point number 2 brings up another way you can improve your code. Another thing about your code that isn't very STL-ish is the use of a hand-written loop. <algorithm>s were designed for this purpose, and the best code is the code you never write. You can use a loop to compute the total and mean of the vector, through the use of an accumulator:

#include <numeric>
#include <functional>
struct my_totals : public std::binary_function<my_totals, double, my_totals>
{
    my_totals() : total_(0), count_(0) {};
    my_totals operator+(double v) const
    {
        my_totals ret = *this;
        ret.total_ += v;
        ++ret.count_;
        return ret;
    }
    double mean() const { return total_/count_; }
    double total_;
    unsigned count_;
};

...and then:

my_totals ttls = std::accumulate(v.begin(), v.end(), my_totals());
cout << "The sum of the values is: " << ttls.total_ << endl;
cout << "The mean value is: " << ttls.mean() << endl;

EDIT:

If you have the benefit of a C++0x-compliant compiler, this can be made even simpler using std::for_each (within #include <algorithm>) and a lambda expression:

double total = 0;
for_each( v.begin(), v.end(), [&total](double  v) { total += v; });
cout << "The sum of the values is: " << total << endl;
cout << "The mean value is: " << total/v.size() << endl;

Python+OpenCV: cv2.imwrite

This following code should extract face in images and save faces on disk

def detect(image):
    image_faces = []
    bitmap = cv.fromarray(image)
    faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
    if faces:
        for (x,y,w,h),n in faces:
            image_faces.append(image[y:(y+h), x:(x+w)])
            #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
    return image_faces

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        image_faces = []
        image_faces = detect(frame)
        for i, face in enumerate(image_faces):
            cv2.imwrite("face-" + str(i) + ".jpg", face)

        #cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

How and where to use ::ng-deep?

Make sure not to miss the explanation of :host-context which is directly above ::ng-deep in the angular guide : https://angular.io/guide/component-styles. I missed it up until now and wish I'd seen it sooner.

::ng-deep is often necessary when you didn't write the component and don't have access to its source, but :host-context can be a very useful option when you do.

For example I have a black <h1> header inside a component I designed, and I want the ability to change it to white when it's displayed on a dark themed background.

If I didn't have access to the source I may have to do this in the css for the parent:

.theme-dark widget-box ::ng-deep h1 { color: white; }

But instead with :host-context you can do this inside the component.

 h1 
 {
     color: black;       // default color

     :host-context(.theme-dark) &
     {
         color: white;   // color for dark-theme
     }

     // OR set an attribute 'outside' with [attr.theme]="'dark'"

     :host-context([theme='dark']) &
     {
         color: white;   // color for dark-theme
     }
 }

This will look anywhere in the component chain for .theme-dark and apply the css to the h1 if found. This is a good alternative to relying too much on ::ng-deep which while often necessary is somewhat of an anti-pattern.

In this case the & is replaced by the h1 (that's how sass/scss works) so you can define your 'normal' and themed/alternative css right next to each other which is very handy.

Be careful to get the correct number of :. For ::ng-deep there are two and for :host-context only one.

Generating PDF files with JavaScript

I've just written a library called jsPDF which generates PDFs using Javascript alone. It's still very young, and I'll be adding features and bug fixes soon. Also got a few ideas for workarounds in browsers that do not support Data URIs. It's licensed under a liberal MIT license.

I came across this question before I started writing it and thought I'd come back and let you know :)

Generate PDFs in Javascript

Example create a "Hello World" PDF file.

_x000D_
_x000D_
// Default export is a4 paper, portrait, using milimeters for units_x000D_
var doc = new jsPDF()_x000D_
_x000D_
doc.text('Hello world!', 10, 10)_x000D_
doc.save('a4.pdf')
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.debug.js"></script>
_x000D_
_x000D_
_x000D_

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

 jquery.ajax({
            url: `//your api url`
            type: "GET",
            dataType: "json",
            success: function(data) {
                jQuery.each(data, function(index, value) {
                        console.log(data);
                        `All you API data is here`
                    }
                }
            });     

How to get javax.comm API?

Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.

if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip

How to prevent colliders from passing through each other?

Try setting the models to environment and static. That fix my issue.

Global constants file in Swift

To have global constants in my apps, this is what I do in a separate Swift file:

import Foundation

struct Config {
    static let baseURL = "https://api.com"

    static APIKeys {
        static let token = "token"
        static let user = "user"
    }

    struct Notifications {
        static let awareUser = "aware_user"
    }
}

It's easy to use, and to call everywhere like this:

print(Config.Notifications.awareUser)

How to set lifetime of session

Set following php parameters to same value in seconds:

session.cookie_lifetime
session.gc_maxlifetime

in php.ini, .htaccess or for example with

ini_set('session.cookie_lifetime', 86400);
ini_set('session.gc_maxlifetime', 86400);

for a day.

Links:

http://www.php.net/manual/en/session.configuration.php

http://www.php.net/manual/en/function.ini-set.php

What is __pycache__?

The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__ directory.

When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__ folder.

When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py with the B option.

LDAP root query syntax to search more than one specific OU

The answer is NO you can't. Why?

Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:

  1. The node where the search should begin, which is a Distinguish Name (DN)
  2. The attributes you want to be brought back
  3. The depth of the search (base, one-level, subtree)
  4. The filter

You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value.

So the filter you give does not mean anything.

On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.

As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.

It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:

(&(objectCategory=person)(|(ou=staff)(ou=vendors)))

git-diff to ignore ^M

Try git diff --ignore-space-at-eol, or git diff --ignore-space-change, or git diff --ignore-all-space.

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

For those of you that have Postgres 9.5 or higher, the new ON CONFLICT DO NOTHING syntax should work:

INSERT INTO target_table (field_one, field_two, field_three ) 
SELECT field_one, field_two, field_three
FROM source_table
ON CONFLICT (field_one) DO NOTHING;

For those of us who have an earlier version, this right join will work instead:

INSERT INTO target_table (field_one, field_two, field_three )
SELECT source_table.field_one, source_table.field_two, source_table.field_three
FROM source_table 
LEFT JOIN target_table ON source_table.field_one = target_table.field_one
WHERE target_table.field_one IS NULL;

Why does modern Perl avoid UTF-8 by default?

I think you misunderstand Unicode and its relationship to Perl. No matter which way you store data, Unicode, ISO-8859-1, or many other things, your program has to know how to interpret the bytes it gets as input (decoding) and how to represent the information it wants to output (encoding). Get that interpretation wrong and you garble the data. There isn't some magic default setup inside your program that's going to tell the stuff outside your program how to act.

You think it's hard, most likely, because you are used to everything being ASCII. Everything you should have been thinking about was simply ignored by the programming language and all of the things it had to interact with. If everything used nothing but UTF-8 and you had no choice, then UTF-8 would be just as easy. But not everything does use UTF-8. For instance, you don't want your input handle to think that it's getting UTF-8 octets unless it actually is, and you don't want your output handles to be UTF-8 if the thing reading from them can't handle UTF-8. Perl has no way to know those things. That's why you are the programmer.

I don't think Unicode in Perl 5 is too complicated. I think it's scary and people avoid it. There's a difference. To that end, I've put Unicode in Learning Perl, 6th Edition, and there's a lot of Unicode stuff in Effective Perl Programming. You have to spend the time to learn and understand Unicode and how it works. You're not going to be able to use it effectively otherwise.

HTML5 image icon to input placeholder

Adding to Tim's answer:

  #search:placeholder-shown {
     // show background image, I like svg 
     // when using svg, do not use HEX for colour; you can use rbg/a instead
     // also notice the single quotes
     background-image url('data:image/svg+xml; utf8, <svg>... <g fill="grey"...</svg>')
     // other background props
   }

   #search:not(:placeholder-shown) { background-image: none;}

Find closing HTML tag in Sublime Text

I think, you may want to try another approach with folding enabled.

In both ST2 and ST3, if you enable folding in User settings:

{
    ...(previous item)
    "fold_buttons": true,
    ...(next item, thus the comma)
}

You can see the triangle folding button at the left side of the line where the start tag is. Click it to expand/fold. If you want to copy, fold and copy, you get all block.

enter image description here

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

How do I encode URI parameter values?

It seems that CharEscapers from Google GData-java-client has what you want. It has uriPathEscaper method, uriQueryStringEscaper, and generic uriEscaper. (All return Escaper object which does actual escaping). Apache License.

Add new attribute (element) to JSON object using JavaScript

You can also dynamically add attributes with variables directly in an object literal.

const amountAttribute = 'amount';
const foo = {
                [amountAttribute]: 1
            };
foo[amountAttribute + "__more"] = 2;

Results in:

{
    amount: 1, 
    amount__more: 2
}

Why can I ping a server but not connect via SSH?

ping (ICMP protocol) and ssh are two different protocols.

  1. It could be that ssh service is not running or not installed

  2. firewall restriction (local to server like iptables or even sshd config lock down ) or (external firewall that protects incomming traffic to network hosting 111.111.111.111)

First check is to see if ssh port is up

nc -v -w 1 111.111.111.111 -z 22

if it succeeds then ssh should communicate if not then it will never work until restriction is lifted or ssh is started

How to show "Done" button on iPhone number pad

A much easier solution

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    [super touchesBegan:touches withEvent:event];

    [textViewInstance1 resignFirstResponder];
    [textViewInstance2 resignFirstResponder];
    [textField resignFirstResponder];
}

How can I divide two integers to get a double?

var result = decimal.ToDouble(decimal.Divide(5, 2));

Compile to stand alone exe for C# app in Visual Studio 2010

Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.

Determine whether a key is present in a dictionary

My answer is "neither one".

I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.

This is usually done with enclosing the code in a try...except clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).

Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".

As a trivial example consider:

if 'name' in dct:
    value = dct['name'] * 3
else:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

vs

try:
    value = dct['name'] * 3
except KeyError:
    logerror('"%s" not found in dictionary, using default' % name)
    value = 42

Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).

Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict: is better for the reasons stated in the other answers.

If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).

Correct way to synchronize ArrayList in java

You're synchronizing twice, which is pointless and possibly slows down the code: changes while iterating over the list need a synchronnization over the entire operation, which you are doing with synchronized (in_queue_list) Using Collections.synchronizedList() is superfluous in that case (it creates a wrapper that synchronizes individual operations).

However, since you are emptying the list completely, the iterated removal of the first element is the worst possible way to do it, sice for each element all following elements have to be copied, making this an O(n^2) operation - horribly slow for larger lists.

Instead, simply call clear() - no iteration needed.

Edit: If you need the single-method synchronization of Collections.synchronizedList() later on, then this is the correct way:

List<Record> in_queue_list = Collections.synchronizedList(in_queue);
in_queue_list.clear(); // synchronized implicitly, 

But in many cases, the single-method synchronization is insufficient (e.g. for all iteration, or when you get a value, do computations based on it, and replace it with the result). In that case, you have to use manual synchronization anyway, so Collections.synchronizedList() is just useless additional overhead.

SQL Server datetime LIKE select?

You can also use convert to make the date searchable using LIKE. For example,

select convert(VARCHAR(40),create_date,121) , * from sys.objects where     convert(VARCHAR(40),create_date,121) LIKE '%17:34%'

How do I access ViewBag from JS

You can achieve the solution, by doing this:

JavaScript:

var myValue = document.getElementById("@(ViewBag.CC)").value;

or if you want to use jQuery, then:

jQuery

var myValue = $('#' + '@(ViewBag.CC)').val();

Python Image Library fails with message "decoder JPEG not available" - PIL

For those on Mac OS Mountain Lion, I followed the anwser of zeantsoi, but it doesn't work.

I finally ended up with the solution of this post: http://appelfreelance.com/2010/06/libjpeg-pil-snow-leopard-python2-6-_jpeg_resync_to_restart/

Now, I'm happily running my script for jpeg !

input type=file show only button

I just styled an input file with width: 85px, and the text field disappeared at all

Convert String to int array in java

In tight loops or on mobile devices it's not a good idea to generate lots of garbage through short-lived String objects, especially when parsing long arrays.

The method in my answer parses data without generating garbage, but it does not deal with invalid data gracefully and cannot parse negative numbers. If your data comes from untrusted source, you should be doing some additional validation or use one of the alternatives provided in other answers.

public static void readToArray(String line, int[] resultArray) {
    int index = 0;
    int number = 0;

    for (int i = 0, n = line.length(); i < n; i++) {
        char c = line.charAt(i);
        if (c == ',') {
            resultArray[index] = number;
            index++;
            number = 0;
        }
        else if (Character.isDigit(c)) {
            int digit = Character.getNumericValue(c);
            number = number * 10 + digit;
        }
    }

    if (index < resultArray.length) {
        resultArray[index] = number;
    }
}

public static int[] toArray(String line) {
    int[] result = new int[countOccurrences(line, ',') + 1];
    readToArray(line, result);
    return result;
}

public static int countOccurrences(String haystack, char needle) {
    int count = 0;
    for (int i=0; i < haystack.length(); i++) {
        if (haystack.charAt(i) == needle) {
            count++;
        }
    }
    return count;
}

countOccurrences implementation was shamelessly stolen from John Skeet

how to use "AND", "OR" for RewriteCond on Apache?

This is an interesting question and since it isn't explained very explicitly in the documentation I'll answer this by going through the sourcecode of mod_rewrite; demonstrating a big benefit of open-source.

In the top section you'll quickly spot the defines used to name these flags:

#define CONDFLAG_NONE               1<<0
#define CONDFLAG_NOCASE             1<<1
#define CONDFLAG_NOTMATCH           1<<2
#define CONDFLAG_ORNEXT             1<<3
#define CONDFLAG_NOVARY             1<<4

and searching for CONDFLAG_ORNEXT confirms that it is used based on the existence of the [OR] flag:

else if (   strcasecmp(key, "ornext") == 0
         || strcasecmp(key, "OR") == 0    ) {
    cfg->flags |= CONDFLAG_ORNEXT;
}

The next occurrence of the flag is the actual implementation where you'll find the loop that goes through all the RewriteConditions a RewriteRule has, and what it basically does is (stripped, comments added for clarity):

# loop through all Conditions that precede this Rule
for (i = 0; i < rewriteconds->nelts; ++i) {
    rewritecond_entry *c = &conds[i];

    # execute the current Condition, see if it matches
    rc = apply_rewrite_cond(c, ctx);

    # does this Condition have an 'OR' flag?
    if (c->flags & CONDFLAG_ORNEXT) {
        if (!rc) {
            /* One condition is false, but another can be still true. */
            continue;
        }
        else {
            /* skip the rest of the chained OR conditions */
            while (   i < rewriteconds->nelts
                   && c->flags & CONDFLAG_ORNEXT) {
                c = &conds[++i];
            }
        }
    }
    else if (!rc) {
        return 0;
    }
}

You should be able to interpret this; it means that OR has a higher precedence, and your example indeed leads to if ( (A OR B) AND (C OR D) ). If you would, for example, have these Conditions:

RewriteCond A [or]
RewriteCond B [or]
RewriteCond C
RewriteCond D

it would be interpreted as if ( (A OR B OR C) and D ).

C# generic list <T> how to get the type of T?

Type type = pi.PropertyType;
if(type.IsGenericType && type.GetGenericTypeDefinition()
        == typeof(List<>))
{
    Type itemType = type.GetGenericArguments()[0]; // use this...
}

More generally, to support any IList<T>, you need to check the interfaces:

foreach (Type interfaceType in type.GetInterfaces())
{
    if (interfaceType.IsGenericType &&
        interfaceType.GetGenericTypeDefinition()
        == typeof(IList<>))
    {
        Type itemType = type.GetGenericArguments()[0];
        // do something...
        break;
    }
}

c++ exception : throwing std::string

Yes. std::exception is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?

boost has an excellent document on good style for exceptions and error handling. It's worth a read.

Hide text using css

h1{
   background:url("../images/logo.png") no-repeat;
   height:180px;
   width:200px;
   display:inline-block;
   font-size:0px !important;
   text-intent:-9999999px !important;
   color:transparent !important;
 }

How to sort in-place using the merge sort algorithm?

Just for reference, here is a nice implementation of a stable in-place merge sort. Complicated, but not too bad.

I ended up implementing both a stable in-place merge sort and a stable in-place quicksort in Java. Please note the complexity is O(n (log n)^2)

How to check if a file contains a specific string using Bash

I done this, seems to work fine

if grep $SearchTerm $FileToSearch; then
   echo "$SearchTerm found OK"
else
   echo "$SearchTerm not found"
fi

SharePoint : How can I programmatically add items to a custom list instance

I think these both blog post should help you solving your problem.

http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/

Short walk through:

  1. Get a instance of the list you want to add the item to.
  2. Add a new item to the list:

    SPListItem newItem = list.AddItem();
    
  3. To bind you new item to a content type you have to set the content type id for the new item:

    newItem["ContentTypeId"] = <Id of the content type>;
    
  4. Set the fields specified within your content type.

  5. Commit your changes:

    newItem.Update();
    

Typescript sleep

Or rather than to declare a function, simply:

setTimeout(() => {
    console.log('hello');
}, 1000);

What does "<html xmlns="http://www.w3.org/1999/xhtml">" do?

Its an XML namespace. It is required when you use XHTML 1.0 or 1.1 doctypes or application/xhtml+xml mimetypes.

You should be using HTML5 doctype, then you don't need it for text/html. Better start from template like this :

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8 />
        <title>domcument title</title>
        <link rel="stylesheet" href="/stylesheet.css" type="text/css" />
    </head>
    <body>
            <!-- your html content -->
            <script src="/script.js"></script>
    </body>
</html>



When you have put your Doctype straight - do and validate you html and your css .
That usually will sove you layout issues.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

allow from all will not work along with Require local. Instead, try Require ip xxx.xxx.xxx.xx

For Example:

# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Require local
    Require ip 10.0.0.1
    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

How to convert a time string to seconds?

It looks like you're willing to strip fractions of a second... the problem is you can't use '00' as the hour with %I

>>> time.strptime('00:00:00,000'.split(',')[0],'%H:%M:%S')
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)
>>>

How do I clear this setInterval inside a function?

Simplest way I could think of: add a class.

Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.

_x000D_
_x000D_
var i = 0;_x000D_
this.setInterval(function() {_x000D_
  if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
    console.log('Counting...');_x000D_
    $('#counter').html(i++); //just for explaining and showing_x000D_
  } else {_x000D_
    console.log('Stopped counting');_x000D_
  }_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
    $(this).addClass('pauseInterval');_x000D_
  },function() { //mouse leave_x000D_
    $(this).removeClass('pauseInterval');_x000D_
  }_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
  $('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
  background-color: #eee;_x000D_
  font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
  width: 50%;_x000D_
  background: #ddd;_x000D_
  border: 2px solid #009afd;_x000D_
  border-radius: 5px;_x000D_
  padding: 5px;_x000D_
  text-align: center;_x000D_
  transition: .3s;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
  border-color: red;  _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter">&nbsp;</p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
_x000D_
_x000D_

jquery to loop through table rows and cells, where checkob is checked, concatenate

Try this:

function createcodes() {

    $('.authors-list tr').each(function () {
        //processing this row
        //how to process each cell(table td) where there is checkbox
        $(this).find('td input:checked').each(function () {

             // it is checked, your code here...
        });
    });
}

How to copy JavaScript object to new variable NOT by reference?

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

Documentation

How to use BigInteger?

Actually you can use,

BigInteger sum= new BigInteger("12345");

for creating object for BigInteger class.But the problem here is,you cannot give a variable in the double quotes.So we have to use the valueOf() method and we have to store the answer in that sum again.So we will write,

sum= sum.add(BigInteger.valueOf(i));

Pretty git branch graphs

Based on a Graphviz script I found in an answer to a related question, I've hacked up a ruby script that creates a summary view of a git repository. It elides all linear history and just shows "interesting" commits, i.e. those with multiple parents, multiple children, or pointed to by a branch or tag. Here's a snippet of the graph it generates for jquery:

jquery sample

git-big-picture and BranchMaster are similar tools that try to show only the high-level structure of a graph, by only displaying how tags, branches, merges, etc. are related.

This question has some more options.

How to $http Synchronous call with AngularJS

I recently ran into a situation where I wanted to make to $http calls triggered by a page reload. The solution I went with:

  1. Encapsulate the two calls into functions
  2. Pass the second $http call as a callback into the second function
  3. Call the second function in apon .success

LINQ query to select top five

The solution:

var list = (from t in ctn.Items
           where t.DeliverySelection == true && t.Delivery.SentForDelivery == null
           orderby t.Delivery.SubmissionDate
           select t).Take(5);

How to remove item from a python list in a loop?

The already-mentioned list comprehension approach is probably your best bet. But if you absolutely want to do it in-place (for example if x is really large), here's one way:

x = ["ok", "jj", "uy", "poooo", "fren"]
index=0
while index < len(x):
    if len(x[index]) != 2:
        print "length of %s is: %s" %(x[index], len(x[index]))
        del x[index]
        continue
    index+=1

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

I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.

This is cut from wdCalendar where I modified this procedure:

 function BuildDaysAndWeekView(startday, l, events, config)
   ....
        var scrollpos = $("#dvtec").scrollTop();
        gridcontainer.html(html.join(""));
        setTimeout(function() {
            $("#dvtec").scrollTop(scrollpos);
        }, 25);
   ....

Without the delay, it simply did not work.

How to sort a list of lists by a specific index of the inner list?

Make sure that you do not have any null or NaN values in the list you want to sort. If there are NaN values, then your sort will be off, impacting the sorting of the non-null values.

Check out Python: sort function breaks in the presence of nan

Technically what is the main difference between Oracle JDK and OpenJDK?

Technical differences are a consequence of the goal of each one (OpenJDK is meant to be the reference implementation, open to the community, while Oracle is meant to be a commercial one)

They both have "almost" the same code of the classes in the Java API; but the code for the virtual machine itself is actually different, and when it comes to libraries, OpenJDK tends to use open libraries while Oracle tends to use closed ones; for instance, the font library.

How to run Java program in command prompt

javac only compiles the code. You need to use java command to run the code. The error is because your classpath doesn't contain the class Subclass iwhen you tried to compile it. you need to add them with the -cp variable in javac command

java -cp classpath-entries mainjava arg1 arg2 should run your code with 2 arguments