Programs & Examples On #Uclibc

uclibc is a version of the C standard library for embedded systems

Unsupported operation :not writeable python

You open the variable "file" as a read only then attempt to write to it:

file = open('ValidEmails.txt','r')

Instead, use the 'w' flag.

file = open('ValidEmails.txt','w')
...
file.write(email)

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

For those it might help, I use this list as a reference to define my content-type when I have to deal with images on my app.

It says that jpg extension can be declared with Content-type : image/jpeg

There isn't any image/jpg attribute for content-type.

How to check for empty value in Javascript?

Comment as an answer:

if (timetime[0].value)

This works because any variable in JS can be evaluated as a boolean, so this will generally catch things that are empty, null, or undefined.

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

Sending emails in Node.js?

Mature, simple to use and has lots of features if simple isn't enought: Nodemailer: https://github.com/andris9/nodemailer (note correct url!)

Django download a file

When you upload a file using FileField, the file will have a URL that you can use to point to the file and use HTML download attribute to download that file you can simply do this.

models.py

The model.py looks like this

class CsvFile(models.Model):
    csv_file = models.FileField(upload_to='documents')

views.py

#csv upload

class CsvUploadView(generic.CreateView):

   model = CsvFile
   fields = ['csv_file']
   template_name = 'upload.html'

#csv download

class CsvDownloadView(generic.ListView):

    model = CsvFile
    fields = ['csv_file']
    template_name = 'download.html'

Then in your templates.

#Upload template

upload.html

<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
    {% csrf_token %}
    {{ form.media }}
    {{ form.as_p }}
    <button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>

#download template

download.html

  {% for document in object_list %}

     <a href="{{ document.csv_file.url }}" download  class="btn btn-dark float-right">Download</a>

  {% endfor %}

I did not use forms, just rendered model but either way, FileField is there and it will work the same.

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.

Here is a complete example from your data that shows a bar of for each required value at each date:

import pylab as pl
import datetime

data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""

values = []
dates = []

for line in data.split("\n"):
    x, y = line.split()
    values.append(int(x))
    dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()

You need to parse the date with strptime and set the x-axis to use dates (as described in this answer).

If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:

fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)

EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks (and move them by half the bar width):

fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)

how to set the background color of the whole page in css

The problem is that the body of the page isn't actually visible. The DIVs under have width of 100% and have background colors themselves that override the body CSS.

To Fix the no-man's land, this might work. It's not elegant, but works.

#doc3 {
    margin: auto 10px;
    width: auto;
    height: 2000px;
    background-color: yellow;
}

How to decode a QR-code image in (preferably pure) Python?

For Windows using ZBar

Pre-requisites:

To decode:

from PIL import Image
from pyzbar import pyzbar

img = Image.open('My-Image.jpg')
output = pyzbar.decode(img)
print(output)

Alternatively, you can also try using ZBarLight by setting it up as mentioned here:
https://pypi.org/project/zbarlight/

How to loop through all the properties of a class?

Note that if the object you are talking about has a custom property model (such as DataRowView etc for DataTable), then you need to use TypeDescriptor; the good news is that this still works fine for regular classes (and can even be much quicker than reflection):

foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj)) {
    Console.WriteLine("{0} = {1}", prop.Name, prop.GetValue(obj));
}

This also provides easy access to things like TypeConverter for formatting:

    string fmt = prop.Converter.ConvertToString(prop.GetValue(obj));

Unfortunately Launcher3 has stopped working error in android studio?

May 2017; I had the same issue, could not even get to apps as it just cycled between starting and stopping. Went into avd settings, edited the multi core (unticked the box) and set graphics to software Gles. It appears to have fixed the issue

What's the easy way to auto create non existing dir in ansible

you can create the folder using the following depending on your ansible version.

Latest version 2<

- name: Create Folder
  file: 
   path: "{{project_root}}/conf"
   recurse: yes
   state: directory

Older version:

- name: Create Folder
  file: 
      path="{{project_root}}/conf"
      recurse: yes
      state=directory

Refer - http://docs.ansible.com/ansible/latest/file_module.html

Angular 4 - Select default value in dropdown [Reactive Forms]

Try like this :

component.html

<form [formGroup]="countryForm">
    <select id="country" formControlName="country">
        <option *ngFor="let c of countries" [ngValue]="c">{{ c }}</option>
    </select>
</form>

component.ts

import { FormControl, FormGroup, Validators } from '@angular/forms';

export class Component {

    countries: string[] = ['USA', 'UK', 'Canada'];
    default: string = 'UK';

    countryForm: FormGroup;

    constructor() {
        this.countryForm = new FormGroup({
            country: new FormControl(null);
        });
        this.countryForm.controls['country'].setValue(this.default, {onlySelf: true});
    }
}

Pandas How to filter a Series

From pandas version 0.18+ filtering a series can also be done as below

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

pd.Series(test).where(lambda x : x!=1).dropna()

Checkout: http://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements

Discard all and get clean copy of latest revision?

If you're looking for a method that's easy, then you might want to try this.

I for myself can hardly remember commandlines for all of my tools, so I tend to do it using the UI:


1. First, select "commit"

Commit

2. Then, display ignored files. If you have uncommitted changes, hide them.

Show ignored files

3. Now, select all of them and click "Delete Unversioned".

Delete them

Done. It's a procedure that is far easier to remember than commandline stuff.

How to fix corrupt HDFS FIles

You can use

  hdfs fsck /

to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with

  hdfs fsck / | egrep -v '^\.+$' | grep -v eplica

which ignores lines with nothing but dots and lines talking about replication.

Once you find a file that is corrupt

  hdfs fsck /path/to/corrupt/file -locations -blocks -files

Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.

You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.

Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.

Once you determine what happened and you cannot recover any more blocks, just use the

  hdfs fs -rm /path/to/file/with/permanently/missing/blocks

command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.

JavaScript associative array to JSON

Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).

If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:

> AssocArray.length
0

What is often referred to as "associative array" is actually just an object in JS:

var AssocArray = {};  // <- initialize an object, not an array
AssocArray["a"] = "The letter A"

console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"

Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].

How do I declare an array with a custom class?

You have to provide a default constructor. While you're at it, fix your other constructor, too:

class Name
{
public:
  Name() { }
  Name(string const & f, string const & l) : first(f), last(l) { }
  //...
};

Alternatively, you have to provide the initializers:

Name arr[3] { { "John", "Doe" }, { "Jane", "Smith" }, { "", "" } };

The latter is conceptually preferable, because there's no reason that your class should have a notion of a "default" state. In that case, you simply have to provide an appropriate initializer for every element of the array.

Objects in C++ can never be in an ill-defined state; if you think about this, everything should become very clear.


An alternative is to use a dynamic container, though this is different from what you asked for:

std::vector<Name> arr;
arr.reserve(3);  // morally "an uninitialized array", though it really isn't

arr.emplace_back("John", "Doe");
arr.emplace_back("Jane", "Smith");
arr.emplace_back("", "");

std::vector<Name> brr { { "ab", "cd" }, { "de", "fg" } }; // yet another way

How do I correctly use "Not Equal" in MS Access?

Like this

SELECT DISTINCT Table1.Column1
FROM Table1
WHERE NOT EXISTS( SELECT * FROM Table2
    WHERE Table1.Column1 = Table2.Column1  )

You want NOT EXISTS, not "Not Equal"


By the way, you rarely want to write a FROM clause like this:

FROM Table1, Table2

as this means "FROM all combinations of every row in Table1 with every row in Table2..." Usually that's a lot more result rows than you ever want to see. And in the rare case that you really do want to do that, the more accepted syntax is:

FROM Table1 CROSS JOIN Table2

How to get IntPtr from byte[] in C#

Here's a twist on @user65157's answer (+1 for that, BTW):

I created an IDisposable wrapper for the pinned object:

class AutoPinner : IDisposable
{
   GCHandle _pinnedArray;
   public AutoPinner(Object obj)
   {
      _pinnedArray = GCHandle.Alloc(obj, GCHandleType.Pinned);
   }
   public static implicit operator IntPtr(AutoPinner ap)
   {
      return ap._pinnedArray.AddrOfPinnedObject(); 
   }
   public void Dispose()
   {
      _pinnedArray.Free();
   }
}

then use it like thusly:

using (AutoPinner ap = new AutoPinner(MyManagedObject))
{
   UnmanagedIntPtr = ap;  // Use the operator to retrieve the IntPtr
   //do your stuff
}

I found this to be a nice way of not forgetting to call Free() :)

How do I declare a namespace in JavaScript?

I use this approach:

var myNamespace = {}
myNamespace._construct = function()
{
    var staticVariable = "This is available to all functions created here"

    function MyClass()
    {
       // Depending on the class, we may build all the classes here
       this.publicMethod = function()
       {
          //Do stuff
       }
    }

    // Alternatively, we may use a prototype.
    MyClass.prototype.altPublicMethod = function()
    {
        //Do stuff
    }

    function privateStuff()
    {
    }

    function publicStuff()
    {
       // Code that may call other public and private functions
    }

    // List of things to place publically
    this.publicStuff = publicStuff
    this.MyClass = MyClass
}
myNamespace._construct()

// The following may or may not be in another file
myNamespace.subName = {}
myNamespace.subName._construct = function()
{
   // Build namespace
}
myNamespace.subName._construct()

External code can then be:

var myClass = new myNamespace.MyClass();
var myOtherClass = new myNamepace.subName.SomeOtherClass();
myNamespace.subName.publicOtherStuff(someParameter);

how to modify an existing check constraint?

NO, you can't do it other way than so.

jQuery append text inside of an existing paragraph tag

I have just discovered a way to append text and its working fine at least.

 var text = 'Put any text here';
 $('#text').append(text);

You can change text according to your need.

Hope this helps.

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

My issue was I was performing the segue in UIApplicationDelegate's didFinishLaunchingWithOptions method before I called makeKeyAndVisible() on the window.

Display a loading bar before the entire page is loaded

Use a div #overlay with your loading info / .gif that will cover all your page:

<div id="overlay">
     <img src="loading.gif" alt="Loading" />
     Loading...
</div>

jQuery:

$(window).load(function(){
   // PAGE IS FULLY LOADED  
   // FADE OUT YOUR OVERLAYING DIV
   $('#overlay').fadeOut();
});

Here's an example with a Loading bar:

jsBin demo

  <div id="overlay">
    <div id="progstat"></div>
    <div id="progress"></div>
  </div>

  <div id="container">
    <img src="http://placehold.it/3000x3000/cf5">
  </div>

CSS:

*{margin:0;}
body{ font: 200 16px/1 sans-serif; }
img{ width:32.2%; }

#overlay{
  position:fixed;
  z-index:99999;
  top:0;
  left:0;
  bottom:0;
  right:0;
  background:rgba(0,0,0,0.9);
  transition: 1s 0.4s;
}
#progress{
  height:1px;
  background:#fff;
  position:absolute;
  width:0;                /* will be increased by JS */
  top:50%;
}
#progstat{
  font-size:0.7em;
  letter-spacing: 3px;
  position:absolute;
  top:50%;
  margin-top:-40px;
  width:100%;
  text-align:center;
  color:#fff;
}

JavaScript:

;(function(){
  function id(v){ return document.getElementById(v); }
  function loadbar() {
    var ovrl = id("overlay"),
        prog = id("progress"),
        stat = id("progstat"),
        img = document.images,
        c = 0,
        tot = img.length;
    if(tot == 0) return doneLoading();

    function imgLoaded(){
      c += 1;
      var perc = ((100/tot*c) << 0) +"%";
      prog.style.width = perc;
      stat.innerHTML = "Loading "+ perc;
      if(c===tot) return doneLoading();
    }
    function doneLoading(){
      ovrl.style.opacity = 0;
      setTimeout(function(){ 
        ovrl.style.display = "none";
      }, 1200);
    }
    for(var i=0; i<tot; i++) {
      var tImg     = new Image();
      tImg.onload  = imgLoaded;
      tImg.onerror = imgLoaded;
      tImg.src     = img[i].src;
    }    
  }
  document.addEventListener('DOMContentLoaded', loadbar, false);
}());

Replace all double quotes within String

I think a regex is a little bit of an overkill in this situation. If you just want to remove all the quotes in your string I would use this code:

details = details.replace("\"", "");

Converting Long to Date in Java returns 1970

The Date constructor (click the link!) accepts the time as long in milliseconds, not seconds. You need to multiply it by 1000 and make sure that you supply it as long.

Date d = new Date(1220227200L * 1000);

This shows here

Sun Aug 31 20:00:00 GMT-04:00 2008

Onclick javascript to make browser go back to previous page?

<input name="action" type="submit" value="Cancel" onclick="window.history.back();"/> 

No module named 'pymysql'

Sort of already answered this in the comments, but just so this question has an answer, the problem was resolved through running:

sudo apt-get install python3-pymysql

Create an array with same element repeated multiple times

[c] * n can be written as:

Array(n+1).join(1).split('').map(function(){return c;})

so for [2] * 5

Array(6).join(1).split('').map(function(){return 2;})

How to increase the clickable area of a <a> tag button?

To increase the area of a text link you can use the following css;

a {     
   display: inline-block;     
   position: relative;    
   z-index: 1;     
   padding: 2em;     
   margin: -2em; 
}
  • Display: inline-block is required so that margins and padding can be set
  • Position needs to be relative so that...
  • z-index can be used to make the clickable area stay on top of any text that follows.
  • The padding increases the area that can be clicked
  • The negative margin keeps the flow of surrounding text as it should be (beware of over lapping links)

Adding click event for a button created dynamically using jQuery

Use a delegated event handler bound to the container:

$('#pg_menu_content').on('click', '#btn_a', function(){
    console.log(this.value);
});

That is, bind to an element that exists at the moment that the JS runs (I'm assuming #pg_menu_content exists when the page loads), and supply a selector in the second parameter to .on(). When a click occurs on #pg_menu_content element jQuery checks whether it applied to a child of that element which matches the #btn_a selector.

Either that or bind a standard (non-delegated) click handler after creating the button.

Either way, within the click handler this will refer to the button in question, so this.value will give you its value.

Select NOT IN multiple columns

Another mysteriously unknown RDBMS. Your Syntax is perfectly fine in PostgreSQL. Other query styles may perform faster (especially the NOT EXISTS variant or a LEFT JOIN), but your query is perfectly legit.

Be aware of pitfalls with NOT IN, though, when involving any NULL values:

Variant with LEFT JOIN:

SELECT *
FROM   friend f
LEFT   JOIN likes l USING (id1, id2)
WHERE  l.id1 IS NULL;

See @Michal's answer for the NOT EXISTS variant.
A more detailed assessment of four basic variants:

window.onload vs <body onload=""/>

They both work the same. However, note that if both are defined, only one of them will be invoked. I generally avoid using either of them directly. Instead, you can attach an event handler to the load event. This way you can incorporate more easily other JS packages which might also need to attach a callback to the onload event.

Any JS framework will have cross-browser methods for event handlers.

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

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

Simple jQuery plugin for delayed window resize event.

SYNTAX:

Add new function to resize event

jQuery(window).resizeDelayed( func, delay, id ); // delay and id are optional

Remove the function(by declaring its ID) added earlier

jQuery(window).resizeDelayed( false, id );

Remove all functions

jQuery(window).resizeDelayed( false );

USAGE:

// ADD SOME FUNCTIONS TO RESIZE EVENT
jQuery(window).resizeDelayed( function(){ console.log( 'first event - should run after 0.4 seconds'); }, 400,  'id-first-event' );
jQuery(window).resizeDelayed( function(){ console.log('second event - should run after 1.5 seconds'); }, 1500, 'id-second-event' );
jQuery(window).resizeDelayed( function(){ console.log( 'third event - should run after 3.0 seconds'); }, 3000, 'id-third-event' );

// LETS DELETE THE SECOND ONE
jQuery(window).resizeDelayed( false, 'id-second-event' );

// LETS ADD ONE WITH AUTOGENERATED ID(THIS COULDNT BE DELETED LATER) AND DEFAULT TIMEOUT (500ms)
jQuery(window).resizeDelayed( function(){ console.log('newest event - should run after 0.5 second'); } );

// LETS CALL RESIZE EVENT MANUALLY MULTIPLE TIMES (OR YOU CAN RESIZE YOUR BROWSER WINDOW) TO SEE WHAT WILL HAPPEN
jQuery(window).resize().resize().resize().resize().resize().resize().resize();

USAGE OUTPUT:

first event - should run after 0.4 seconds
newest event - should run after 0.5 second
third event - should run after 3.0 seconds

PLUGIN:

jQuery.fn.resizeDelayed = (function(){

    // >>> THIS PART RUNS ONLY ONCE - RIGHT NOW

    var rd_funcs = [], rd_counter = 1, foreachResizeFunction = function( func ){ for( var index in rd_funcs ) { func(index); } };

    // REGISTER JQUERY RESIZE EVENT HANDLER
    jQuery(window).resize(function() {

        // SET/RESET TIMEOUT ON EACH REGISTERED FUNCTION
        foreachResizeFunction(function(index){

            // IF THIS FUNCTION IS MANUALLY DISABLED ( by calling jQuery(window).resizeDelayed(false, 'id') ),
            // THEN JUST CONTINUE TO NEXT ONE
            if( rd_funcs[index] === false )
                return; // CONTINUE;

            // IF setTimeout IS ALREADY SET, THAT MEANS THAT WE SHOULD RESET IT BECAUSE ITS CALLED BEFORE DURATION TIME EXPIRES
            if( rd_funcs[index].timeout !== false )
                clearTimeout( rd_funcs[index].timeout );

            // SET NEW TIMEOUT BY RESPECTING DURATION TIME
            rd_funcs[index].timeout = setTimeout( rd_funcs[index].func, rd_funcs[index].delay );

        });

    });

    // <<< THIS PART RUNS ONLY ONCE - RIGHT NOW

    // RETURN THE FUNCTION WHICH JQUERY SHOULD USE WHEN jQuery(window).resizeDelayed(...) IS CALLED
    return function( func_or_false, delay_or_id, id ){

        // FIRST PARAM SHOULD BE SET!
        if( typeof func_or_false == "undefined" ){

            console.log( 'jQuery(window).resizeDelayed(...) REQUIRES AT LEAST 1 PARAMETER!' );
            return this; // RETURN JQUERY OBJECT

        }

        // SHOULD WE DELETE THE EXISTING FUNCTION(S) INSTEAD OF CREATING A NEW ONE?
        if( func_or_false == false ){

            // DELETE ALL REGISTERED FUNCTIONS?
            if( typeof delay_or_id == "undefined" ){

                // CLEAR ALL setTimeout's FIRST
                foreachResizeFunction(function(index){

                    if( typeof rd_funcs[index] != "undefined" && rd_funcs[index].timeout !== false )
                        clearTimeout( rd_funcs[index].timeout );

                });

                rd_funcs = [];

                return this; // RETURN JQUERY OBJECT

            }
            // DELETE ONLY THE FUNCTION WITH SPECIFIC ID?
            else if( typeof rd_funcs[delay_or_id] != "undefined" ){

                // CLEAR setTimeout FIRST
                if( rd_funcs[delay_or_id].timeout !== false )
                    clearTimeout( rd_funcs[delay_or_id].timeout );

                rd_funcs[delay_or_id] = false;

                return this; // RETURN JQUERY OBJECT

            }

        }

        // NOW, FIRST PARAM MUST BE THE FUNCTION
        if( typeof func_or_false != "function" )
            return this; // RETURN JQUERY OBJECT

        // SET THE DEFAULT DELAY TIME IF ITS NOT ALREADY SET
        if( typeof delay_or_id == "undefined" || isNaN(delay_or_id) )
            delay_or_id = 500;

        // SET THE DEFAULT ID IF ITS NOT ALREADY SET
        if( typeof id == "undefined" )
            id = rd_counter;

        // ADD NEW FUNCTION TO RESIZE EVENT
        rd_funcs[id] = {
            func : func_or_false,
            delay: delay_or_id,
            timeout : false
        };

        rd_counter++;

        return this; // RETURN JQUERY OBJECT

    }

})();

Calculate the execution time of a method

Following this Microsoft Doc:

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();
        Thread.Sleep(10000);
        stopWatch.Stop();
        // Get the elapsed time as a TimeSpan value.
        TimeSpan ts = stopWatch.Elapsed;

        // Format and display the TimeSpan value.
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

Output: RunTime 00:00:09.94

How to read from stdin with fgets()?

You have a wrong idea of what fgets returns. Take a look at this: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

It returns null when it finds an EOF character. Try running the program above and pressing CTRL+D (or whatever combination is your EOF character), and the loop will exit succesfully.

How do you want to detect the end of the input? Newline? Dot (you said sentence xD)?

How do I represent a time only value in .NET?

As others have said, you can use a DateTime and ignore the date, or use a TimeSpan. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime type to represent a time of day.

One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...

(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)

How to find a text inside SQL Server procedures / triggers?

You can search within the definitions of all database objects using the following SQL:

SELECT 
    o.name, 
    o.id, 
    c.text,
    o.type
FROM 
    sysobjects o 
RIGHT JOIN syscomments c 
    ON o.id = c.id 
WHERE 
    c.text like '%text_to_find%'

How to wait in a batch script?

I actually found the right command to use.. its called timeout: http://www.ss64.com/nt/timeout.html

Converting Date and Time To Unix Timestamp

If you just need a good date-parsing function, I would look at date.js. It will take just about any date string you can throw at it, and return you a JavaScript Date object.

Once you have a Date object, you can call its getTime() method, which will give you milliseconds since January 1, 1970. Just divide that result by 1000 to get the unix timestamp value.

In code, just include date.js, then:

var unixtime = Date.parse("24-Nov-2009 17:57:35").getTime()/1000

WPF Binding StringFormat Short Date String

If you want add a string with the value use this:

<TextBlock Text="{Binding Date, StringFormat= 'Date : {0:d}'}" />

Bootstrap dropdown sub menu missing

Shprink's code helped me the most, but to avoid the dropdown to go off-screen i updated it to:

JS:

$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
    // Avoid following the href location when clicking
    event.preventDefault(); 
    // Avoid having the menu to close when clicking
    event.stopPropagation(); 
    // If a menu is already open we close it
    $('ul.dropdown-menu [data-toggle=dropdown]').parent().removeClass('open');
    // opening the one you clicked on
    $(this).parent().addClass('open');

    var menu = $(this).parent().find("ul");
    var menupos = $(menu).offset();

    if (menupos.left + menu.width() > $(window).width()) {
        var newpos = -$(menu).width();
        menu.css({ left: newpos });    
    } else {
        var newpos = $(this).parent().width();
        menu.css({ left: newpos });
    }

});

CSS: FROM background-color: #eeeeee TO background-color: #c5c5c5 - white font & light background wasn't looking good.

.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
  background-color: #c5c5c5;
  border-color: #428bca;
}

I hope this helps people as much as it did for me!

But i hope Bootstrap add the subs feature back ASAP.

How to convert JSONObjects to JSONArray?

Something like this:

JSONObject songs= json.getJSONObject("songs");
Iterator x = songs.keys();
JSONArray jsonArray = new JSONArray();

while (x.hasNext()){
    String key = (String) x.next();
    jsonArray.put(songs.get(key));
}

How can I preview a merge in git?

Maybe this can help you ? git-diff-tree - Compares the content and mode of blobs found via two tree objects

React-Native Button style not work

The React Native Button is very limited in what you can do, see; Button

It does not have a style prop, and you don't set text the "web-way" like <Button>txt</Button> but via the title property <Button title="txt" />

If you want to have more control over the appearance you should use one of the TouchableXXXX' components like TouchableOpacity They are really easy to use :-)

Strip Leading and Trailing Spaces From Java String

With Java-11 and above, you can make use of the String.strip API to return a string whose value is this string, with all leading and trailing whitespace removed. The javadoc for the same reads :

/**
 * Returns a string whose value is this string, with all leading
 * and trailing {@link Character#isWhitespace(int) white space}
 * removed.
 * <p>
 * If this {@code String} object represents an empty string,
 * or if all code points in this string are
 * {@link Character#isWhitespace(int) white space}, then an empty string
 * is returned.
 * <p>
 * Otherwise, returns a substring of this string beginning with the first
 * code point that is not a {@link Character#isWhitespace(int) white space}
 * up to and including the last code point that is not a
 * {@link Character#isWhitespace(int) white space}.
 * <p>
 * This method may be used to strip
 * {@link Character#isWhitespace(int) white space} from
 * the beginning and end of a string.
 *
 * @return  a string whose value is this string, with all leading
 *          and trailing white space removed
 *
 * @see Character#isWhitespace(int)
 *
 * @since 11
 */
public String strip()

The sample cases for these could be:--

System.out.println("  leading".strip()); // prints "leading"
System.out.println("trailing  ".strip()); // prints "trailing"
System.out.println("  keep this  ".strip()); // prints "keep this"

Referencing value in a closed Excel workbook using INDIRECT?

If you know the number of sheet you want to reference you can use below function to find out the name. Than you can use it in INDIRECT funcion.

Public Function GETSHEETNAME(address As String, Optional SheetNumber As Integer = 1) As String

    Set WS = GetObject(address).Worksheets
    GETSHEETNAME = WS(SheetNumber).Name

End Function

This solution doesn't require referenced workbook to be open - Excel gonna open it by itself (but it's gonna be hidden).

TERM environment variable not set

You've answered the question with this statement:

Cron calls this .sh every 2 minutes

Cron does not run in a terminal, so why would you expect one to be set?

The most common reason for getting this error message is because the script attempts to source the user's .profile which does not check that it's running in a terminal before doing something tty related. Workarounds include using a shebang line like:

#!/bin/bash -p

Which causes the sourcing of system-level profile scripts which (one hopes) does not attempt to do anything too silly and will have guards around code that depends on being run from a terminal.

If this is the entirety of the script, then the TERM error is coming from something other than the plain content of the script.

Hibernate - A collection with cascade=”all-delete-orphan” was no longer referenced by the owning entity instance

It might be caused by hibernate-enhance-maven-plugin. When I enabled enableLazyInitialization property this exception started on happening on my lazy collection. I'm using hibernate 5.2.17.Final.

Note this two hibernate issues:

How to use filesaver.js

For people who want to load it in the console :

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js';
document.body.appendChild(s);

Then :

saveAs(new Blob([data], {type: "application/octet-stream ;charset=utf-8"}), "video.ts")

File will be save when you're out of a breakpoint (at least on Chrome)

How to change the color of progressbar in C# .NET 3.5?

EDIT

By the sounds of things you're using the XP Theme which has the green block based prog-bar. Try flipping your UI Style to Windows Classic and test again, but you may need to implement your own OnPaint event to get it to do what you want across all UI Styles

Or as someone else pointed out, disable the VisualStyles for your application.

Original

As far as I know, the rendering of the Progress bar happens inline with the windows theme style that you've chosen (win2K, xp, vista)

You can change the color by setting the property

ProgressBar.ForeColor

I'm not sure that you can do much more however...

does some googling

Theres an article here from MS KB on creating a "Smooth" progress bar

http://support.microsoft.com/kb/323116

SQL datetime format to date only

With SQL server you can use this

SELECT CONVERT(VARCHAR(10), GETDATE(), 101) AS [MM/DD/YYYY];

with mysql server you can do the following

SELECT * FROM my_table WHERE YEAR(date_field) = '2006' AND MONTH(date_field) = '9' AND DAY(date_field) = '11'

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How to test android apps in a real device with Android Studio?

If USB Debugging Mode is enabled and does not work, you should install your device driver.

For Nexus Devices;

  • Install Google USB Drivers on SDK Tools.
  • Go to Control Panel > Device Manager and check drivers status. (Probably you can see warning icon on ADB Interface Driver.) Select ADB Interface driver and click update. Choose "Browse my computer for driver software" and set folder path like "D:\Users\userName\AppData\Local\Android\sdk".

For Another Devices;

  • If you install the model's driver, it may work. For ex: Samsung Kies, LG PC Suite.

Hope it helps!

Call two functions from same onclick

Add semi-colons ; to the end of the function calls in order for them both to work.

 <input id="btn" type="button" value="click" onclick="pay(); cls();"/>

I don't believe the last one is required but hey, might as well add it in for good measure.

Here is a good reference from SitePoint http://reference.sitepoint.com/html/event-attributes/onclick

Leverage browser caching, how on apache or .htaccess?

I took my chance to provide full .htaccess code to pass on Google PageSpeed Insight:

  1. Enable compression
  2. Leverage browser caching
# Enable Compression
<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
</IfModule>
<IfModule mod_gzip.c>
  mod_gzip_on Yes
  mod_gzip_dechunk Yes
  mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
  mod_gzip_item_include handler ^cgi-script$
  mod_gzip_item_include mime ^text/.*
  mod_gzip_item_include mime ^application/x-javascript.*
  mod_gzip_item_exclude mime ^image/.*
  mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

# Leverage Browser Caching
<IfModule mod_expires.c>
  ExpiresActive On
  ExpiresByType image/jpg "access 1 year"
  ExpiresByType image/jpeg "access 1 year"
  ExpiresByType image/gif "access 1 year"
  ExpiresByType image/png "access 1 year"
  ExpiresByType text/css "access 1 month"
  ExpiresByType text/html "access 1 month"
  ExpiresByType application/pdf "access 1 month"
  ExpiresByType text/x-javascript "access 1 month"
  ExpiresByType application/x-shockwave-flash "access 1 month"
  ExpiresByType image/x-icon "access 1 year"
  ExpiresDefault "access 1 month"
</IfModule>
<IfModule mod_headers.c>
  <filesmatch "\.(ico|flv|jpg|jpeg|png|gif|css|swf)$">
  Header set Cache-Control "max-age=2678400, public"
  </filesmatch>
  <filesmatch "\.(html|htm)$">
  Header set Cache-Control "max-age=7200, private, must-revalidate"
  </filesmatch>
  <filesmatch "\.(pdf)$">
  Header set Cache-Control "max-age=86400, public"
  </filesmatch>
  <filesmatch "\.(js)$">
  Header set Cache-Control "max-age=2678400, private"
  </filesmatch>
</IfModule>

There is also some configurations for various web servers see here.
Hope this would help to get the 100/100 score.

optimized page score

How to align text below an image in CSS?

Instead of images i choose background option:

HTML:

  <div class="class1">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>    
  <div class="class2">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>
  <div class="class3">
   <p>Some paragraph, Some paragraph, Some paragraph, Some paragraph, Some paragraph, 
   </p>
  </div>        

CSS:

  .class1 {

    background: url("Some.png") no-repeat top center;
    text-align: center;

   }

  .class2 {

    background: url("Some2.png") no-repeat top center;
    text-align: center;

   }

  .class3 {

    background: url("Some3.png") no-repeat top center;
    text-align: center;

   }

A top-like utility for monitoring CUDA activity on a GPU

you can use nvidia-smi pmon -i 0 to monitor every process in GPU 0. including compute mode, sm usage, memory usage, encoder usage, decoder usage.

Is it possible to specify condition in Count()?

Here is what I did to get a data set that included both the total and the number that met the criteria, within each shipping container. That let me answer the question "How many shipping containers have more than X% items over size 51"

select
   Schedule,
   PackageNum,
   COUNT (UniqueID) as Total,
   SUM (
   case
      when
         Size > 51 
      then
         1 
      else
         0 
   end
) as NumOverSize 
from
   Inventory 
where
   customer like '%PEPSI%' 
group by
   Schedule, PackageNum

Why can't Python parse this JSON data?

If you're using Python3, you can try changing your (connection.json file) JSON to:

{
  "connection1": {
    "DSN": "con1",
    "UID": "abc",
    "PWD": "1234",
    "connection_string_python":"test1"
  }
  ,
  "connection2": {
    "DSN": "con2",
    "UID": "def",
    "PWD": "1234"
  }
}

Then using the following code:

connection_file = open('connection.json', 'r')
conn_string = json.load(connection_file)
conn_string['connection1']['connection_string_python'])
connection_file.close()
>>> test1

Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2

My problem were different indices, the following code solved my problem.

df1.reset_index(drop=True, inplace=True)
df2.reset_index(drop=True, inplace=True)
df = pd.concat([df1, df2], axis=1)

No module named Image

Did you setup PIL module? Link

You can try to reinstall it on your computer.

Run react-native application on iOS device directly from command line?

If you get this error [email protected] preinstall: ./src/scripts/check_reqs.js && xcodebuild ... using npm install -g ios-deploy

Try this. It works for me:

  1. sudo npm uninstall -g ios-deploy
  2. brew install ios-deploy

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

How do I clone a github project to run locally?

I use @Thiho answer but i get this error:

'git' is not recognized as an internal or external command

For solving that i use this steps:

I add the following paths to PATH:

  • C:\Program Files\Git\bin\

  • C:\Program Files\Git\cmd\

In windows 7:

  1. Right-click "Computer" on the Desktop or Start Menu.
  2. Select "Properties".
  3. On the very far left, click the "Advanced system settings" link.
  4. Click the "Environment Variables" button at the bottom.
  5. Double-click the "Path" entry under "System variables".
  6. At the end of "Variable value", insert a ; if there is not already one, and then C:\Program Files\Git\bin\;C:\Program Files\Git\cmd. Do not put a space between ; and the entry.

Finally close and re-open your console.

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Trigger change event of dropdown

I don't know that much JQuery but I've heard it allows to fire native events with this syntax.

$(document).ready(function(){

    $('#countrylist').change(function(e){
       // Your event handler
    });

    // And now fire change event when the DOM is ready
    $('#countrylist').trigger('change');
});

You must declare the change event handler before calling trigger() or change() otherwise it won't be fired. Thanks for the mention @LenielMacaferi.

More information here.

Enabling/installing GD extension? --without-gd

In my case (php 5.6, Ubuntu 14.04) the following command worked for me:

sudo apt-get install php5.6-gd

According to php version we need to change the php5.x-gd

linking jquery in html

Add your test.js file after the jQuery libraries. This way your test.js file can use the libraries.

Adding Git-Bash to the new Windows Terminal

Adding "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i" doesn't work for me. Because of space symbol (which is separator in cmd) in %PROGRAMFILES% terminal executes command "C:\Program" instead of "C:\Program Files\Git\bin\bash.exe -l -i". The solution should be something like adding quotation marks in json file, but I didn't figure out how. The only solution is to add "C:\Program Files\Git\bin" to %PATH% and write "commandline": "bash.exe" in profiles.json

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

open the gradlew file with android studio, everything will be downloaded

Convert comma separated string of ints to int array

You should use a foreach loop, like this:

public static IEnumerable<int> StringToIntList(string str) {
    if (String.IsNullOrEmpty(str))
        yield break;

    foreach(var s in str.Split(',')) {
        int num;
        if (int.TryParse(s, out num))
            yield return num;
    }
}

Note that like your original post, this will ignore numbers that couldn't be parsed.

If you want to throw an exception if a number couldn't be parsed, you can do it much more simply using LINQ:

return (str ?? "").Split(',').Select<string, int>(int.Parse);

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

Invalid http_host header

settings.py

ALLOWED_HOSTS = ['*']

How to run Gulp tasks sequentially one after the other

I was having this exact same problem and the solution turned out to be pretty easy for me. Basically change your code to the following and it should work. NOTE: the return before gulp.src made all the difference for me.

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean",->
    return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

How to color System.out.println output?

Here is a solution for Win32 Console.

1) Get JavaNativeAccess libraries here: https://github.com/twall/jna/

2) These two Java classes will do the trick.

Enjoy.

package com.stackoverflow.util;

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Structure;

public class Win32 {
    public static final int STD_INPUT_HANDLE = -10;
    public static final int STD_OUTPUT_HANDLE = -11;
    public static final int STD_ERROR_HANDLE = -12;

    public static final short CONSOLE_FOREGROUND_COLOR_BLACK        = 0x00;
    public static final short CONSOLE_FOREGROUND_COLOR_BLUE         = 0x01;
    public static final short CONSOLE_FOREGROUND_COLOR_GREEN        = 0x02;
    public static final short CONSOLE_FOREGROUND_COLOR_AQUA         = 0x03;
    public static final short CONSOLE_FOREGROUND_COLOR_RED          = 0x04;
    public static final short CONSOLE_FOREGROUND_COLOR_PURPLE       = 0x05;
    public static final short CONSOLE_FOREGROUND_COLOR_YELLOW       = 0x06;
    public static final short CONSOLE_FOREGROUND_COLOR_WHITE        = 0x07;
    public static final short CONSOLE_FOREGROUND_COLOR_GRAY         = 0x08;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_BLUE   = 0x09;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_GREEN  = 0x0A;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_AQUA   = 0x0B;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_RED    = 0x0C;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_PURPLE = 0x0D;
    public static final short CONSOLE_FOREGROUND_COLOR_LIGHT_YELLOW = 0x0E;
    public static final short CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE = 0x0F;

    public static final short CONSOLE_BACKGROUND_COLOR_BLACK        = 0x00;
    public static final short CONSOLE_BACKGROUND_COLOR_BLUE         = 0x10;
    public static final short CONSOLE_BACKGROUND_COLOR_GREEN        = 0x20;
    public static final short CONSOLE_BACKGROUND_COLOR_AQUA         = 0x30;
    public static final short CONSOLE_BACKGROUND_COLOR_RED          = 0x40;
    public static final short CONSOLE_BACKGROUND_COLOR_PURPLE       = 0x50;
    public static final short CONSOLE_BACKGROUND_COLOR_YELLOW       = 0x60;
    public static final short CONSOLE_BACKGROUND_COLOR_WHITE        = 0x70;
    public static final short CONSOLE_BACKGROUND_COLOR_GRAY         = 0x80;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_BLUE   = 0x90;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_GREEN  = 0xA0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_AQUA   = 0xB0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_RED    = 0xC0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_PURPLE = 0xD0;
    public static final short CONSOLE_BACKGROUND_COLOR_LIGHT_YELLOW = 0xE0;
    public static final short CONSOLE_BACKGROUND_COLOR_BRIGHT_WHITE = 0xF0;

    // typedef struct _COORD {
    //    SHORT X;
    //    SHORT Y;
    //  } COORD, *PCOORD;
    public static class COORD extends Structure {
        public short X;
        public short Y;
    }

    // typedef struct _SMALL_RECT {
    //    SHORT Left;
    //    SHORT Top;
    //    SHORT Right;
    //    SHORT Bottom;
    //  } SMALL_RECT;
    public static class SMALL_RECT extends Structure {
        public short Left;
        public short Top;
        public short Right;
        public short Bottom;
    }

    // typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
    //    COORD      dwSize;
    //    COORD      dwCursorPosition;
    //    WORD       wAttributes;
    //    SMALL_RECT srWindow;
    //    COORD      dwMaximumWindowSize;
    //  } CONSOLE_SCREEN_BUFFER_INFO;
    public static class CONSOLE_SCREEN_BUFFER_INFO extends Structure {
        public COORD dwSize;
        public COORD dwCursorPosition;
        public short wAttributes;
        public SMALL_RECT srWindow;
        public COORD dwMaximumWindowSize;
    }

    // Source: https://github.com/twall/jna/nonav/javadoc/index.html
    public interface Kernel32 extends Library {
        Kernel32 DLL = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);

        // HANDLE WINAPI GetStdHandle(
        //        __in  DWORD nStdHandle
        //      );
        public int GetStdHandle(
                int nStdHandle);

        // BOOL WINAPI SetConsoleTextAttribute(
        //        __in  HANDLE hConsoleOutput,
        //        __in  WORD wAttributes
        //      );
        public boolean SetConsoleTextAttribute(
                int in_hConsoleOutput, 
                short in_wAttributes);

        // BOOL WINAPI GetConsoleScreenBufferInfo(
        //        __in   HANDLE hConsoleOutput,
        //        __out  PCONSOLE_SCREEN_BUFFER_INFO lpConsoleScreenBufferInfo
        //      );
        public boolean GetConsoleScreenBufferInfo(
                int in_hConsoleOutput,
                CONSOLE_SCREEN_BUFFER_INFO out_lpConsoleScreenBufferInfo);

        // DWORD WINAPI GetLastError(void);
        public int GetLastError();
    }
}
package com.stackoverflow.util;

import java.io.PrintStream;

import com.stackoverflow.util.Win32.Kernel32;

public class ConsoleUtil {
    public static void main(String[] args)
    throws Exception {
        System.out.print("abc");
        static_color_print(
                System.out, 
                "def", 
                Win32.CONSOLE_BACKGROUND_COLOR_RED, 
                Win32.CONSOLE_FOREGROUND_COLOR_BRIGHT_WHITE);
        System.out.print("def");
        System.out.println();
    }

    private static Win32.CONSOLE_SCREEN_BUFFER_INFO _static_console_screen_buffer_info = null; 

    public static void static_save_settings() {
        if (null == _static_console_screen_buffer_info) {
            _static_console_screen_buffer_info = new Win32.CONSOLE_SCREEN_BUFFER_INFO();
        }
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, _static_console_screen_buffer_info);
    }

    public static void static_restore_color()
    throws Exception {
        if (null == _static_console_screen_buffer_info) {
            throw new Exception("Internal error: Must save settings before restore");
        }
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        Kernel32.DLL.SetConsoleTextAttribute(
                stdout_handle, 
                _static_console_screen_buffer_info.wAttributes);
    }

    public static void static_set_color(Short background_color, Short foreground_color) {
        int stdout_handle = Kernel32.DLL.GetStdHandle(Win32.STD_OUTPUT_HANDLE);
        if (null == background_color || null == foreground_color) {
            Win32.CONSOLE_SCREEN_BUFFER_INFO console_screen_buffer_info = 
                new Win32.CONSOLE_SCREEN_BUFFER_INFO();
            Kernel32.DLL.GetConsoleScreenBufferInfo(stdout_handle, console_screen_buffer_info);
            short current_bg_and_fg_color = console_screen_buffer_info.wAttributes;
            if (null == background_color) {
                short current_bg_color = (short) (current_bg_and_fg_color / 0x10);
                background_color = new Short(current_bg_color);
            }
            if (null == foreground_color) {
                short current_fg_color = (short) (current_bg_and_fg_color % 0x10);
                foreground_color = new Short(current_fg_color);
            }
        }
        short bg_and_fg_color = 
            (short) (background_color.shortValue() | foreground_color.shortValue());
        Kernel32.DLL.SetConsoleTextAttribute(stdout_handle, bg_and_fg_color);
    }

    public static<T> void static_color_print(
            PrintStream ostream, 
            T value, 
            Short background_color, 
            Short foreground_color)
    throws Exception {
        static_save_settings();
        try {
            static_set_color(background_color, foreground_color);
            ostream.print(value);
        }
        finally {
            static_restore_color();
        }
    }

    public static<T> void static_color_println(
            PrintStream ostream, 
            T value, 
            Short background_color, 
            Short foreground_color)
    throws Exception {
        static_save_settings();
        try {
            static_set_color(background_color, foreground_color);
            ostream.println(value);
        }
        finally {
            static_restore_color();
        }
    }
}

Throwing multiple exceptions in a method of an interface in java

You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read

public class MyClass implements MyInterface {
  public void find(int x) throws A_Exception, B_Exception{
    ----
    ----
    ---
  }
}

Then an interface would look like this

public interface MyInterface {
  void find(int x) throws A_Exception, B_Exception;
}

How to convert String object to Boolean Object?

We created soyuz-to library to simplify this problem (convert X to Y). It's just a set of SO answers for similar questions. This might be strange to use the library for such a simple problem, but it really helps in a lot of similar cases.

import io.thedocs.soyuz.to;

Boolean aBoolean = to.Boolean("true");

Please check it - it's very simple and has a lot of other useful features

Similarity String Comparison in Java

You can achieve this using the apache commons java library. Take a look at these two functions within it:
- getLevenshteinDistance
- getFuzzyDistance

How to suppress Pandas Future warning ?

Warnings are annoying. As mentioned in other answers, you can suppress them using:

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)

But if you want to handle them one by one and you are managing a bigger codebase, it will be difficult to find the line of code which is causing the warning. Since warnings unlike errors don't come with code traceback. In order to trace warnings like errors, you can write this at the top of the code:

import warnings
warnings.filterwarnings("error")

But if the codebase is bigger and it is importing bunch of other libraries/packages, then all sort of warnings will start to be raised as errors. In order to raise only certain type of warnings (in your case, its FutureWarning) as error, you can write:

import warnings
warnings.simplefilter(action='error', category=FutureWarning)

How to prevent going back to the previous activity?

Put

finish();

immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add

onCreate(){
    getActionBar().setDisplayHomeAsUpEnabled(false);
    ...
}

to the activity you are starting.

Checking if a collection is empty in Java: which is the best method?

A good example of where this matters in practice is the ConcurrentSkipListSet implementation in the JDK, which states:

Beware that, unlike in most collections, the size method is not a constant-time operation.

This is a clear case where isEmpty() is much more efficient than checking whether size()==0.

You can see why, intuitively, this might be the case in some collections. If it's the sort of structure where you have to traverse the whole thing to count the elements, then if all you want to know is whether it's empty, you can stop as soon as you've found the first one.

Attach to a processes output for viewing

You can use reptyr:

sudo apt install reptyr
reptyr pid

How to Set Focus on JTextField?

In my case nothing above worked untill I called requestFocus() AFTER my constructor has returned.

MyPanel panel = new MyPanel(...);
frame.add(panel);
panel.initFocus();

MyPanel.initFocus() would have:

myTextField.requestFocus();

And it works.

Disabling swap files creation in vim

I agree with those who question why vim needs all this 'disaster recovery' stuff when no other text editors bother with it. I don't want vim creating ANY extra files in the edited file's directory when I'm editing it, thank you very much. To that end, I have this in my _vimrc to disable swap files, and move irritating 'backup' files to the Temp dir:

" Uncomment below to prevent 'tilde backup files' (eg. myfile.txt~) from being created
"set nobackup

" Uncomment below to cause 'tilde backup files' to be created in a different dir so as not to clutter up the current file's directory (probably a better idea than disabling them altogether)
set backupdir=C:\Windows\Temp

" Uncomment below to disable 'swap files' (eg. .myfile.txt.swp) from being created
set noswapfile

IDENTITY_INSERT is set to OFF - How to turn it ON?

Shouldn't you be setting identity_Insert ON, inserting the records and then turning it back off?

Like this:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
SET IDENTITY_INSERT tbl_content ON
GO

ALTER procedure [dbo].[spInsertDeletedIntoTBLContent]
@ContentID int, 
SET IDENTITY_INSERT tbl_content ON
...insert command...
SET IDENTITY_INSERT tbl_content OFF

Difference between [routerLink] and routerLink

You'll see this in all the directives:

When you use brackets, it means you're passing a bindable property (a variable).

  <a [routerLink]="routerLinkVariable"></a>

So this variable (routerLinkVariable) could be defined inside your class and it should have a value like below:

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!

But with variables, you have the opportunity to make it dynamic right?

export class myComponent {

    public routerLinkVariable = "/home"; // the value of the variable is string!


    updateRouterLinkVariable(){

        this.routerLinkVariable = '/about';
    }

Where as without brackets you're passing string only and you can't change it, it's hard coded and it'll be like that throughout your app.

<a routerLink="/home"></a>

UPDATE :

The other speciality about using brackets specifically for routerLink is that you can pass dynamic parameters to the link you're navigating to:

So adding a new variable

export class myComponent {
        private dynamicParameter = '129';
        public routerLinkVariable = "/home"; 

Updating the [routerLink]

  <a [routerLink]="[routerLinkVariable,dynamicParameter]"></a>

When you want to click on this link, it would become:

  <a href="/home/129"></a>

Node update a specific package

Always you can do it manually. Those are the steps:

  • Go to the NPM package page, and search for the GitHub link.
  • Now download the latest version using GitHub download link, or by clonning. git clone github_url
  • Copy the package to your node_modules folder for e.g. node_modules/browser-sync

Now it should work for you. To be sure it will not break in the future when you do npm i, continue the upcoming two steps:

  • Check the version of the new package by reading the package.json file in it's folder.
  • Open your project package.json and set the same version for where it's appear in the dependencies part of your package.json

While it's not recommened to do it manually. Sometimes it's good to understand how things are working under the hood, to be able to fix things. I found myself doing it from time to time.

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

python pandas: apply a function with arguments to a series

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

args : tuple

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

Show and hide a View with a slide up/down animation

Using ObjectAnimator

private fun slideDown(view: View) {
    val height = view.height
    ObjectAnimator.ofFloat(view, "translationY", 0.toFloat(), height.toFloat()).apply {
        duration = 1000
        start()
    }
}

private fun slideUp(view: View) {
    val height = view.height
    ObjectAnimator.ofFloat(view, "translationY", height.toFloat(),0.toFloat()).apply {
        duration = 1000
        start()
    }
}

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

Simpler is better IMO!

Why don't you do this?

public class CourseController : JsonController
{
    public ActionResult ManageCoursesModel()
    {
        return JsonContent(<somedata>);
    }
}

The simple base class controller

public class JsonController : BaseController
{
    protected ContentResult JsonContent(Object data)
    {
        return new ContentResult
        {
            ContentType = "application/json",
             Content = JsonConvert.SerializeObject(data, new JsonSerializerSettings { 
              ContractResolver = new CamelCasePropertyNamesContractResolver() }),
            ContentEncoding = Encoding.UTF8
        };
    }
}

How to install Python packages from the tar.gz file without using pip install

You may use pip for that without using the network. See in the docs (search for "Install a particular source archive file"). Any of those should work:

pip install relative_path_to_seaborn.tar.gz    
pip install absolute_path_to_seaborn.tar.gz    
pip install file:///absolute_path_to_seaborn.tar.gz    

Or you may uncompress the archive and use setup.py directly with either pip or python:

cd directory_containing_tar.gz
tar -xvzf seaborn-0.10.1.tar.gz
pip install seaborn-0.10.1
python setup.py install

Of course, you should also download required packages and install them the same way before you proceed.

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Many times I have been facing this problem, I have experienced ClassNotFoundException. if jar is not at physical location.

So make sure .jar file(mysql connector) in the physical location of WEB-INF lib folder. and make sure restarting Tomcat by using shutdown command in cmd. it should work.

jQuery - Appending a div to body, the body is the object?

    $('body').append($('<div/>', {
        id: 'holdy' 
    }));

Parsing a comma-delimited std::string

You could also use the following function.

void tokenize(const string& str, vector<string>& tokens, const string& delimiters = ",")
{
  // Skip delimiters at beginning.
  string::size_type lastPos = str.find_first_not_of(delimiters, 0);

  // Find first non-delimiter.
  string::size_type pos = str.find_first_of(delimiters, lastPos);

  while (string::npos != pos || string::npos != lastPos) {
    // Found a token, add it to the vector.
    tokens.push_back(str.substr(lastPos, pos - lastPos));

    // Skip delimiters.
    lastPos = str.find_first_not_of(delimiters, pos);

    // Find next non-delimiter.
    pos = str.find_first_of(delimiters, lastPos);
  }
}

How to get value of Radio Buttons?

Windows Forms

For cases where there are multiple radio buttons to check, this function is very compact:

/// <summary>
/// Get the value of the radio button that is checked.
/// </summary>
/// <param name="buttons">The radio buttons to look through</param>
/// <returns>The name of the radio button that is checked</returns>
public static string GetCheckedRadioButton(params RadioButton[] radioButtons)
{
    // Look at each button, returning the text of the one that is checked.
    foreach (RadioButton button in radioButtons)
    {
        if (button.Checked)
            return button.Text;
    }
    return null;
}

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

Yet another way to do this:

(Get-Date).AddDays(-1).Date.AddHours(22)

How to pass variables from one php page to another without form?

You can use Ajax calls or $_GET["String"]; Method

How to gzip all files in all sub-directories into one compressed file in bash

there are lots of compression methods that work recursively command line and its good to know who the end audience is.

i.e. if it is to be sent to someone running windows then zip would probably be best:

zip -r file.zip folder_to_zip

unzip filenname.zip

for other linux users or your self tar is great

tar -cvzf filename.tar.gz folder

tar -cvjf filename.tar.bz2 folder  # even more compression

#change the -c to -x to above to extract

One must be careful with tar and how things are tarred up/extracted, for example if I run

cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd


pwd

/home/myusername

tar -xvzf passwd.tar.gz

this will create /home/myusername/etc/passwd

unsure if all versions of tar do this:

 Removing leading `/' from member names

nvarchar(max) vs NText

VARCHAR(MAX) is big enough to accommodate TEXT field. TEXT, NTEXT and IMAGE data types of SQL Server 2000 will be deprecated in future version of SQL Server, SQL Server 2005 provides backward compatibility to data types but it is recommended to use new data types which are VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX).

How do I pass JavaScript values to Scriptlet in JSP?

I can provide two ways,

a.jsp,

<html>
    <script language="javascript" type="text/javascript">
        function call(){
            var name = "xyz";
            window.location.replace("a.jsp?name="+name);
        }
    </script>
    <input type="button" value="Get" onclick='call()'>
    <%
        String name=request.getParameter("name");
        if(name!=null){
            out.println(name);
        }
    %>
</html>

b.jsp,

<script>
    var v="xyz";
</script>
<% 
    String st="<script>document.writeln(v)</script>";
    out.println("value="+st); 
%>

Losing Session State

I was having a situation in ASP.NET 4.0 where my session would be reset on every page request (and my SESSION_START code would run on each page request). This didn't happen to every user for every session, but it usually happened, and when it did, it would happen on each page request.

My web.config sessionState tag had the same setting as the one mentioned above.

cookieless="false"

When I changed it to the following...

cookieless="UseCookies"

... the problem seemed to go away. Apparently true|false were old choices from ASP.NET 1. Starting in ASP.Net 2.0, the enumerated choices started being available. I guess these options were deprecated. The "false" value has never presented a problem in the past - I've only noticed in on ASP.NET 4.0. I don't know if something has changed in 4.0 that no longer supports it correctly.

Also, I just found this out not long ago. Since the problem was intermittent before, I suppose I could still encounter it, but so far it's working with this new setting.

How to run python script on terminal (ubuntu)?

Set the PATH as below:


In the csh shell - type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.

In the bash shell (Linux) - type export PATH="$PATH:/usr/local/bin/python" and press Enter.

In the sh or ksh shell - type PATH="$PATH:/usr/local/bin/python" and press Enter.

Note - /usr/local/bin/python is the path of the Python directory


now run as below:

-bash-4.2$ python test.py

Hello, Python!

Exit single-user mode

To switch out of Single User mode, try:

ALTER DATABASE [my_db] SET MULTI_USER

To switch back to Single User mode, you can use:

ALTER DATABASE [my_db] SET SINGLE_USER

Passing a local variable from one function to another

Adding to @pranay-rana's list:

Third way is:

function passFromValue(){
    var x = 15;
    return x;  
}
function passToValue() {
    var y = passFromValue();
    console.log(y);//15
}
passToValue(); 

Convert DataTable to IEnumerable<T>

If you are producing the DataTable from an SQL query, have you considered simply using Dapper instead?

Then, instead of making a SqlCommand with SqlParameters and a DataTable and a DataAdapter and on and on, which you then have to laboriously convert to a class, you just define the class, make the query column names match the field names, and the parameters are bound easily by name. You already have the TankReading class defined, so it will be really simple!

using Dapper;

// Below can be SqlConnection cast to DatabaseConnection, too.
DatabaseConnection connection = // whatever
IEnumerable<TankReading> tankReadings = connection.Query<TankReading>(
   "SELECT * from TankReading WHERE Value = @value",
   new { value = "tank1" } // note how `value` maps to `@value`
);
return tankReadings;

Now isn't that awesome? Dapper is very optimized and will give you darn near equivalent performance as reading directly with a DataAdapter.

If your class has any logic in it at all or is immutable or has no parameterless constructor, then you probably do need to have a DbTankReading class (as a pure POCO/Plain Old Class Object):

// internal because it should only be used in the data source project and not elsewhere
internal sealed class DbTankReading {
   int TankReadingsID { get; set; }
   DateTime? ReadingDateTime { get; set; }
   int ReadingFeet { get; set; }
   int ReadingInches { get; set; }
   string MaterialNumber { get; set; }
   string EnteredBy { get; set; }
   decimal ReadingPounds { get; set; }
   int MaterialID { get; set; }
   bool Submitted { get; set; }
}

You'd use that like this:

IEnumerable<TankReading> tankReadings = connection
   .Query<DbTankReading>(
      "SELECT * from TankReading WHERE Value = @value",
      new { value = "tank1" } // note how `value` maps to `@value`
   )
   .Select(tr => new TankReading(
      tr.TankReadingsID,
      tr.ReadingDateTime,
      tr.ReadingFeet,
      tr.ReadingInches,
      tr.MaterialNumber,
      tr.EnteredBy,
      tr.ReadingPounds,
      tr.MaterialID,
      tr.Submitted
   });

Despite the mapping work, this is still less painful than the data table method. This also lets you perform some kind of logic, though if the logic is any more than very simple straight-across mapping, I'd put the logic into a separate TankReadingMapper class.

Twitter Bootstrap and ASP.NET GridView

You need to set useaccessibleheader attribute of the gridview to true and also then also specify a TableSection to be a header after calling the DataBind() method on you GridView object. So if your grid view is mygv

mygv.UseAccessibleHeader = True
mygv.HeaderRow.TableSection = TableRowSection.TableHeader

This should result in a proper formatted grid with thead and tbody tags

What's the difference between a Future and a Promise?

Future and Promise are proxy object for unknown result

Promise completes a Future

  • Future - read/consumer of unknown result

  • Promise - write/producer of unknown result.

//Future has a reference to Promise
Future -> Promise

As a producer I promise something and responsible for it

As a consumer who retrieved a promise I expect to have a result in future

As for Java CompletableFutures it is a Promise because you can set the result and also it implements Future

Creating temporary files in Android

For temporary internal files their are 2 options

1.

File file; 
file = File.createTempFile(filename, null, this.getCacheDir());

2.

File file
file = new File(this.getCacheDir(), filename);

Both options adds files in the applications cache directory and thus can be cleared to make space as required but option 1 will add a random number on the end of the filename to keep files unique. It will also add a file extension which is .tmp by default, but it can be set to anything via the use of the 2nd parameter. The use of the random number means despite specifying a filename it doesn't stay the same as the number is added along with the suffix/file extension (.tmp by default) e.g you specify your filename as internal_file and comes out as internal_file1456345.tmp. Whereas you can specify the extension you can't specify the number that is added. You can however find the filename it generates via file.getName();, but you would need to store it somewhere so you can use it whenever you wanted for example to delete or read the file. Therefore for this reason I prefer the 2nd option as the filename you specify is the filename that is created.

Regex replace (in Python) - a simpler way?

>>> import re
>>> s = "start foo end"
>>> s = re.sub("foo", "replaced", s)
>>> s
'start replaced end'
>>> s = re.sub("(?<= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s)
>>> s
'start can use a callable for the replaced text too end'
>>> help(re.sub)
Help on function sub in module re:

sub(pattern, repl, string, count=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a callable, it's passed the match object and must return
    a replacement string to be used.

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

Javascript passes variables by reference, this means that:

var i = [];
var j = i;
i.push( 1 );

Now because of by reference part i is [1], and j is [1] as well, even though only i was changed. This is because when we say j = i javascript doesn't copy the i variable and assign it to j but references i variable through j.

Angular copy lets us lose this reference, which means:

var i = [];
var j = angular.copy( i );
i.push( 1 );

Now i here equals to [1], while j still equals to [].

There are situations when such kind of copy functionality is very handy.

Allow only numbers to be typed in a textbox

You could subscribe for the onkeypress event:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

and then define the isNumber function:

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

You can see it in action here.

setState() inside of componentDidUpdate()

If you use setState inside componentDidUpdate it updates the component, resulting in a call to componentDidUpdate which subsequently calls setState again resulting in the infinite loop. You should conditionally call setState and ensure that the condition violating the call occurs eventually e.g:

componentDidUpdate: function() {
    if (condition) {
        this.setState({..})
    } else {
        //do something else
    }
}

In case you are only updating the component by sending props to it(it is not being updated by setState, except for the case inside componentDidUpdate), you can call setState inside componentWillReceiveProps instead of componentDidUpdate.

Plotting images side by side using matplotlib

As per matplotlib's suggestion for image grids:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid

fig = plt.figure(figsize=(4., 4.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(2, 2),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )

for ax, im in zip(grid, image_data):
    # Iterating over the grid returns the Axes.
    ax.imshow(im)

plt.show()

How to add an element to the beginning of an OrderedDict?

If you know you will want a 'c' key, but do not know the value, insert 'c' with a dummy value when you create the dict.

d1 = OrderedDict([('c', None), ('a', '1'), ('b', '2')])

and change the value later.

d1['c'] = 3

Detecting Back Button/Hash Change in URL

Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.

Select distinct values from a list using LINQ in C#

You can try with this code

var result =  (from  item in List
              select new 
              {
                 EmpLoc = item.empLoc,
                 EmpPL= item.empPL,
                 EmpShift= item.empShift
              })
              .ToList()
              .Distinct();

The type arguments for method cannot be inferred from the usage

I wanted to make a simple and understandable example

if you call a method like this, your client will not know return type

var interestPoints = Mediator.Handle(new InterestPointTypeRequest
            {
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,
            });

Then you should say to compiler i know the return type is List<InterestPointTypeMap>

var interestPoints  = Mediator.Handle<List<InterestPointTypeMap>>(new InterestPointTypeRequest
            {
                LanguageCode = request.LanguageCode,
                AgentId = request.AgentId,
                InterestPointId = request.InterestPointId,
                InterestPointTypeId = request.InterestPointTypeId
            });

the compiler will no longer be mad at you for knowing the return type

bind/unbind service example (android)

First of all, two things that we need to understand,

Client

  • It makes request to a specific server

bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);

here mServiceConn is instance of ServiceConnection class(inbuilt) it is actually interface that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.

Server

  • It handles the request of the client and makes replica of its own which is private to client only who send request and this raplica of server runs on different thread.

Now at client side, how to access all the methods of server?

  • Server sends response with IBinder Object. So, IBinder object is our handler which accesses all the methods of Service by using (.) operator.

.

MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
        Log.d("ServiceConnection","connected");
        myService = binder;
    }
    //binder comes from server to communicate with method's of 

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
}

Now how to call method which lies in service

myservice.serviceMethod();

Here myService is object and serviceMethod is method in service. and by this way communication is established between client and server.

How to hide Soft Keyboard when activity starts

Put this in the manifest inside the Activity tag

  android:windowSoftInputMode="stateHidden"  

what does "dead beef" mean?

It's a made up expression using only the letters A-F, often used when a recognisable hexadecimal number is required. Some systems use it for various purposes such as showing memory which has been freed and should not be referenced again. In a debugger this value showing up could be a sign that you have made an error. From Wikipedia:

0xDEADBEEF ("dead beef") is used by IBM RS/6000 systems, Mac OS on 32-bit PowerPC processors and the Commodore Amiga as a magic debug value. On Sun Microsystems' Solaris, it marks freed kernel memory. On OpenVMS running on Alpha processors, DEAD_BEEF can be seen by pressing CTRL-T.

The number 0xDEADBEEF is equal to the less recognisable decimal number 3735928559 (unsigned) or -559038737 (signed).

How do I get the serial key for Visual Studio Express?

I believe that if you download the offline ISO image file, and use that to install Visual Studio Express, you won't have to register.

Go here and find the link that says "All - Offline Install ISO image file". Click on it to expand it, select your language, and then click "Download".

Otherwise, it's possible that online registration is simply down for a while, as the error message indicates. You have 30 days before it expires, so give it a few days before starting to panic.

Javascript validation: Block special characters

For special characters:

var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?";

for (var i = 0; i < document.formname.fieldname.value.length; i++) {
    if (iChars.indexOf(document.formname.fieldname.value.charAt(i)) != -1) {
        alert ("Your username has special characters. \nThese are not allowed.\n Please remove them and try again.");
        return false;
    }
}

Permission denied error on Github Push

Based on the information that the original poster has provided so far, it might be the case that the project owners of EasySoftwareLicensing/software-licensing-php will only accept pull requests from forks, so you may need to fork the main repo and push to your fork, then make pull requests from it to the main repo.

See the following GitHub help articles for instructions:

  1. Fork a Repo.
  2. Collaborating.

Creating dummy variables in pandas for python

So I was actually needing an answer to this question today (7/25/2013), so I wrote this earlier. I've tested it with some toy examples, hopefully you get some mileage out of it

def categorize_dict(x, y=0):
    # x Requires string or numerical input
    # y is a boolean that specifices whether to return category names along with the dict.
    # default is no
    cats = list(set(x))
    n = len(cats)
    m = len(x)
    outs = {}
    for i in cats:
        outs[i] = [0]*m
    for i in range(len(x)):
        outs[x[i]][i] = 1
    if y:
        return outs,cats
    return outs

jQuery get the location of an element relative to window

Initially, Grab the .offset position of the element and calculate its relative position with respect to window

Refer :
1. offset
2. scroll
3. scrollTop

You can give it a try at this fiddle

Following few lines of code explains how this can be solved

when .scroll event is performed, we calculate the relative position of the element with respect to window object

$(window).scroll(function () {
    console.log(eTop - $(window).scrollTop());
});

when scroll is performed in browser, we call the above event handler function

code snippet


_x000D_
_x000D_
function log(txt) {_x000D_
  $("#log").html("location : <b>" + txt + "</b> px")_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
  var eTop = $('#element').offset().top; //get the offset top of the element_x000D_
  log(eTop - $(window).scrollTop()); //position of the ele w.r.t window_x000D_
_x000D_
  $(window).scroll(function() { //when window is scrolled_x000D_
    log(eTop - $(window).scrollTop());_x000D_
  });_x000D_
});
_x000D_
#element {_x000D_
  margin: 140px;_x000D_
  text-align: center;_x000D_
  padding: 5px;_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  border: 1px solid #0099f9;_x000D_
  border-radius: 3px;_x000D_
  background: #444;_x000D_
  color: #0099d9;_x000D_
  opacity: 0.6;_x000D_
}_x000D_
#log {_x000D_
  position: fixed;_x000D_
  top: 40px;_x000D_
  left: 40px;_x000D_
  color: #333;_x000D_
}_x000D_
#scroll {_x000D_
  position: fixed;_x000D_
  bottom: 10px;_x000D_
  right: 10px;_x000D_
  border: 1px solid #000;_x000D_
  border-radius: 2px;_x000D_
  padding: 5px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="log"></div>_x000D_
_x000D_
<div id="element">Hello_x000D_
  <hr>World</div>_x000D_
<div id="scroll">Scroll Down</div>
_x000D_
_x000D_
_x000D_

Serialize Class containing Dictionary member

You can't serialize a class that implements IDictionary. Check out this link.

Q: Why can't I serialize hashtables?

A: The XmlSerializer cannot process classes implementing the IDictionary interface. This was partly due to schedule constraints and partly due to the fact that a hashtable does not have a counterpart in the XSD type system. The only solution is to implement a custom hashtable that does not implement the IDictionary interface.

So I think you need to create your own version of the Dictionary for this. Check this other question.

Hibernate show real SQL

Worth noting that the code you see is sent to the database as is, the queries are sent separately to prevent SQL injection. AFAIK The ? marks are placeholders that are replaced by the number params by the database, not by hibernate.

How can I select and upload multiple files with HTML and PHP, using HTTP POST?

Full solution in Firefox 5:

<html>
<head>
</head>
<body>
 <form name="uploader" id="uploader" action="multifile.php" method="POST" enctype="multipart/form-data" >
  <input id="infile" name="infile[]" type="file" onBlur="submit();" multiple="true" ></input> 
 </form>

<?php
echo "No. files uploaded : ".count($_FILES['infile']['name'])."<br>"; 


$uploadDir = "images/";
for ($i = 0; $i < count($_FILES['infile']['name']); $i++) {

 echo "File names : ".$_FILES['infile']['name'][$i]."<br>";
 $ext = substr(strrchr($_FILES['infile']['name'][$i], "."), 1); 

 // generate a random new file name to avoid name conflict
 $fPath = md5(rand() * time()) . ".$ext";

 echo "File paths : ".$_FILES['infile']['tmp_name'][$i]."<br>";
 $result = move_uploaded_file($_FILES['infile']['tmp_name'][$i], $uploadDir . $fPath);

 if (strlen($ext) > 0){
  echo "Uploaded ". $fPath ." succefully. <br>";
 }
}
echo "Upload complete.<br>";
?>

</body>
</html>

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

Find objects between two dates MongoDB

db.collection.find({"createdDate":{$gte:new ISODate("2017-04-14T23:59:59Z"),$lte:new ISODate("2017-04-15T23:59:59Z")}}).count();

Replace collection with name of collection you want to execute query

Check if a PHP cookie exists and if not set its value

Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

Source

Using "If cell contains #N/A" as a formula condition.

Input the following formula in C1:

=IF(ISNA(A1),B1,A1*B1)

Screenshots:

When #N/A:

enter image description here

When not #N/A:

enter image description here

Let us know if this helps.

Assign value from successful promise resolve to external variable

This could be updated to ES6 with arrow functions and look like:

getFeed().then(data => vm.feed = data);

If you wish to use the async function, you could also do like that:

async function myFunction(){
    vm.feed = await getFeed();
    // do whatever you need with vm.feed below
 }

Difference between "char" and "String" in Java

Char is a single alphabet where as String is a sequence of characters. Char is primitive datatype where as String is a class.

In PHP with PDO, how to check the final SQL parametrized query?

I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):

Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:

SET GLOBAL general_log = 'ON';

In a terminal, tail your log file. Mine was here:

>sudo tail -f /usr/local/mysql/data/myMacComputerName.log

You can search for your mysql files with this terminal command:

>ps auxww|grep [m]ysqld

I found that PDO escapes everything, so you can't write

$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();

Because it creates:

SELECT * FROM `example` WHERE `'userName'` = 'mick' ;

Which did not create an error, just an empty result. Instead I needed to use

$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";

to get

SELECT * FROM `example` WHERE `userName` = 'mick' ;

When you are done execute:

SET GLOBAL general_log = 'OFF';

or else your logs will get huge.

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

Check an integer value is Null in c#

As stated above, ?? is the null coalescing operator. So the equivalent to

(Age ?? 0) == 0

without using the ?? operator is

(!Age.HasValue) || Age == 0

However, there is no version of .Net that has Nullable< T > but not ??, so your statement,

Now i have to check in a older application where the declaration part is not in ternary.

is doubly invalid.

Select distinct using linq

You should override Equals and GetHashCode meaningfully, in this case to compare the ID:

public class LinqTest
{
    public int id { get; set; }
    public string value { get; set; }

    public override bool Equals(object obj)
    {
        LinqTest obj2 = obj as LinqTest;
        if (obj2 == null) return false;
        return id == obj2.id;
    }

    public override int GetHashCode()
    {
        return id;
    }
}

Now you can use Distinct:

List<LinqTest> uniqueIDs = myList.Distinct().ToList();

Find html label associated with a given input

As it has been already mentionned, the (currently) top-rated answer does not take into account the possibility to embed an input inside a label.

Since nobody has posted a JQuery-free answer, here is mine :

var labels = form.getElementsByTagName ('label');
var input_label = {};
for (var i = 0 ; i != labels.length ; i++)
{
    var label = labels[i];
    var input = label.htmlFor
              ? document.getElementById(label.htmlFor)
              : label.getElementsByTagName('input')[0];
    input_label[input.outerHTML] = 
        (label.innerText || label.textContent); // innerText for IE8-
}

In this example, for the sake of simplicity, the lookup table is directly indexed by the input HTML elements. This is hardly efficient and you can adapt it however you like.

You can use a form as base element, or the whole document if you want to get labels for multiple forms at once.

No checks are made for incorrect HTML (multiple or missing inputs inside labels, missing input with corresponding htmlFor id, etc), but feel free to add them.

You might want to trim the label texts, since trailing spaces are often present when the input is embedded in the label.

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option>

Thank you all for this thread! My colleague and I just discovered that the default_value property is a Constant, not a Variable.

In other React forms I've built, the default value for a Select was preset in an associated Context. So the first time the Select was rendered, default_value was set to the correct value.

But in my latest React form (a small modal), I'm passing the values for the form as props and then using a useEffect to populate the associated Context. So the FIRST time the Select is rendered, default_value is set to null. Then when the Context is populated and the Select is supposed to be re-rendered, default_value cannot be changed and thus the initial default value is not set.

The solution was ultimately simple: Use the value property instead. But figuring out why default_value didn't work like it did with my other forms took some time.

I'm posting this to help others in the community.

HTML.ActionLink vs Url.Action in ASP.NET Razor

<p>
    @Html.ActionLink("Create New", "Create")
</p>
@using (Html.BeginForm("Index", "Company", FormMethod.Get))
{
    <p>
        Find by Name: @Html.TextBox("SearchString", ViewBag.CurrentFilter as string)
        <input type="submit" value="Search" />
        <input type="button" value="Clear" onclick="location.href='@Url.Action("Index","Company")'"/>
    </p>
}

In the above example you can see that If I specifically need a button to do some action, I have to do it with @Url.Action whereas if I just want a link I will use @Html.ActionLink. The point is when you have to use some element(HTML) with action url is used.

How to find elements with 'value=x'?

$(selector).filter(function(){return this.value==yourval}).remove();

Conda command is not recognized on Windows 10

case #1 You should set 3 path:

%ANACONDAPATH%;
%ANACONDAPATH%\Scripts;
%ANACONDAPATH%\Library\bin;

It will solve problem:

C:\WINDOWS\system32>conda update conda
Solving environment: failed

CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/msys2/noarch/repodata.json.bz2>
Elapsed: -
...

case #2 Also you can use Anaconda Promd (for Win10) instead CLI (cmd.exe)

How to style a JSON block in Github Wiki?

I encountered the same problem. So, I tried representing the JSON in different Language syntax formats.But all time favorites are Perl, js, python, & elixir.

This is how it looks.

The following screenshots are from the Gitlab in a markdown file. This may vary based on the colors using for syntax in MARKDOWN files.

JsonasPerl

JsonasPython

JsonasJs

JsonasElixir

Quick Sort Vs Merge Sort

While quicksort is often a better choice than merge sort, there are definitely times when merge sort is thereotically a better choice. The most obvious time is when it's extremely important that your algorithm run faster than O(n^2). Quicksort is usually faster than this, but given the theoretical worst possible input, it could run in O(n^2), which is worse than the worst possible merge sort.

Quicksort is also more complicated than mergesort, especially if you want to write a really solid implementation, and so if you're aiming for simplicity and maintainability, merge sort becomes a promising alternative with very little performance loss.

Cannot GET / Nodejs Error

If you are getting this error, it could be because you don't have a route defined for your get.

For example:

const express = require('express');

const app = express();

app.get('/people', function (req, res) {
    res.send('hello');
})

app.listen(3000);


http://http://localhost:3000/people --> this works
http://http://localhost:3000 --> this will output Cannot GET / message.

css transform, jagged edges in chrome

I've been having an issue with a CSS3 gradient with -45deg. The background slanted, was badly jagged similar to but worse than the original post. So I started playing with both the background-size. This would stretch out the jaggedness, but it was still there. Then in addition I read that other people are having issues too at 45deg increments so I adjusted from -45deg to -45.0001deg and my problem was solved.

In my CSS below, background-size was initially 30px and the deg for the background gradient was exactly -45deg, and all keyframes were 30px 0.

    @-webkit-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-moz-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-ms-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-o-keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @keyframes progressStripeLTR {
        to {
            background-position: 60px 0;
        };
    }

    @-webkit-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-moz-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-ms-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @-o-keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    @keyframes progressStripeRTL {
        to {
            background-position: -60px 0;
        };
    }

    .pro-bar-candy {
        width: 100%;
        height: 15px;

        -webkit-border-radius:  3px;
        -moz-border-radius:     3px;
        border-radius:          3px;

        background: rgb(187, 187, 187);
        background: -moz-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -webkit-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -o-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -ms-linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: linear-gradient(
                        -45.0001deg,
                        rgba(187, 187, 187, 1.00) 25%,
                        transparent 25%,
                        transparent 50%,
                        rgba(187, 187, 187, 1.00) 50%,
                        rgba(187, 187, 187, 1.00) 75%,
                        transparent 75%,
                        transparent
                    );
        background: -webkit-gradient(
                        linear,
                        right bottom,
                        right top,
                        color-stop(
                            25%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            25%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            50%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            50%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            75%,
                            rgba(187, 187, 187, 1.00)
                        ),
                        color-stop(
                            75%,
                            rgba(0, 0, 0, 0.00)
                        ),
                        color-stop(
                            rgba(0, 0, 0, 0.00)
                        )
                    );

        background-repeat: repeat-x;
        -webkit-background-size:    60px 60px;
        -moz-background-size:       60px 60px;
        -o-background-size:         60px 60px;
        background-size:            60px 60px;
        }

    .pro-bar-candy.candy-ltr {
        -webkit-animation:  progressStripeLTR .6s linear infinite;
        -moz-animation:     progressStripeLTR .6s linear infinite;
        -ms-animation:      progressStripeLTR .6s linear infinite;
        -o-animation:       progressStripeLTR .6s linear infinite;
        animation:          progressStripeLTR .6s linear infinite;
        }

    .pro-bar-candy.candy-rtl {
        -webkit-animation:  progressStripeRTL .6s linear infinite;
        -moz-animation:     progressStripeRTL .6s linear infinite;
        -ms-animation:      progressStripeRTL .6s linear infinite;
        -o-animation:       progressStripeRTL .6s linear infinite;
        animation:          progressStripeRTL .6s linear infinite;
        }

Adding quotes to a string in VBScript

You can do like:

a="""xyz"""  
g="abcd " & a  

Or:

a=chr(34) & "xyz" & chr(34)
g="abcd " & a  

How to comment out a block of code in Python

Python does not have such a mechanism. Prepend a # to each line to block comment. For more information see PEP 8. Most Python IDEs support a mechanism to do the block-commenting-with-pound-signs automatically for you. For example, in IDLE on my machine, it's Alt+3 and Alt+4.

Don't use triple-quotes; as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.

How to change facet labels?

The labeller function defintion with variable, value as arguments would not work for me. Also if you want to use expression you need to use lapply and can not simply use arr[val], as the argument to the function is a data.frame.

This code did work:

libary(latex2exp)
library(ggplot2)
arr <- list('virginica'=TeX("x_1"), "versicolor"=TeX("x_2"), "setosa"=TeX("x_3"))
mylabel <- function(val) { return(lapply(val, function(x) arr[x])) }
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) + geom_line() + facet_wrap(~Species, labeller=mylabel)

Can't use System.Windows.Forms

You have to add the reference of the namespace : System.Windows.Forms to your project, because for some reason it is not already added, so you can add New Reference from Visual Studio menu.

Right click on "Reference" ? "Add New Reference" ? "System.Windows.Forms"

Android ImageView setImageResource in code

You can use this code:

// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];

// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...

// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
   if(countriesId[i][0].equals(countryCode))
      break;
}
// Now "i" is the index of the country

img.setImageResource(Integer.parseInt(countriesId[i][1]));

Xcode is not currently available from the Software Update server

I deleted the command tools directory given by xcode-select -p due to npm gyp error.

xcode-select failed to install the files with the not available error.

I ran the Xcode application and the command tools installed as part of the startup.

npm worked.

However this didn't fully fix the tools. I had to use xcode-select to switch the path to the Developer directory within the Xcode application directory.

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer  

MacOS catalina.

Full width layout with twitter bootstrap

Because the accepted answer isn't on the same planet as BS3, I'll share what I'm using to achieve nearly full-width capabilities.

First off, this is cheating. It's not really fluid width - but it appears to be - depending on the size of the screen viewing the site.

The problem with BS3 and fluid width sites is that they have taken this "mobile first" approach, which requires that they define every freaking screen width up to what they consider to be desktop (1200px) I'm working on a laptop with a 1900px wide screen - so I end up with 350px on either side of the content at what BS3 thinks is a desktop sized width.

They have defined 10 screen widths (really only 5, but anyway). I don't really feel comfortable changing those, because they are common widths. So, I chose to define some extra widths for BS to choose from when deciding the width of the container class.

The way I use BS is to take all of the Bootstrap provided LESS files, omit the variables.less file to provide my own, and add one of my own to the end to override the things I want to change. Within my less file, I add the following to achieve 2 common screen width settings:

@media screen and (min-width: 1600px) {
    .container {
        max-width: (1600px - @grid-gutter-width);
    }
}
@media screen and (min-width: 1900px) {
    .container {
        max-width: (1900px - @grid-gutter-width);
    }
}

These two settings set the example for what you need to do to achieve different screen widths. Here, you get full width at 1600px, and 1900px. Any less than 1600 - BS falls back to the 1200px width, then to 768px and so forth - down to phone size.

If you have larger to support, just create more @media screen statements like these. If you're building the CSS instead, you'll want to determine what gutter width was used and subtract it from your target screen width.

Update:

Bootstrap 3.0.1 and up (so far) - it's as easy as setting @container-large-desktop to 100%

Force Intellij IDEA to reread all maven dependencies

If you are using version ranges for any dependencies, make sure that IntelliJ is using Maven 3 to import the project. You can find this setting in: Settings > Maven > Importing > Use Maven3 to import project. Otherwise you may find that SNAPSHOT versions are not imported correctly.

I get Access Forbidden (Error 403) when setting up new alias

This question is old and although you managed to make it work but I feel it would be helpful if I make clear some of points you have raised here.

First about directory name having spaces. I have been playing with apache2 configuration files and I have discovered that, if the directory name has space then enclose it in double quotes and all problems disappear. For example...

    NameVirtualHost     local.webapp.org
    <VirtualHost local.webapp.org:80>
        ServerAdmin [email protected]
        DocumentRoot "E:/Project/my php webapp"
        ServerName local.webapp.org
    </VirtualHost>

Note the way DocumentRoot line is written.

Second is about Access forbidden from xampp. I found that default xampp configuration (..path to xampp/apache/httpd.conf) has a section that looks like the following.

    <Directory>
        AllowOverride none
        Require all denied
    </Directory>

Change it and make it look like below. Save the file restart apache from xampp and that solves the problem.

    <Directory>
       Options Indexes FollowSymLinks Includes ExecCGI
       AllowOverride none
       Require all granted
    </Directory>

Modify a Column's Type in sqlite3

If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.

  1. "File" - "Open Database"
  2. In the "Database Structure" tab, click on the table content (not table name), then "Edit" menu, "Modify table", and now you can change the data type of any column with a drop down menu. I changed a 'text' field to 'numeric' in order to retrieve data in a number range.

DB Browser for SQLite is open source and free. For Linux it is available from the repository.

How to get the difference between two arrays of objects in JavaScript

I think the @Cerbrus solution is spot on. I have implemented the same solution but extracted the repeated code into it's own function (DRY).

 function filterByDifference(array1, array2, compareField) {
  var onlyInA = differenceInFirstArray(array1, array2, compareField);
  var onlyInb = differenceInFirstArray(array2, array1, compareField);
  return onlyInA.concat(onlyInb);
}

function differenceInFirstArray(array1, array2, compareField) {
  return array1.filter(function (current) {
    return array2.filter(function (current_b) {
        return current_b[compareField] === current[compareField];
      }).length == 0;
  });
}

Android Reading from an Input stream efficiently

What about this. Seems to give better performance.

byte[] bytes = new byte[1000];

StringBuilder x = new StringBuilder();

int numRead = 0;
while ((numRead = is.read(bytes)) >= 0) {
    x.append(new String(bytes, 0, numRead));
}

Edit: Actually this sort of encompasses both steelbytes and Maurice Perry's

How do you set the EditText keyboard to only consist of numbers on Android?

I think you used somehow the right way to show the number only on the keyboard so better try the given line with xml in your edit text and it will work perfectly so here the code is-

  android:inputType="number"

In case any doubt you can again ask to me i'll try to completely sort out your problem. Thanks

Why are iframes considered dangerous and a security risk?

As soon as you're displaying content from another domain, you're basically trusting that domain not to serve-up malware.

There's nothing wrong with iframes per se. If you control the content of the iframe, they're perfectly safe.

How to Force New Google Spreadsheets to refresh and recalculate?

When the problem is in the recalculation of an IF condition, I add AND(ISDATE(NOW());condition) so that the cell is forced to recalculate according to what is set in the Calculation tab in Spreadsheet Settings as explained before.

This works because NOW is one of the functions that is affected by the Calculation setting and ISDATE(NOW()) always returns TRUE.

For example, in one of my sheets I had the following condition which I use to check whether a sheet with name stored in C1 is already created:

=IF(ISREF(INDIRECT(C$1&"!A1")); TRUE; FALSE)

In this case C1="February", so I expected the condition to become TRUE when a sheet with this name was created, which didn't happen. To force it to update, I changed the Calculation setting and used:

=IF(AND( ISDATE(NOW()) ; ISREF(INDIRECT(C$1&"!A1")) ); TRUE; FALSE)

PHP date() format when inserting into datetime in MySQL

A small addendum to accepted answer: If database datetime is stored as UTC (what I always do), you should use gmdate('Y-m-d H:i:s') instead of date("Y-m-d H:i:s").

Or, if you prefer to let MySQL handle everything, as some answers suggest, I would insert MySQL's UTC_TIMESTAMP, with the same result.

Note: I understood the question referring to current time.

Close Android Application

Before doing so please read this other question too:

android.os.Process.killProcess(android.os.Process.myPid());

CFNetwork SSLHandshake failed iOS 9

The device I tested at had wrong time set. So when I tried accessing a page with a certificate that would run out soon it would deny access because the device though the certificate had expired. To fix, set proper time on the device!

How to call a function from another controller in angularjs?

The best approach for you to communicate between the two controllers is to use events.

See the scope documentation

In this check out $on, $broadcast and $emit.

Why .NET String is immutable?

Just to throw this in, an often forgotten view is of security, picture this scenario if strings were mutable:

string dir = "C:\SomePlainFolder";

//Kick off another thread
GetDirectoryContents(dir);

void GetDirectoryContents(string directory)
{
  if(HasAccess(directory) {
    //Here the other thread changed the string to "C:\AllYourPasswords\"
    return Contents(directory);
  }
  return null;
}

You see how it could be very, very bad if you were allowed to mutate strings once they were passed.

Why is "forEach not a function" for this object?

If you really need to use a secure foreach interface to iterate an object and make it reusable and clean with a npm module, then use this, https://www.npmjs.com/package/foreach-object

Ex:

import each from 'foreach-object';
   
const object = {
   firstName: 'Arosha',
   lastName: 'Sum',
   country: 'Australia'
};
   
each(object, (value, key, object) => {
   console.log(key + ': ' + value);
});
   
// Console log output will be:
//      firstName: Arosha
//      lastName: Sum
//      country: Australia

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

In my case, I used the old namespace library while my project was set up making use of androidx one.

The solution was to replace android.support.design.widget.BottomNavigationView component with the right one to escape from support library: com.google.android.material.bottomnavigation.BottomNavigationView.

How to check type of variable in Java?

I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.

public class TypeTester <T extends Number>{

<T extends Object> String tester(T ToTest){

    if (ToTest instanceof Integer) return ("Integer");
    else if(ToTest instanceof Double) return ("Double");
    else if(ToTest instanceof Float) return ("Float");
    else if(ToTest instanceof String) return ("String");
    else if(ToTest.getClass().isArray()) return ("Array");
    else return ("Unsure");
}
}

I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.

public class Generics {
public static void main(String[] args) {
    int [] myArray = new int [10];

    TypeTester<Integer> callFunction = new TypeTester<Integer>();
    System.out.println(callFunction.tester(myArray));
}
}

You can swap out the myArray in the final line for say 10.2F to test Float etc

Take multiple lists into dataframe

@oopsi used pd.concat() but didn't include the column names. You could do the following, which, unlike the first solution in the accepted answer, gives you control over the column order (avoids dicts, which are unordered):

import pandas as pd
lst1 = range(100)
lst2 = range(100)
lst3 = range(100)

s1=pd.Series(lst1,name='lst1Title')
s2=pd.Series(lst2,name='lst2Title')
s3=pd.Series(lst3 ,name='lst3Title')
percentile_list = pd.concat([s1,s2,s3], axis=1)

percentile_list
Out[2]: 
    lst1Title  lst2Title  lst3Title
0           0          0          0
1           1          1          1
2           2          2          2
3           3          3          3
4           4          4          4
5           5          5          5
6           6          6          6
7           7          7          7
8           8          8          8
...

Scanner is skipping nextLine() after using next() or nextFoo()?

sc.nextLine() is better as compared to parsing the input. Because performance wise it will be good.

Get a list of URLs from a site

wget from a linux box might also be a good option as there are switches to spider and change it's output.

EDIT: wget is also available on Windows: http://gnuwin32.sourceforge.net/packages/wget.htm

How do I change the font size and color in an Excel Drop Down List?

I created a custom view that is at 100%. Use the dropdowns then click to view page layout to go back to a smaller view.

Exec : display stdout "live"

There are already several answers however none of them mention the best (and easiest) way to do this, which is using spawn and the { stdio: 'inherit' } option. It seems to produce the most accurate output, for example when displaying the progress information from a git clone.

Simply do this:

var spawn = require('child_process').spawn;

spawn('coffee', ['-cw', 'my_file.coffee'], { stdio: 'inherit' });

Credit to @MorganTouvereyQuilling for pointing this out in this comment.

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Adding/removing items from a JavaScript object with jQuery

That's not JSON at all, it's just Javascript objects. JSON is a text representation of data, that uses a subset of the Javascript syntax.

The reason that you can't find any information about manipulating JSON using jQuery is because jQuery has nothing that can do that, and it's generally not done at all. You manipulate the data in the form of Javascript objects, and then turn it into a JSON string if that is what you need. (jQuery does have methods for the conversion, though.)

What you have is simply an object that contains an array, so you can use all the knowledge that you already have. Just use data.items to access the array.

For example, to add another item to the array using dynamic values:

// The values to put in the item
var id = 7;
var name = "The usual suspects";
var type = "crime";
// Create the item using the values
var item = { id: id, name: name, type: type };
// Add the item to the array
data.items.push(item);

How do I open phone settings when a button is clicked?

Using UIApplication.openSettingsURLString

Update for Swift 5.1

 override func viewDidAppear(_ animated: Bool) {
    let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in

        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
            return
        }

        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        }
    }
    alertController.addAction(settingsAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)
}

Swift 4.2

override func viewDidAppear(_ animated: Bool) {
    let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in

        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }

        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        }
    }
    alertController.addAction(settingsAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)
}

How to Generate a random number of fixed length using JavaScript?

You can use the below code to generate a random number that will always be 6 digits:

Math.random().toString().substr(2, 6)

Hope this works for everyone :)

Briefly how this works is Math.random() generates a random number between 0 and 1 which we convert to a string and using .toString() and take a 6 digit sample from said string using .substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters.

This can be used for any length number.

If you want to do more reading on this here are some links to the docs to save you some googling:

Math.random(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

.toString(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

.substr(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

'module' object is not callable - calling method in another file

  • from a directory_of_modules, you can import a specific_module.py
  • this specific_module.py, can contain a Class with some_methods() or just functions()
  • from a specific_module.py, you can instantiate a Class or call functions()
  • from this Class, you can execute some_method()

Example:

#!/usr/bin/python3
from directory_of_modules import specific_module
instance = specific_module.DbConnect("username","password")
instance.login()

Excerpts from PEP 8 - Style Guide for Python Code:

Modules should have short and all-lowercase names.

Notice: Underscores can be used in the module name if it improves readability.

A Python module is simply a source file(*.py), which can expose:

  • Class: names using the "CapWords" convention.

  • Function: names in lowercase, words separated by underscores.

  • Global Variables: the conventions are about the same as those for Functions.

What does the ">" (greater-than sign) CSS selector mean?

All p tags with class some_class which are direct children of a div tag.

How can I find my Apple Developer Team id and Team Agent Apple ID?

For personal teams

grep DEVELOPMENT_TEAM MyProject.xcodeproj/project.pbxproj

should give you the team ID

DEVELOPMENT_TEAM = ZU88ND8437;

How to specify the actual x axis values to plot as x axis ticks in R

In case of plotting time series, the command ts.plot requires a different argument than xaxt="n"

require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))

static constructors in C++? I need to initialize private static objects

Wow, I can't believe no one mentioned the most obvious answer, and one that most closely mimics C#'s static-constructor behavior, i.e. it doesn't get called until the first object of that type is created.

std::call_once() is available in C++11; if you can't use that, it can be done with a static boolean class-variable, and a compare-and-exchange atomic-operation. In your constructor, see if you can atomically change the class-static flag from false to true, and if so, you can run the static-construction code.

For extra credit, make it a 3-way flag instead of a boolean, i.e. not run, running, and done running. Then all other instances of that class can spin-lock until the instance running the static-constructor has finished (i.e. issue a memory-fence, then set the state to "done running"). Your spin-lock should execute the processor's "pause" instruction, double the wait each time up until a threshold, etc. — pretty standard spin-locking technique.

In the absence of C++11, this should get you started.

Here's some pseudocode to guide you. Put this in your class definition:

enum EStaticConstructor { kNotRun, kRunning, kDone };
static volatile EStaticConstructor sm_eClass = kNotRun;

And this in your constructor:

while (sm_eClass == kNotRun)
{
    if (atomic_compare_exchange_weak(&sm_eClass, kNotRun, kRunning))
    {
        /* Perform static initialization here. */

        atomic_thread_fence(memory_order_release);
        sm_eClass = kDone;
    }
}
while (sm_eClass != kDone)
    atomic_pause();

Reportviewer tool missing in visual studio 2017 RC

** Update**: 11/19/2019

Microsoft has released a new version of the control 150.1400.0 in their Nuget library. My short testing shows that it works again in the forms designer where 150.1357.0 and 150.1358.0 did not. This includes being able to resize and modify the ReportViewer Tasks on the control itself.

** Update**: 8/18/2019

Removing the latest version and rolling back to 150.900.148.0 seems to work on multiple computers I'm using with VS2017 and VS2019.

You can roll back to 150.900.148 in the Nuget solution package manager. It works similarly to the previous versions. Use the drop down box to select the older version.

enter image description here

It may be easier to manually delete references to post 150.900 versions of ReportViewer and readd them than it is to fix them.

Remember to restart Visual Studio after changing the toolbox entry.

Update: 8/7/2019

A newer version of the ReportViewer control has been released, probably coinciding with Visual Studio 2019. I was working with V150.1358.0.

Following the directions in this answer gets the control in the designer's toolbox. But once dropped on the form it doesn't display. The control shows up below the form as a non-visual component.

This is working as designed according to Microsoft SQL BI support. This is the group responsible for the control.

While you still cannot interact with the control directly, these additional steps give a workaround so the control can be sized on the form. While now visible, the designer treats the control as if it didn't exist.

I've created a feedback request at the suggestion of Microsoft SQL BI support. Please consider voting on it to get Microsoft's attention.

Microsoft Azure Feedback page - Restore Designtime features of the WinForms ReportViewer Control

Additional steps:

  • After adding the reportviewer to the WinForm
  • Add a Panel Control to the WinForm.
  • In the form's form.designer.cs file, add the Reportviewer control to the panel.

      // 
      // panel1
      // 
      this.panel1.Controls.Add(this.reportViewer1);
    
  • Return to the form's designer, you should see the reportViewer on the panel

  • In the Properties panel select the ReportViewer in the controls list dropdown
  • Set the reportViewer's Dock property to Fill

Now you can position the reportViewer by actually interacting with the panel.

Update: Microsoft released a document on April 18, 2017 describing how to configure and use the reporting tool in Visual Studio 2017.

Visual Studio 2017 does not have the ReportViewer tool installed by default in the ToolBox. Installing the extension Microsoft Rdlc Report Designer for Visual Studio and then adding that to the ToolBox results in a non-visual component that appears below the form.

Microsoft Support had told me this is a bug, but as of April 21, 2017 it is "working as designed".

The following steps need to be followed for each project that requires ReportViewer.

  • If you have ReportViewer in the Toolbox, remove it. Highlight, right-click and delete.
    • You will have to have a project with a form open to do this.

Edited 8/7/2019 - It looks like the current version of the RDLC Report Designer extension no longer interferes. You need this to actually edit the reports.

  • If you have the Microsoft Rdlc Report Designer for Visual Studio extension installed, uninstall it.

  • Close your solution and restart Visual Studio. This is a crucial step, errors will occur if VS is not restarted when switching between solutions.

  • Open your solution.
  • Open the NuGet Package Manager Console (Tools/NuGet Package Manager/Package Manager Console)
  • At the PM> prompt enter this command, case matters.

    Install-Package Microsoft.ReportingServices.ReportViewerControl.WinForms

    You should see text describing the installation of the package.

Now we can temporarily add the ReportViewer tool to the tool box.

  • Right-click in the toolbox and use Choose Items...

  • We need to browse to the proper DLL that is located in the solutions Packages folder, so hit the browse button.

  • In our example we can paste in the packages folder as shown in the text of Package Manager Console.

    C:\Users\jdoe\Documents\Projects\_Test\ReportViewerTest\WindowsFormsApp1\packages

  • Then double click on the folder named Microsoft.ReportingServices.ReportViewerControl.Winforms.140.340.80

    The version number will probably change in the future.

  • Then double-click on lib and again on net40.

  • Finally, double click on the file Microsoft.ReportViewer.WinForms.dll

    You should see ReportViewer checked in the dialog. Scroll to the right and you will see the version 14.0.0.0 associated to it.

  • Click OK.

ReportViewer is now located in the ToolBox.

  • Drag the tool to the desired form(s).

  • Once completed, delete the ReportViewer tool from the tool box. You can't use it with another project.

  • You may save the project and are good to go.

Remember to restart Visual Studio any time you need to open a project with ReportViewer so that the DLL is loaded from the correct location. If you try and open a solution with a form with ReportViewer without restarting you will see errors indicating that the “The variable 'reportViewer1' is either undeclared or was never assigned.“.

If you add a new project to the same solution you need to create the project, save the solution, restart Visual Studio and then you should be able to add the ReportViewer to the form. I have seen it not work the first time and show up as a non-visual component.

When that happens, removing the component from the form, deleting the Microsoft.ReportViewer.* references from the project, saving and restarting usually works.

JPA OneToMany not deleting child

You can try this:

@OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true).

Using array map to filter results with if conditional

You're looking for the .filter() function:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  });

That'll produce an array that contains only those objects whose "selected" property is true (or truthy).

edit sorry I was getting some coffee and I missed the comments - yes, as jAndy noted in a comment, to filter and then pluck out just the "id" values, it'd be:

  $scope.appIds = $scope.applicationsHere.filter(function(obj) {
    return obj.selected;
  }).map(function(obj) { return obj.id; });

Some functional libraries (like Functional, which in my opinion doesn't get enough love) have a .pluck() function to extract property values from a list of objects, but native JavaScript has a pretty lean set of such tools.

Count immediate child div elements using jQuery

var n_numTabs = $("#superpics div").size();

or

var n_numTabs = $("#superpics div").length;

As was already said, both return the same result.
But the size() function is more jQuery "P.C".
I had a similar problem with my page.
For now on, just omit the > and it should work fine.

How to trigger the window resize event in JavaScript?

I wasn't actually able to get this to work with any of the above solutions. Once I bound the event with jQuery then it worked fine as below:

$(window).bind('resize', function () {
    resizeElements();
}).trigger('resize');

Accessing the web page's HTTP Headers in JavaScript

Another way to send header information to JavaScript would be through cookies. The server can extract whatever data it needs from the request headers and send them back inside a Set-Cookie response header — and cookies can be read in JavaScript. As keparo says, though, it's best to do this for just one or two headers, rather than for all of them.