Programs & Examples On #Concurrent collections

Alphabet range in Python

If you are looking to an equivalent of letters[1:10] from R, you can use:

import string
list(string.ascii_lowercase[0:10])

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

How do I protect Python code?

Idea of having time restricted license and check for it in locally installed program will not work. Even with perfect obfuscation, license check can be removed. However if you check license on remote system and run significant part of the program on your closed remote system, you will be able to protect your IP.

Preventing competitors from using the source code as their own or write their inspired version of the same code, one way to protect is to add signatures to your program logic (some secrets to be able to prove that code was stolen from you) and obfuscate the python source code so, it's hard to read and utilize.

Good obfuscation adds basically the same protection to your code, that compiling it to executable (and stripping binary) does. Figuring out how obfuscated complex code works might be even harder than actually writing your own implementation.

This will not help preventing hacking of your program. Even with obfuscation code license stuff will be cracked and program may be modified to have slightly different behaviour (in the same way that compiling code to binary does not help protection of native programs).

In addition to symbol obfuscation might be good idea to unrefactor the code, which makes everything even more confusing if e.g. call graphs points to many different places even if actually those different places does eventually the same thing.

Logical signature inside obfuscated code (e.g. you may create table of values which are used by program logic, but also used as signature), which can be used to determine that code is originated from you. If someone decides to use your obfuscated code module as part of their own product (even after reobfuscating it to make it seem different) you can show, that code is stolen with your secret signature.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

get UTC timestamp in python with datetime

Another possibility is:

d = datetime.datetime.utcnow()
epoch = datetime.datetime(1970,1,1)
t = (d - epoch).total_seconds()

This works as both "d" and "epoch" are naive datetimes, making the "-" operator valid, and returning an interval. total_seconds() turns the interval into seconds. Note that total_seconds() returns a float, even d.microsecond == 0

Create a data.frame with m columns and 2 rows

For completeness:

Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

EDIT: speed test data.frame vs. as.data.frame

system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  8.005   0.108   8.165 

system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  3.759   0.048   3.802 

Yes, it appears to be faster (by about 2 times).

How to convert milliseconds into human readable form?

You should use the datetime functions of whatever language you're using, but, just for fun here's the code:

int milliseconds = someNumber;

int seconds = milliseconds / 1000;

int minutes = seconds / 60;

seconds %= 60;

int hours = minutes / 60;

minutes %= 60;

int days = hours / 24;

hours %= 24;

What does Docker add to lxc-tools (the userspace LXC tools)?

The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.

LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.

LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.

Key features of LXD are:

  • Secure by design (unprivileged containers, resource restrictions and much more)
  • Scalable (from containers on your laptop to thousand of compute nodes)
  • Intuitive (simple, clear API and crisp command line experience)
  • Image based (no more distribution templates, only good, trusted images) Live migration

There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.

However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.

The OpenStack nclxd plugin a list of features supported include:

stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support

By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.

How can I format a list to print each element on a separate line in python?

Embrace the future! Just to be complete, you can also do this the Python 3k way by using the print function:

from __future__ import print_function  # Py 2.6+; In Py 3k not needed

mylist = ['10', 12, '14']    # Note that 12 is an int

print(*mylist,sep='\n')

Prints:

10
12
14

Eventually, print as Python statement will go away... Might as well start to get used to it.

libxml install error using pip

I was having this issue with a pip install of lxml. My CentOS instance was using python 2.6 which was throwing this error.

To get around this I did the following to run with Python 2.7:

  1. Run: sudo yum install python-devel
  2. Run sudo yum install libxslt-devel libxml2-devel
  3. Use Python 2.7 to run your command by using /usr/bin/python2.7 YOUR_PYTHON_COMMAND (For me it was /usr/bin/python2.7 -m pip install lxml)

Check if Internet Connection Exists with jQuery?

5 years later-version:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.

How to format a JavaScript date

I think you can just use the non-standard Date method toLocaleFormat(formatString)

formatString: A format string in the same format expected by the strftime() function in C.

var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011

References:

Changing :hover to touch/click for mobile devices

A CSS only solution for those who are having trouble with mobile touchscreen button styling.

This will fix your hover-stick / active button problems.

_x000D_
_x000D_
body, html {
  width: 600px;
}
p {
  font-size: 20px;
}

button {
  border: none;
  width: 200px;
  height: 60px;
  border-radius: 30px;
  background: #00aeff;
  font-size: 20px;
}

button:active {
  background: black;
  color: white;
}

.delayed {
  transition: all 0.2s;
  transition-delay: 300ms;
}

.delayed:active {
  transition: none;
}
_x000D_
<h1>Sticky styles for better touch screen buttons!</h1>

<button>Normal button</button>

<button class="delayed"><a href="https://www.google.com"/>Delayed style</a></button>

<p>The CSS :active psuedo style is displayed between the time when a user touches down (when finger contacts screen) on a element to the time when the touch up (when finger leaves the screen) occures.   With a typical touch-screen tap interaction, the time of which the :active psuedo style is displayed can be very small resulting in the :active state not showing or being missed by the user entirely.  This can cause issues with users not undertanding if their button presses have actually reigstered or not.</p>

<p>Having the the :active styling stick around for a few hundred more milliseconds after touch up would would improve user understanding when they have interacted with a button.</p>
_x000D_
_x000D_
_x000D_

When to use @QueryParam vs @PathParam

I personally used the approach of "if it makes sense for the user to bookmark a URLwhich includes these parameters then use PathParam".

For instance, if the URL for a user profile includes some profile id parameter, since this can be bookmarked by the user and/or emailed around, I would include that profile id as a path parameter. Also, another considerent to this is that the page denoted by the URL which includes the path param doesn't change -- the user will set up his/her profile, save it, and then unlikely to change that much from there on; this means webcrawlers/search engines/browsers/etc can cache this page nicely based on the path.

If a parameter passed in the URL is likely to change the page layout/content then I'd use that as a queryparam. For instance, if the profile URL supports a parameter which specifies whether to show the user email or not, I would consider that to be a query param. (I know, arguably, you could say that the &noemail=1 or whatever parameter it is can be used as a path param and generates 2 separate pages -- one with the email on it, one without it -- but logically that's not the case: it is still the same page with or without certain attributes shown.

Hope this helps -- I appreciate the explanation might be a bit fuzzy :)

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.

import timeit

setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''

timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)

Results:

1.1214002349999777 s  # WouterOvermeire
1.1922008498571748 s  # Jeff
1.7034366211428602 s  # Kikohs

Re-render React component when prop changes

ComponentWillReceiveProps() is going to be deprecated in the future due to bugs and inconsistencies. An alternative solution for re-rendering a component on props change is to use ComponentDidUpdate() and ShouldComponentUpdate().

ComponentDidUpdate() is called whenever the component updates AND if ShouldComponentUpdate() returns true (If ShouldComponentUpdate() is not defined it returns true by default).

shouldComponentUpdate(nextProps){
    return nextProps.changedProp !== this.state.changedProp;
}

componentDidUpdate(props){
    // Desired operations: ex setting state
}

This same behavior can be accomplished using only the ComponentDidUpdate() method by including the conditional statement inside of it.

componentDidUpdate(prevProps){
    if(prevProps.changedProp !== this.props.changedProp){
        this.setState({          
            changedProp: this.props.changedProp
        });
    }
}

If one attempts to set the state without a conditional or without defining ShouldComponentUpdate() the component will infinitely re-render

How to check if a variable is null or empty string or all whitespace in JavaScript?

When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:

function isNullOrWhiteSpace(str){
    return str == null || str.replace(/\s/g, '').length < 1;
}

Unsafe JavaScript attempt to access frame with URL

Crossframe-Scripting is not possible when the two frames have different domains -> Security.

See this: http://javascript.about.com/od/reference/a/frame3.htm

Now to answer your question: there is no solution or work around, you simply should check your website-design why there must be two frames from different domains that changes the url of the other one.

Increasing heap space in Eclipse: (java.lang.OutOfMemoryError)

In the Eclipse download folder make the entries in the eclipse.ini file :

--launcher.XXMaxPermSize
512M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms512m
-Xmx1024m

or what ever values you want.

Best approach to remove time part of datetime in SQL Server

For me the code below is always a winner:

SELECT CONVERT(DATETIME, FLOOR(CONVERT(FLOAT,GETDATE())));

Android Studio: Default project directory

I found an easy way:

  1. Open a new project;
  2. Change the project location name by typing and not the Browse... button;
  3. The Next button will appear now.

How to print a double with two decimals in Android?

Before you use DecimalFormat you need to use the following import or your code will not work:

import java.text.DecimalFormat;

The code for formatting is:

DecimalFormat precision = new DecimalFormat("0.00"); 
// dblVariable is a number variable and not a String in this case
txtTextField.setText(precision.format(dblVariable));

How to make a radio button unchecked by clicking it?

Unfortunately it does not work in Chrome or Edge, but it does work in FireFox:

$(document)
// uncheck it when clicked
.on("click","input[type='radio']", function(){ $(this).prop("checked",false); })
// re-check it if value is changed to this input
.on("change","input[type='radio']", function(){ $(this).prop("checked",true); });

Check play state of AVPlayer

Swift extension based on the answer by maz

extension AVPlayer {

    var isPlaying: Bool {
        return ((rate != 0) && (error == nil))
    }
}

Segmentation fault on large array sizes

You're probably just getting a stack overflow here. The array is too big to fit in your program's stack address space.

If you allocate the array on the heap you should be fine, assuming your machine has enough memory.

int* array = new int[1000000];

But remember that this will require you to delete[] the array. A better solution would be to use std::vector<int> and resize it to 1000000 elements.

UIScrollView not scrolling

If your scrollView is a subview of a containerView of some type, then make sure that your scrollView is within the frame or bounds of the containerView. I had containerView.clipsToBounds = NO which still allowed me see the scrollView, but because scrollView wasn't within the bounds of containerView it wouldn't detect touch events.

For example:

containerView.frame = CGRectMake(0, 0, 200, 200);
scrollView.frame = CGRectMake(0, 200, 200, 200);
[containerView addSubview:scrollView];
scrollView.userInteractionEnabled = YES;

You will be able to see the scrollView but it won't receive user interactions.

Rails 3 migrations: Adding reference column?

If you are using the Rails 4.x you can now generate migrations with references, like this:

rails generate migration AddUserRefToProducts user:references

like you can see on rails guides

How to print a certain line of a file with PowerShell?

To reduce memory consumption and to speed up the search you may use -ReadCount option of Get-Content cmdlet (https://technet.microsoft.com/ru-ru/library/hh849787.aspx).

This may save hours when you working with large files.

Here is an example:

$n = 60699010
$src = 'hugefile.csv'
$batch = 100
$timer = [Diagnostics.Stopwatch]::StartNew()

$count = 0
Get-Content $src -ReadCount $batch -TotalCount $n | %  { 
    $count += $_.Length
    if ($count -ge $n ) {
        $_[($n - $count + $_.Length - 1)]
    }
}

$timer.Stop()
$timer.Elapsed

This prints $n'th line and elapsed time.

Java URLConnection Timeout

You can manually force disconnection by a Thread sleep. This is an example:

URLConnection con = url.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
new Thread(new InterruptThread(con)).start();

then

public class InterruptThread implements Runnable {

    HttpURLConnection con;
    public InterruptThread(HttpURLConnection con) {
        this.con = con;
    }

    public void run() {
        try {
            Thread.sleep(5000); // or Thread.sleep(con.getConnectTimeout())
        } catch (InterruptedException e) {

        }
        con.disconnect();
        System.out.println("Timer thread forcing to quit connection");
    }
}

ActiveModel::ForbiddenAttributesError when creating new user

There is an easier way to avoid the Strong Parameters at all, you just need to convert the parameters to a regular hash, as:

unlocked_params = ActiveSupport::HashWithIndifferentAccess.new(params)

model.create!(unlocked_params)

This defeats the purpose of strong parameters of course, but if you are in a situation like mine (I'm doing my own management of allowed params in another part of my system) this will get the job done.

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

Drop all tables command

I don't think you can drop all tables in one hit but you can do the following to get the commands:

select 'drop table ' || name || ';' from sqlite_master
    where type = 'table';

The output of this is a script that will drop the tables for you. For indexes, just replace table with index.

You can use other clauses in the where section to limit which tables or indexes are selected (such as "and name glob 'pax_*'" for those starting with "pax_").

You could combine the creation of this script with the running of it in a simple bash (or cmd.exe) script so there's only one command to run.

If you don't care about any of the information in the DB, I think you can just delete the file it's stored in off the hard disk - that's probably faster. I've never tested this but I can't see why it wouldn't work.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I recommended an experimental new attribute CSS I tested on latest browser and it's good:

image-rendering: optimizeSpeed;             /*                     */
image-rendering: -moz-crisp-edges;          /* Firefox             */
image-rendering: -o-crisp-edges;            /* Opera               */
image-rendering: -webkit-optimize-contrast; /* Chrome (and Safari) */
image-rendering: optimize-contrast;         /* CSS3 Proposed       */
-ms-interpolation-mode: nearest-neighbor;   /* IE8+                */

With this the browser will know the algorithm for rendering

Automatically get loop index in foreach loop in Perl

autobox::Core provides, among many more things, a handy for method:

use autobox::Core;

['a'..'z']->for( sub{
    my ($index, $value) = @_;
    say "$index => $value";
});

Alternatively, have a look at an iterator module, for example: Array::Iterator

use Array::Iterator;

my $iter = Array::Iterator->new( ['a'..'z'] );
while ($iter->hasNext) {
    $iter->getNext;
    say $iter->currentIndex . ' => ' . $iter->current;
}

Also see:

Set database from SINGLE USER mode to MULTI USER

I googled for the solution for a while and finally came up with the below solution,

SSMS in general uses several connections to the database behind the scenes.

You will need to kill these connections before changing the access mode.(I have done it with EXEC(@kill); in the code template below.)

Then,

Run the following SQL to set the database in MULTI_USER mode.

USE master
GO
DECLARE @kill varchar(max) = '';
SELECT @kill = @kill + 'KILL ' + CONVERT(varchar(10), spid) + '; '
FROM master..sysprocesses 
WHERE spid > 50 AND dbid = DB_ID('<Your_DB_Name>')
EXEC(@kill);

GO
SET DEADLOCK_PRIORITY HIGH
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH NO_WAIT
ALTER DATABASE [<Your_DB_Name>] SET MULTI_USER WITH ROLLBACK IMMEDIATE
GO

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

ALTER DATABASE [<Your_DB_Name>] SET SINGLE_USER

This should work. Happy coding!!

Thanks!!

C Macro definition to determine big endian or little endian machine?

You can in fact access the memory of a temporary object by using a compound literal (C99):

#define IS_LITTLE_ENDIAN (1 == *(unsigned char *)&(const int){1})

Which GCC will evaluate at compile time.

How to toggle (hide / show) sidebar div using jQuery

$(document).ready(function () {
    $(".trigger").click(function () {
        $("#sidebar").toggle("fast");
        $("#sidebar").toggleClass("active");
        return false;
    });
});


<div>
    <a class="trigger" href="#">
        <img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
    </a>
</div>
<div id="sidebar">
</div>

Instead #sidebar give the id of ur div.

Convert timestamp to string

try this

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String string  = dateFormat.format(new Date());
System.out.println(string);

you can create any format see this

Trying to create a file in Android: open failed: EROFS (Read-only file system)

I have tried this with and without the WRITE_INTERNAL_STORAGE permission.

There is no WRITE_INTERNAL_STORAGE permission in Android.

How do I create this file for writing?

You don't, except perhaps on a rooted device, if your app is running with superuser privileges. You are trying to write to the root of internal storage, which apps do not have access to.

Please use the version of the FileOutputStream constructor that takes a File object. Create that File object based off of some location that you can write to, such as:

  • getFilesDir() (called on your Activity or other Context)
  • getExternalFilesDir() (called on your Activity or other Context)

The latter will require WRITE_EXTERNAL_STORAGE as a permission.

Is there an easier way than writing it to a file then reading from it again?

You can temporarily put it in a static data member.

because many people don't have SD card slots

"SD card slots" are irrelevant, by and large. 99% of Android device users will have external storage -- the exception will be 4+ year old devices where the user removed their SD card. Devices manufactured since mid-2010 have external storage as part of on-board flash, not as removable media.

How to determine total number of open/active connections in ms sql server 2005

As @jwalkerjr mentioned, you should be disposing of connections in code (if connection pooling is enabled, they are just returned to the connection pool). The prescribed way to do this is using the 'using' statement:

// Execute stored proc to read data from repository
using (SqlConnection conn = new SqlConnection(this.connectionString))
{
    using (SqlCommand cmd = conn.CreateCommand())
    {
        cmd.CommandText = "LoadFromRepository";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", fileID);

        conn.Open();
        using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
        {
            if (rdr.Read())
            {
                filename = SaveToFileSystem(rdr, folderfilepath);
            }
        }
    }
}

How to convert JSON to XML or XML to JSON?

Thanks for David Brown's answer. In my case of JSON.Net 3.5, the convert methods are under the JsonConvert static class:

XmlNode myXmlNode = JsonConvert.DeserializeXmlNode(myJsonString); // is node not note
// or .DeserilizeXmlNode(myJsonString, "root"); // if myJsonString does not have a root
string jsonString = JsonConvert.SerializeXmlNode(myXmlNode);

Linq on DataTable: select specific column into datatable, not whole table

If you already know beforehand how many columns your new DataTable would have, you can do something like this:

DataTable matrix = ... // get matrix values from db

DataTable newDataTable = new DataTable();
newDataTable.Columns.Add("c_to", typeof(string));
newDataTable.Columns.Add("p_to", typeof(string));

var query = from r in matrix.AsEnumerable()
            where r.Field<string>("c_to") == "foo" &&
                    r.Field<string>("p_to") == "bar"
            let objectArray = new object[]
            {
                r.Field<string>("c_to"), r.Field<string>("p_to")
            }
            select objectArray;

foreach (var array in query)
{
    newDataTable.Rows.Add(array);
}

How do I parse a YAML file in Ruby?

Maybe I'm missing something, but why try to parse the file? Why not just load the YAML and examine the object(s) that result?

If your sample YAML is in some.yml, then this:

require 'yaml'
thing = YAML.load_file('some.yml')
puts thing.inspect

gives me

{"javascripts"=>[{"fo_global"=>["lazyload-min", "holla-min"]}]}

How to Resize a Bitmap in Android?

profileImage.setImageBitmap(
    Bitmap.createScaledBitmap(
        BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length), 
        80, 80, false
    )
);

Google Map API v3 ~ Simply Close an infowindow?

I was having a similar issue. I simply added the following to my code:

closeInfoWindow = function() {
    infoWindow.close();
};

google.maps.event.addListener(map, 'click', closeInfoWindow);

The full js code is (the code above is about 15 lines from the bottom):

jQuery(window).load(function() {
if (jQuery("#map_canvas").length > 0){
    googlemap();
}
});

function googlemap() {

jQuery('#map_canvas').css({'height': '400px'});

// Create the map 
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map_canvas"), {
  mapTypeId: google.maps.MapTypeId.ROADMAP,
  streetViewControl: false
});

// Create the shared infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("div");
var title = document.createElement("div");
var boxText = document.createElement("div");

var myOptions = {
         content: boxText
        ,disableAutoPan: false
        ,maxWidth: 0
        ,pixelOffset: new google.maps.Size(-117,-200)
        ,zIndex: null
        ,boxStyle: { 
          background: "url('"+siteRoot+"images/house-icon-flat.png') no-repeat"
          ,opacity: 1
          ,width: "236px"
          ,height: "300px"
         }
        ,closeBoxMargin: "10px 0px 2px 2px"
        ,closeBoxURL: "http://kdev.langley.com/wp-content/themes/langley/images/close.gif"
        ,infoBoxClearance: new google.maps.Size(1, 1)
        ,isHidden: false
        ,pane: "floatPane"
        ,enableEventPropagation: false
};


var infoWindow = new InfoBox(myOptions);
var MarkerImage = siteRoot+'images/house-web-marker.png';

// Create the markers
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lat, data.lng),
        map: map,
        title: data.title,
        content: data.html,
        icon: MarkerImage
    });
    google.maps.event.addListener(marker, "click", function() {
        infoWindow.open(map, this);         
        title.innerHTML = marker.getTitle();
        infoWindow.setContent(marker.content);
        infoWindow.open(map, marker);
        jQuery(".innerinfo").parent().css({'overflow':'hidden', 'margin-right':'10px'});            
    });
}

// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
    var data = markers[index];
    bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
var origcent = new google.maps.LatLng(map.getCenter());
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.

closeInfoWindow = function() {
        infoWindow.close();
    };

google.maps.event.addListener(map, 'click', closeInfoWindow);

google.maps.event.addListener(infoWindow, 'closeclick', function()
{
    centermap();
});

function centermap()
{
    map.setCenter(map.fitBounds(bounds));
}
}

jQuery(window).resize(function() {
googlemap();
});

How to get rid of underline for Link component of React Router?

I think the best way to use react-router-dom Link in a MenuItem (and other MaterialUI component such as buttons) is to pass the Link in the "component" prop

<Menu>
   <MenuItem component={Link} to={'/first'}>Team 1</MenuItem>
   <MenuItem component={Link} to={'/second'}>Team 2</MenuItem>
</Menu>

you need to pass the route path in the 'to' prop of the "MenuItem" (which will be passed down to the Link component). In this way you don't need to add any style as it will use the MenuItem style

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

How are you running the application? Are you just hitting the website or are you building and running from within Visual Studio? If you are building and running you may want to tell it to use the local IIS web server. This would make sure it is using the App Pool you have set up to run with v4.0/integrated.

I am guessing that it is using the Visual Studio Development Server when running. This server is probably trying to run with the 2.0 framework. This then causes your error to be thrown.

Edit: To note, I normally just build my website application and then I attach to process w3wp when I want to debug. I do not use the publishing tool. Of course this means my local working directory is within the web root.

Rerouting stdin and stdout from C

This is the most readily available, handy and useful way to do

freopen("dir","r",stdin);

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

How to edit one specific row in Microsoft SQL Server Management Studio 2008?

How to edit one specific row/tuple in Server Management Studio 2008/2012/2014/2016

Step 1: Right button mouse > Select "Edit Top 200 Rows"

Edit top 200 rows

Step 2: Navigate to Query Designer > Pane > SQL (Shortcut: Ctrl+3)

Navigate to Query Designer > Pane > SQL

Step 3: Modify the query

Modify the query

Step 4: Right button mouse > Select "Execute SQL" (Shortcut: Ctrl+R)

enter image description here

How to use table variable in a dynamic sql statement?

Well, I figured out the way and thought to share with the people out there who might run into the same problem.

Let me start with the problem I had been facing,

I had been trying to execute a Dynamic Sql Statement that used two temporary tables I declared at the top of my stored procedure, but because that dynamic sql statment created a new scope, I couldn't use the temporary tables.

Solution:

I simply changed them to Global Temporary Variables and they worked.

Find my stored procedure underneath.

CREATE PROCEDURE RAFCustom_Room_GetRelatedProducts
-- Add the parameters for the stored procedure here
@PRODUCT_SKU nvarchar(15) = Null

AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;

IF OBJECT_ID('tempdb..##RelPro', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##RelPro
END

Create Table ##RelPro
(
    RowID int identity(1,1),
    ID int,
    Item_Name nvarchar(max),
    SKU nvarchar(max),
    Vendor nvarchar(max),
    Product_Img_180 nvarchar(max),
    rpGroup int,
    Assoc_Item_1 nvarchar(max),
    Assoc_Item_2 nvarchar(max),
    Assoc_Item_3 nvarchar(max),
    Assoc_Item_4 nvarchar(max),
    Assoc_Item_5 nvarchar(max),
    Assoc_Item_6 nvarchar(max),
    Assoc_Item_7 nvarchar(max),
    Assoc_Item_8 nvarchar(max),
    Assoc_Item_9 nvarchar(max),
    Assoc_Item_10 nvarchar(max)
);

Begin
    Insert ##RelPro(ID, Item_Name, SKU, Vendor, Product_Img_180, rpGroup)

    Select distinct zp.ProductID, zp.Name, zp.SKU,
        (Select m.Name From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID),
        'http://s0001.server.com/is/sw11/DG/' + 
        (Select m.Custom1 From ZNodeManufacturer m(nolock) Where m.ManufacturerID = zp.ManufacturerID) +
        '_' + zp.SKU + '_3?$SC_3243$', ep.RoomID
    From Product zp(nolock) Inner Join RF_ExtendedProduct ep(nolock) On ep.ProductID = zp.ProductID
    Where zp.ActiveInd = 1 And SUBSTRING(zp.SKU, 1, 2) <> 'GC' AND zp.Name <> 'PLATINUM' AND zp.SKU = (Case When @PRODUCT_SKU Is Not Null Then @PRODUCT_SKU Else zp.SKU End)
End

declare @curr_row int = 0,
        @tot_rows int= 0,
        @sku nvarchar(15) = null;

IF OBJECT_ID('tempdb..##TSku', 'U') IS NOT NULL
BEGIN
    DROP TABLE ##TSku
END
Create Table ##TSku (tid int identity(1,1), relsku nvarchar(15));

Select @curr_row = (Select MIN(RowId) From ##RelPro);
Select @tot_rows = (Select MAX(RowId) From ##RelPro);

while @curr_row <= @tot_rows
Begin
    select @sku = SKU from ##RelPro where RowID = @curr_row;

    truncate table ##TSku;

    Insert ##TSku(relsku)
    Select distinct top(10) tzp.SKU From Product tzp(nolock) INNER JOIN 
    [INTRANET].raf_FocusAssociatedItem assoc(nolock) ON assoc.associatedItemID = tzp.SKU
    Where (assoc.isActive=1) And (tzp.ActiveInd = 1) AND (assoc.productID = @sku)

    declare @curr_row1 int = (Select Min(tid) From ##TSku),
            @tot_rows1 int = (Select Max(tid) From ##TSku);

    If(@tot_rows1 <> 0)
    Begin
        While @curr_row1 <= @tot_rows1
        Begin
            declare @col_name nvarchar(15) = null,
                    @sqlstat nvarchar(500) = null;
            set @col_name =  'Assoc_Item_' + Convert(nvarchar(2), @curr_row1);
            set @sqlstat = 'update ##RelPro set ' + @col_name + ' = (Select relsku From ##TSku Where tid = ' + Convert(nvarchar(2), @curr_row1) + ') Where RowID = ' + Convert(nvarchar(2), @curr_row);
            Exec(@sqlstat);
            set @curr_row1 = @curr_row1 + 1;
        End
    End
    set @curr_row = @curr_row + 1;
End

Select * From ##RelPro;

END GO

How to use Class<T> in Java?

Using the generified version of class Class allows you, among other things, to write things like

Class<? extends Collection> someCollectionClass = someMethod();

and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.

Difference between BYTE and CHAR in column datatypes

I am not sure since I am not an Oracle user, but I assume that the difference lies when you use multi-byte character sets such as Unicode (UTF-16/32). In this case, 11 Bytes could account for less than 11 characters.

Also those field types might be treated differently in regard to accented characters or case, for example 'binaryField(ete) = "été"' will not match while 'charField(ete) = "été"' might (again not sure about Oracle).

Restrict varchar() column to specific values?

When you are editing a table
Right Click -> Check Constraints -> Add -> Type something like Frequency IN ('Daily', 'Weekly', 'Monthly', 'Yearly') in expression field and a good constraint name in (Name) field.
You are done.

Disposing WPF User Controls

An UserControl has a Destructor, why don't you use that?

~MyWpfControl()
    {
        // Dispose of any Disposable items here
    }

Deleting rows from parent and child tables

Here's a complete example of how it can be done. However you need flashback query privileges on the child table.

Here's the setup.

create table parent_tab
  (parent_id number primary key,
  val varchar2(20));

create table child_tab
    (child_id number primary key,
    parent_id number,
    child_val number,
     constraint child_par_fk foreign key (parent_id) references parent_tab);

insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');

insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);

commit;

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).

delete from child_tab where child_val = 100;

Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab

delete from parent_tab
where parent_id in
  (select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
  minus
  select parent_id from child_tab);

'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)

select * from parent_tab
where parent_id not in (select parent_id from child_tab);

select * from parent_tab;

It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.

Insert/Update/Delete with function in SQL Server

You can't update tables from a function like you would a stored procedure, but you CAN update table variables.

So for example, you can't do this in your function:

create table MyTable
(
    ID int,
    column1 varchar(100)
)
update [MyTable]
set column1='My value'

but you can do:

declare @myTable table
(
    ID int,
    column1 varchar(100)
)

Update @myTable
set column1='My value'

How to run wget inside Ubuntu Docker image?

You need to install it first. Create a new Dockerfile, and install wget in it:

FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:

docker build -t my-ubuntu .

Finally, run it:

docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

How to securely save username/password (local)?

DPAPI is just for this purpose. Use DPAPI to encrypt the password the first time the user enters is, store it in a secure location (User's registry, User's application data directory, are some choices). Whenever the app is launched, check the location to see if your key exists, if it does use DPAPI to decrypt it and allow access, otherwise deny it.

why should I make a copy of a data frame in pandas

Assumed you have data frame as below

df1
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

When you would like create another df2 which is identical to df1, without copy

df2=df1
df2
     A    B    C    D
4 -1.0 -1.0 -1.0 -1.0
5 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0
6 -1.0 -1.0 -1.0 -1.0

And would like modify the df2 value only as below

df2.iloc[0,0]='changed'

df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

At the same time the df1 is changed as well

df1
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Since two df as same object, we can check it by using the id

id(df1)
140367679979600
id(df2)
140367679979600

So they as same object and one change another one will pass the same value as well.


If we add the copy, and now df1 and df2 are considered as different object, if we do the same change to one of them the other will not change.

df2=df1.copy()
id(df1)
140367679979600
id(df2)
140367674641232

df1.iloc[0,0]='changedback'
df2
         A    B    C    D
4  changed -1.0 -1.0 -1.0
5       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0
6       -1 -1.0 -1.0 -1.0

Good to mention, when you subset the original dataframe, it is safe to add the copy as well in order to avoid the SettingWithCopyWarning

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

Is there a function in python to split a word into a list?

def count(): list = 'oixfjhibokxnjfklmhjpxesriktglanwekgfvnk'

word_list = []
# dict = {}
for i in range(len(list)):
    word_list.append(list[i])
# word_list1 = sorted(word_list)
for i in range(len(word_list) - 1, 0, -1):
    for j in range(i):
        if word_list[j] > word_list[j + 1]:
            temp = word_list[j]
            word_list[j] = word_list[j + 1]
            word_list[j + 1] = temp
print("final count of arrival of each letter is : \n", dict(map(lambda x: (x, word_list.count(x)), word_list)))

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

HTML

  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on

Typescript

currentLesson:string;

  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]

constructor(){
  this.currentLesson=this.classes[0].currentLesson
}

DEMO

Putting everything in a loop:

HTML

<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>
</div>

Typescript

currentLesson:string;

classes = [
{
  name: 'Lesson1',
  level: 1,
  code: 1,
},{
  name: 'Lesson2',
  level: 1,
  code: 2,
},
{
  name: 'Lesson3',
  level: 2,
  code: 3,
}]

DEMO

Stop an input field in a form from being submitted

I just wanted to add an additional option: In your input add the form tag and specify the name of a form that doesn't exist on your page:

<input form="fakeForm" type="text" readonly value="random value" />

Android emulator: How to monitor network traffic?

You can monitor network traffic from Android Studio. Go to Android Monitor and open Network tab.

http://developer.android.com/tools/debugging/ddms.html

UPDATE: ?? Android Device Monitor was deprecated in Android Studio 3.1. See more in https://developer.android.com/studio/profile/monitor

How can I load Partial view inside the view?

I had exactly the same problem as Leniel. I tried fixes suggested here and a dozen other places. The thing that finally worked for me was simply adding

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")

to my layout...

How to get size in bytes of a CLOB column in Oracle?

The simple solution is to cast CLOB to BLOB and then request length of BLOB !

The problem is that Oracle doesn't have a function that cast CLOB to BLOB, but we can simply define a function to do that

create or replace
FUNCTION clob2blob (p_in clob) RETURN blob IS 
    v_blob        blob;
    v_desc_offset PLS_INTEGER := 1;
    v_src_offset  PLS_INTEGER := 1;
    v_lang        PLS_INTEGER := 0;
    v_warning     PLS_INTEGER := 0;  
BEGIN
    dbms_lob.createtemporary(v_blob,TRUE);
    dbms_lob.converttoblob
        ( v_blob
        , p_in
        , dbms_lob.getlength(p_in)
        , v_desc_offset
        , v_src_offset
        , dbms_lob.default_csid
        , v_lang
        , v_warning
        );
    RETURN v_blob;
END;

The SQL command to use to obtain number of bytes is

SELECT length(clob2blob(fieldname)) as nr_bytes 

or

SELECT dbms_lob.getlength(clob2blob(fieldname)) as nr_bytes

I have tested this on Oracle 10g without using Unicode(UTF-8). But I think that this solution must be correct using Unicode(UTF-8) Oracle instance :-)

I want render thanks to Nashev that has posted a solution to convert clob to blob How convert CLOB to BLOB in Oracle? and to this post written in german (the code is in PL/SQL) 13ter.info.blog that give additionally a function to convert blob to clob !

Can somebody test the 2 commands in Unicode(UTF-8) CLOB so I'm sure that this works with Unicode ?

Making a div vertically scrollable using CSS

Try like this.

_x000D_
_x000D_
<div style="overflow-y: scroll; height:400px;">
_x000D_
_x000D_
_x000D_

Free ASP.Net and/or CSS Themes

I have used Open source Web Design in the past. They have quite a few css themes, don't know about ASP.Net

Command line tool to dump Windows DLL version?

You can write a VBScript script to get the file version info:

VersionInfo.vbs

set args = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetFileVersion(args(0))
Wscript.Quit

You can call this from the command line like this:

cscript //nologo VersionInfo.vbs C:\Path\To\MyFile.dll

Why is nginx responding to any domain name?

To answer your question - nginx picks the first server if there's no match. See documentation:

If its value does not match any server name, or the request does not contain this header field at all, then nginx will route the request to the default server for this port. In the configuration above, the default server is the first one...

Now, if you wanted to have a default catch-all server that, say, responds with 404 to all requests, then here's how to do it:

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name _;
    ssl_certificate <path to cert>
    ssl_certificate_key <path to key>
    return 404;
}

Note that you need to specify certificate/key (that can be self-signed), otherwise all SSL connections will fail as nginx will try to accept connection using this default_server and won't find cert/key.

How can I clear the content of a file?

The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.

Login with facebook android sdk app crash API 4

The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):

Mikhail,

The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.

Good luck with your implementation.

How to concat a string to xsl:value-of select="...?

You can use the rather sensibly named xpath function called concat here

<a>
   <xsl:attribute name="href">
      <xsl:value-of select="concat('myText:', /*/properties/property[@name='report']/@value)" />
   </xsl:attribute>
</a>  

Of course, it doesn't have to be text here, it can be another xpath expression to select an element or attribute. And you can have any number of arguments in the concat expression.

Do note, you can make use of Attribute Value Templates (represented by the curly braces) here to simplify your expression

<a href="{concat('myText:', /*/properties/property[@name='report']/@value)}"></a>

How can I confirm a database is Oracle & what version it is using SQL?

Here's a simple function:

CREATE FUNCTION fn_which_edition
        RETURN VARCHAR2
    IS

    /*

        Purpose: determine which database edition

        MODIFICATION HISTORY
        Person      Date        Comments
        ---------   ------      -------------------------------------------
        dcox        6/6/2013    Initial Build

    */

    -- Banner
    CURSOR c_get_banner
    IS
        SELECT banner
          FROM v$version
         WHERE UPPER(banner) LIKE UPPER('Oracle Database%');

    vrec_banner c_get_banner%ROWTYPE; -- row record
    v_database VARCHAR2(32767); --

BEGIN
    -- Get banner to get edition
    OPEN c_get_banner;
    FETCH c_get_banner INTO vrec_banner;
    CLOSE c_get_banner;

    -- Check for Database type
    IF INSTR( UPPER(vrec_banner.banner), 'EXPRESS') > 0
    THEN
        v_database := 'EXPRESS';
    ELSIF INSTR( UPPER(vrec_banner.banner), 'STANDARD') > 0
    THEN
        v_database := 'STANDARD';
    ELSIF INSTR( UPPER(vrec_banner.banner), 'PERSONAL') > 0
    THEN
        v_database := 'PERSONAL';
    ELSIF INSTR( UPPER(vrec_banner.banner), 'ENTERPRISE') > 0
    THEN
        v_database := 'ENTERPRISE';
    ELSE
        v_database := 'UNKNOWN';
    END IF;

    RETURN v_database;
EXCEPTION
    WHEN OTHERS
    THEN
        RETURN 'ERROR:' || SQLERRM(SQLCODE);
END fn_which_edition; -- function fn_which_edition
/

Done.

Vibrate and Sound defaults on notification

For Kotlin you can Try this.

var builder = NotificationCompat.Builder(this,CHANNEL_ID)
     .setVibrate(longArrayOf(1000, 1000, 1000, 1000, 1000))
     .setSound(Settings.System.DEFAULT_NOTIFICATION_URI)

is there a function in lodash to replace matched item

Seems like the simplest solution would to use ES6's .map or lodash's _.map:

var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];

// lodash
var newArr = _.map(arr, function(a) {
  return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});

// ES6
var newArr = arr.map(function(a) {
  return a.id === 1 ? {id: 1, name: "Person New Name"} : a;
});

This has the nice effect of avoiding mutating the original array.

Uncaught TypeError: Cannot set property 'onclick' of null

Does document.getElementById("blue") exist? if it doesn't then blue_box will be equal to null. you can't set a onclick on something that's null

git command to move a folder inside another

I solved this on windows by doing this:

  • Open Power shell console
  • run dir
  • Alt-click and drag over the file/folder name column, then copy
  • Paste to notepad++
  • run replace with regex: replace (.*) with git mv ".\\\1" ".\\<New_Folder_Here>\"
  • copy all text from notepad++ into powershell
  • hit enter

How to scroll to an element inside a div?

To scroll an element into view of a div, only if needed, you can use this scrollIfNeeded function:

_x000D_
_x000D_
function scrollIfNeeded(element, container) {_x000D_
  if (element.offsetTop < container.scrollTop) {_x000D_
    container.scrollTop = element.offsetTop;_x000D_
  } else {_x000D_
    const offsetBottom = element.offsetTop + element.offsetHeight;_x000D_
    const scrollBottom = container.scrollTop + container.offsetHeight;_x000D_
    if (offsetBottom > scrollBottom) {_x000D_
      container.scrollTop = offsetBottom - container.offsetHeight;_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
document.getElementById('btn').addEventListener('click', ev => {_x000D_
  ev.preventDefault();_x000D_
  scrollIfNeeded(document.getElementById('goose'), document.getElementById('container'));_x000D_
});
_x000D_
.scrollContainer {_x000D_
  overflow-y: auto;_x000D_
  max-height: 100px;_x000D_
  position: relative;_x000D_
  border: 1px solid red;_x000D_
  width: 120px;_x000D_
}_x000D_
_x000D_
body {_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.box {_x000D_
  margin: 5px;_x000D_
  background-color: yellow;_x000D_
  height: 25px;_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
#goose {_x000D_
  background-color: lime;_x000D_
}
_x000D_
<div id="container" class="scrollContainer">_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div id="goose" class="box">goose</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
  <div class="box">duck</div>_x000D_
</div>_x000D_
_x000D_
<button id="btn">scroll to goose</button>
_x000D_
_x000D_
_x000D_

How to add a hook to the application context initialization event?

I had a single page application on entering URL it was creating a HashMap (used by my webpage) which contained data from multiple databases. I did following things to load everything during server start time-

1- Created ContextListenerClass

public class MyAppContextListener implements ServletContextListener
    @Autowired

    private  MyDataProviderBean myDataProviderBean; 

    public MyDataProviderBean getMyDataProviderBean() {

        return MyDataProviderBean;

    }

    public void setMyDataProviderBean(MyDataProviderBean MyDataProviderBean) {

        this.myDataProviderBean = MyDataProviderBean;

    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {

        System.out.println("ServletContextListener destroyed");

    }


    @Override

    public void contextInitialized(ServletContextEvent context) {

        System.out.println("ServletContextListener started");

        ServletContext sc = context.getServletContext();

        WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(sc);

        MyDataProviderBean MyDataProviderBean = (MyDataProviderBean)springContext.getBean("myDataProviderBean");

        Map<String, Object> myDataMap = MyDataProviderBean.getDataMap();

        sc.setAttribute("myMap", myDataMap);

    }

2- Added below entry in web.xml

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> 
<listener>
    <listener-class>com.context.listener.MyAppContextListener</listener-class>
</listener>

3- In my Controller Class updated code to first check for Map in servletContext

    @RequestMapping(value = "/index", method = RequestMethod.GET)
        public String index(@ModelAttribute("model") ModelMap model) {

            Map<String, Object> myDataMap = new HashMap<String, Object>();
            if (context != null && context.getAttribute("myMap")!=null)
            {

                myDataMap=(Map<String, Object>)context.getAttribute("myMap");
            }

            else
            {

                myDataMap = myDataProviderBean.getDataMap();
            }

            for (String key : myDataMap.keySet())
            {
                model.addAttribute(key, myDataMap.get(key));
            }
            return "myWebPage";

        }

With this much change when I start my tomcat it loads dataMap during startTime and puts everything in servletContext which is then used by Controller Class to get results from already populated servletContext .

What jar should I include to use javax.persistence package in a hibernate based application?

hibernate.jar and hibernate-entitymanager.jar contains only the packages org.hibernate.*. So you should take it from the Glassfish project.

CSS pseudo elements in React

Inline styling does not support pseudos or at-rules (e.g., @media). Recommendations range from reimplement CSS features in JavaScript for CSS states like :hover via onMouseEnter and onMouseLeave to using more elements to reproduce pseudo-elements like :after and :before to just use an external stylesheet.

Personally dislike all of those solutions. Reimplementing CSS features via JavaScript does not scale well -- neither does adding superfluous markup.

Imagine a large team wherein each developer is recreating CSS features like :hover. Each developer will do it differently, as teams grow in size, if it can be done, it will be done. Fact is with JavaScript there are about n ways to reimplement CSS features, and over time you can bet on every one of those ways being implemented with the end result being spaghetti code.

So what to do? Use CSS. Granted you asked about inline styling going to assume you're likely in the CSS-in-JS camp (me too!). Have found colocating HTML and CSS to be as valuable as colocating JS and HTML, lots of folks just don't realise it yet (JS-HTML colocation had lots of resistance too at first).

Made a solution in this space called Style It that simply lets your write plaintext CSS in your React components. No need to waste cycles reinventing CSS in JS. Right tool for the right job, here is an example using :after:

npm install style-it --save

Functional Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return Style.it(`
      #heart {
        position: relative;
        width: 100px;
        height: 90px;
      }
      #heart:before,
      #heart:after {
        position: absolute;
        content: "";
        left: 50px;
        top: 0;
        width: 50px;
        height: 80px;
        background: red;
        -moz-border-radius: 50px 50px 0 0;
        border-radius: 50px 50px 0 0;
        -webkit-transform: rotate(-45deg);
        -moz-transform: rotate(-45deg);
        -ms-transform: rotate(-45deg);
        -o-transform: rotate(-45deg);
        transform: rotate(-45deg);
        -webkit-transform-origin: 0 100%;
        -moz-transform-origin: 0 100%;
        -ms-transform-origin: 0 100%;
        -o-transform-origin: 0 100%;
        transform-origin: 0 100%;
      }
      #heart:after {
        left: 0;
        -webkit-transform: rotate(45deg);
        -moz-transform: rotate(45deg);
        -ms-transform: rotate(45deg);
        -o-transform: rotate(45deg);
        transform: rotate(45deg);
        -webkit-transform-origin: 100% 100%;
        -moz-transform-origin: 100% 100%;
        -ms-transform-origin: 100% 100%;
        -o-transform-origin: 100% 100%;
        transform-origin :100% 100%;
      }
    `,
      <div id="heart" />
    );
  }
}

export default Intro;

JSX Syntax (JSFIDDLE)

import React from 'react';
import Style from 'style-it';

class Intro extends React.Component {
  render() {
    return (
      <Style>
      {`
        #heart {
          position: relative;
          width: 100px;
          height: 90px;
        }
        #heart:before,
        #heart:after {
          position: absolute;
          content: "";
          left: 50px;
          top: 0;
          width: 50px;
          height: 80px;
          background: red;
          -moz-border-radius: 50px 50px 0 0;
          border-radius: 50px 50px 0 0;
          -webkit-transform: rotate(-45deg);
          -moz-transform: rotate(-45deg);
          -ms-transform: rotate(-45deg);
          -o-transform: rotate(-45deg);
          transform: rotate(-45deg);
          -webkit-transform-origin: 0 100%;
          -moz-transform-origin: 0 100%;
          -ms-transform-origin: 0 100%;
          -o-transform-origin: 0 100%;
          transform-origin: 0 100%;
        }
        #heart:after {
          left: 0;
          -webkit-transform: rotate(45deg);
          -moz-transform: rotate(45deg);
          -ms-transform: rotate(45deg);
          -o-transform: rotate(45deg);
          transform: rotate(45deg);
          -webkit-transform-origin: 100% 100%;
          -moz-transform-origin: 100% 100%;
          -ms-transform-origin: 100% 100%;
          -o-transform-origin: 100% 100%;
          transform-origin :100% 100%;
        }
     `}

      <div id="heart" />
    </Style>
  }
}

export default Intro;

Heart example pulled from CSS-Tricks

Using Postman to access OAuth 2.0 Google APIs

This is an old question, but it has no chosen answer, and I just solved this problem myself. Here's my solution:

  1. Make sure you are set up to work with your Google API in the first place. See Google's list of prerequisites. I was working with Google My Business, so I also went through it's Get Started process.

  2. In the OAuth 2.0 playground, Step 1 requires you to select which API you want to authenticate. Select or input as applicable for your case (in my case for Google My Business, I had to input https://www.googleapis.com/auth/plus.business.manage into the "Input your own scopes" input field). Note: this is the same as what's described in step 6 of the "Make a simple HTTP request" section of the Get Started guide.

  3. Assuming successful authentication, you should get an "Access token" returned in the "Step 1's result" step in the OAuth playground. Copy this token to your clipboard.

  4. Open Postman and open whichever collection you want as necessary.

  5. In Postman, make sure "GET" is selected as the request type, and click on the "Authorization" tab below the request type drop-down.

  6. In the Authorization "TYPE" dropdown menu, select "Bearer Token"

  7. Paste your previously copied "Access Token" which you copied from the OAuth playground into the "Token" field which displays in Postman.

  8. Almost there! To test if things work, put https://mybusiness.googleapis.com/v4/accounts/ into the main URL input bar in Postman and click the send button. You should get a JSON list of accounts back in the response that looks something like the following:

    
    {
        "accounts": [
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "PERSONAL",
                "state": {
                    "status": "UNVERIFIED"
                }
            },
            {
                "name": "accounts/REDACTED",
                "accountName": "REDACTED",
                "type": "LOCATION_GROUP",
                "role": "OWNER",
                "state": {
                    "status": "UNVERIFIED"
                },
                "permissionLevel": "OWNER_LEVEL"
            }
        ]
    }
    

Double % formatting question for printf in Java

Yes, %d is for decimal (integer), double expect %f. But simply using %f will default to up to precision 6. To print all of the precision digits for a double, you can pass it via string as:

System.out.printf("%s \r\n",String.valueOf(d));

or

System.out.printf("%s \r\n",Double.toString(d));

This is what println do by default:

System.out.println(d) 

(and terminates the line)

Bootstrap datepicker disabling past dates without current date

It depends on what format you put on the datepicker So first we gave it the format.

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!

    var yyyy = today.getFullYear();
    if(dd<10){
        dd='0'+dd;
    } 
    if(mm<10){
        mm='0'+mm;
    } 
    var today = yyyy+'-'+mm+'-'+dd; //Here you put the format you want

Then Pass the datepicker (depends on the version you using, could be startDate or minDate which is my case )

    //Datetimepicker
    $(function () {
        $('#datetimepicker1').datetimepicker({
            minDate: today, //pass today's date
            daysOfWeekDisabled: [0],
            locale: 'es',
            inline: true,
            format: 'YYYY-MM-DD HH:mm', //format of my datetime (to save on mysqlphpadmin)
            sideBySide: true
        });
    });

How to check if a string contains text from an array of substrings in JavaScript?

var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = 0, len = arr.length; i < len; ++i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}

edit: If the order of the tests doesn't matter, you could use this (with only one loop variable):

var str = "texttexttext";
var arr = ["asd", "ghj", "xtte"];
for (var i = arr.length - 1; i >= 0; --i) {
    if (str.indexOf(arr[i]) != -1) {
        // str contains arr[i]
    }
}

Html encode in PHP

Try this:

<?php
    $str = "This is some <b>bold</b> text.";
    echo htmlspecialchars($str);
?>

Source file 'Properties\AssemblyInfo.cs' could not be found

This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.

How to find tags with only certain attributes - BeautifulSoup

Adding a combination of Chris Redford's and Amr's answer, you can also search for an attribute name with any value with the select command:

from bs4 import BeautifulSoup as Soup
html = '<td valign="top">.....</td>\
    <td width="580" valign="top">.......</td>\
    <td>.....</td>'
soup = Soup(html, 'lxml')
results = soup.select('td[valign]')

angularjs: allows only numbers to be typed into a text box

I had a similar issue and ended up hooking and event

ng-change="changeCount()" 

then:

self.changeCount = function () {
      if (!self.info.itemcount) {
        self.info.itemcount = 1;
      }
 };

So the user is defaulted to 1 if a invalid number is inserted.

No Spring WebApplicationInitializer types detected on classpath

Watch out if you are using Maven. Your folder's structure must be right.

When using Maven, the WEB-INF directory must be inside webapp:

src/main/webapp/WEB-INF

Counter inside xsl:for-each loop

    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:template match="/">
        <newBooks>
                <xsl:for-each select="books/book">
                        <newBook>
                                <countNo><xsl:value-of select="position()"/></countNo>
                                <title>
                                        <xsl:value-of select="title"/>
                                </title>
                        </newBook>
                </xsl:for-each>
        </newBooks>
    </xsl:template>
</xsl:stylesheet>

Visual c++ can't open include file 'iostream'

quick fix for small programs:

add: #include <cstdlib>

How to compare two date values with jQuery

var startDate = $('#start_date').val().replace(/-/g,'/');
var endDate = $('#end_date').val().replace(/-/g,'/');

if(startDate > endDate){
   // do your stuff here...
}

React Native android build failed. SDK location not found

Check out in your local.properties file:

sdk.dir=C\:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk

if the format is proper or not

Representing Directory & File Structure in Markdown Syntax

If you're using VS Code, this is an awesome extension for generating file trees.

Added directly to markdown...

quakehunter
 ? client
 ? node_modules
 ? server
 ? ? index.js
 ? .gitignore
 ? package-lock.json
 ? package.json

Shared-memory objects in multiprocessing

Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.

I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle'd bytestrings generated by pickle.dumps(...).

The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain object.

$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma

from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)

brain['a'] = [1]*10000

brain['a']
# >>> [1,1,1,1,...]

Anaconda Installed but Cannot Launch Navigator

activate the virtual env with command:

 conda activate base

run anacond anavigator

 anaconda-navigator 

How to position two elements side by side using CSS

You can use float:left to align div in one line.

Fiddle

java.text.ParseException: Unparseable date

  • Your formatting pattern fails to match the input string, as noted by other Answers.
  • Your input format is terrible.
  • You are using troublesome old date-time classes that were supplanted years ago by the java.time classes.

ISO 8601

Instead a format such as yours, use ISO 8601 standard formats for exchanging date-time values as text.

The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings.

Proper time zone name

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

Your IST could mean Iceland Standard Time, India Standard Time, Ireland Standard Time, or others. The java.time classes are left to merely guessing, as there is no logical solution to this ambiguity.

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your input strings.

String input = "Sat Jun 01 12:53:10 IST 2013";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10Z[Atlantic/Reykjavik]

If your input was not intended for Iceland, you should pre-parse the string to adjust to a proper time zone name. For example, if you are certain the input was intended for India, change IST to Asia/Kolkata.

String input = "Sat Jun 01 12:53:10 IST 2013".replace( "IST" , "Asia/Kolkata" );
DateTimeFormatter f = DateTimeFormatter.ofPattern( "EEE MMM dd HH:mm:ss z uuuu" , Locale.US );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );

zdt.toString(): 2013-06-01T12:53:10+05:30[Asia/Kolkata]


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

A JRE or JDK must be available in order to run Eclipse. No JVM was found after searching the following locations

I had this problem and it was due to my windows machine playing up. I went into control panel -> system -> advanced - environment variables.

I edited the PATH variable (which was already correctly set up), changed NOTHING, clicked OK to come back out of the screens.

Then eclipse worked. No idea why, except because windows. Hopefully this may help someone.

How to run html file on localhost?

You can use python -m http.server. By default the local server will run on port 8000. If you would like to change this, simply add the port number python -m http.server 1234

If you are using python 2 (instead of 3), the equivalent command is python -m SimpleHTTPServer

How can I commit a single file using SVN over a network?

You have a file myFile.txt you want to commit.

The right procedure is :

  1. Move to the file folder
  2. svn up
  3. svn commit myFile.txt -m "Insert here a commit message!!!"

Hope this will help someone.

Java web start - Unable to load resource

Try using Janela or github to diagnose the problem.

How to detect window.print() finish

compatible with chrome, firefox, opera, Internet Explorer
Note: jQuery required.

<script>

    window.onafterprint = function(e){
        $(window).off('mousemove', window.onafterprint);
        console.log('Print Dialog Closed..');
    };

    window.print();

    setTimeout(function(){
        $(window).one('mousemove', window.onafterprint);
    }, 1);

</script>

sudo: port: command not found

First, you might need to edit your system's PATH

sudo vi /etc/paths

Add 2 following lines:

/opt/local/bin
/opt/local/sbin

Reboot your terminal

ADB Shell Input Events

If you want to send a text to specific device when multiple devices connected. First look for the attached devices using adb devices

adb devices
List of devices attached
3004e25a57192200        device
31002d9e592b7300        device

then get your specific device id and try the following

adb -s 31002d9e592b7300 shell input text 'your text'

Altering a column: null to not null

this seems simpler, but only works on Oracle:

ALTER TABLE [Table] 
ALTER [Column] NUMBER DEFAULT 0 NOT NULL;

in addition, with this, you can also add columns, not just alter it. It updates to the default value (0) in this example, if the value was null.

querySelector, wildcard element match?

[id^='someId'] will match all ids starting with someId.

[id$='someId'] will match all ids ending with someId.

[id*='someId'] will match all ids containing someId.

If you're looking for the name attribute just substitute id with name.

If you're talking about the tag name of the element I don't believe there is a way using querySelector

Can I bind an array to an IN() condition?

I also realise this thread is old but I had a unique problem where, while converting the soon-to-be deprecated mysql driver to the PDO driver I had to make a function which could build, dynamically, both normal params and INs from the same param array. So I quickly built this:

/**
 * mysql::pdo_query('SELECT * FROM TBL_WHOOP WHERE type_of_whoop IN :param AND siz_of_whoop = :size', array(':param' => array(1,2,3), ':size' => 3))
 *
 * @param $query
 * @param $params
 */
function pdo_query($query, $params = array()){

    if(!$query)
        trigger_error('Could not query nothing');

    // Lets get our IN fields first
    $in_fields = array();
    foreach($params as $field => $value){
        if(is_array($value)){
            for($i=0,$size=sizeof($value);$i<$size;$i++)
                $in_array[] = $field.$i;

            $query = str_replace($field, "(".implode(',', $in_array).")", $query); // Lets replace the position in the query string with the full version
            $in_fields[$field] = $value; // Lets add this field to an array for use later
            unset($params[$field]); // Lets unset so we don't bind the param later down the line
        }
    }

    $query_obj = $this->pdo_link->prepare($query);
    $query_obj->setFetchMode(PDO::FETCH_ASSOC);

    // Now lets bind normal params.
    foreach($params as $field => $value) $query_obj->bindValue($field, $value);

    // Now lets bind the IN params
    foreach($in_fields as $field => $value){
        for($i=0,$size=sizeof($value);$i<$size;$i++)
            $query_obj->bindValue($field.$i, $value[$i]); // Both the named param index and this index are based off the array index which has not changed...hopefully
    }

    $query_obj->execute();

    if($query_obj->rowCount() <= 0)
        return null;

    return $query_obj;
}

It is still untested however the logic seems to be there.

Hope it helps someone in the same position,

Edit: After some testing I found out:

  • PDO does not like '.' in their names (which is kinda stupid if you ask me)
  • bindParam is the wrong function, bindValue is the right function.

Code edited to working version.

How to TryParse for Enum value?

Is caching a dynamically generated function/dictionary permissable?

Because you don't (appear to) know the type of the enum ahead of time, the first execution could generate something subsequent executions could take advantage of.

You could even cache the result of Enum.GetNames()

Are you trying to optimize for CPU or Memory? Do you really need to?

Can I Set "android:layout_below" at Runtime Programmatically?

While @jackofallcode answer is correct, it can be written in one line:

((RelativeLayout.LayoutParams) viewToLayout.getLayoutParams()).addRule(RelativeLayout.BELOW, R.id.below_id);

Getting list of parameter names inside python function

locals() returns a dictionary with local names:

def func(a,b,c):
    print(locals().keys())

prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.

Git Pull While Ignoring Local Changes?

If you are on Linux:

git fetch
for file in `git diff origin/master..HEAD --name-only`; do rm -f "$file"; done
git pull

The for loop will delete all tracked files which are changed in the local repo, so git pull will work without any problems.
The nicest thing about this is that only the tracked files will be overwritten by the files in the repo, all other files will be left untouched.

git status shows fatal: bad object HEAD

In my case the error came out of nowhere, but didn't let me push to the remote branch.

git fetch origin

And that solved it.

I agree this may not solve the issue for everyone, but before trying a more complex approach give it a shot at this one, nothing to loose.

How to get the ASCII value in JavaScript for the characters

Here is the example:

_x000D_
_x000D_
var charCode = "a".charCodeAt(0);_x000D_
console.log(charCode);
_x000D_
_x000D_
_x000D_

Or if you have longer strings:

_x000D_
_x000D_
var string = "Some string";_x000D_
_x000D_
for (var i = 0; i < string.length; i++) {_x000D_
  console.log(string.charCodeAt(i));_x000D_
}
_x000D_
_x000D_
_x000D_

String.charCodeAt(x) method will return ASCII character code at a given position.

Multiple returns from a function

Some might prefer returning multiple values as object:

function test() {
    $object = new stdClass();

    $object->x = 'value 1';
    $object->y = 'value 2';

    return $object;
}

And call it like this:

echo test()->x;

Or:

$test = test();
echo $test->y;

Volatile vs Static in Java

Difference Between Static and Volatile :

Static Variable: If two Threads(suppose t1 and t2) are accessing the same object and updating a variable which is declared as static then it means t1 and t2 can make their own local copy of the same object(including static variables) in their respective cache, so update made by t1 to the static variable in its local cache wont reflect in the static variable for t2 cache .

Static variables are used in the context of Object where update made by one object would reflect in all the other objects of the same class but not in the context of Thread where update of one thread to the static variable will reflect the changes immediately to all the threads (in their local cache).

Volatile variable: If two Threads(suppose t1 and t2) are accessing the same object and updating a variable which is declared as volatile then it means t1 and t2 can make their own local cache of the Object except the variable which is declared as a volatile . So the volatile variable will have only one main copy which will be updated by different threads and update made by one thread to the volatile variable will immediately reflect to the other Thread.

Install sbt on ubuntu

As an alternative approach, you can save the SBT Extras script to a file called sbt.sh and set the permission to executable. Then add this file to your path, or just put it under your ~/bin directory.

The bonus here, is that it will download and use the correct version of SBT depending on your project properties. This is a nice convenience if you tend to compile open source projects that you pull from GitHub and other.

Is there a way to split a widescreen monitor in to two or more virtual monitors?

I use WinSplit Revolution for the keyboard arrangement capability and I use bblean as a replacement for Explorer. It has multiple workspace capabilities built right in and it allows you to customize it exactly how you want it to look.

How can I time a code segment for testing performance with Pythons timeit?

If you are profiling your code and can use IPython, it has the magic function %timeit.

%%timeit operates on cells.

In [2]: %timeit cos(3.14)
10000000 loops, best of 3: 160 ns per loop

In [3]: %%timeit
   ...: cos(3.14)
   ...: x = 2 + 3
   ...: 
10000000 loops, best of 3: 196 ns per loop

How to set date format in HTML date input tag?

We can change this yyyy-mm-dd format to dd-mm-yyyy in javascript by using split method.

let dateyear= "2020-03-18";
let arr = dateyear.split('-') //now we get array of these and we can made in any format as we want
let dateFormat = arr[2] + "-" + arr[1] + "-" + arr[0]  //In dd-mm-yyyy format

Can't find/install libXtst.so.6?

This worked for me in Luna elementary OS

sudo apt-get install libxtst6:i386

Detect URLs in text with JavaScript

First you need a good regex that matches urls. This is hard to do. See here, here and here:

...almost anything is a valid URL. There are some punctuation rules for splitting it up. Absent any punctuation, you still have a valid URL.

Check the RFC carefully and see if you can construct an "invalid" URL. The rules are very flexible.

For example ::::: is a valid URL. The path is ":::::". A pretty stupid filename, but a valid filename.

Also, ///// is a valid URL. The netloc ("hostname") is "". The path is "///". Again, stupid. Also valid. This URL normalizes to "///" which is the equivalent.

Something like "bad://///worse/////" is perfectly valid. Dumb but valid.

Anyway, this answer is not meant to give you the best regex but rather a proof of how to do the string wrapping inside the text, with JavaScript.

OK so lets just use this one: /(https?:\/\/[^\s]+)/g

Again, this is a bad regex. It will have many false positives. However it's good enough for this example.

_x000D_
_x000D_
function urlify(text) {_x000D_
  var urlRegex = /(https?:\/\/[^\s]+)/g;_x000D_
  return text.replace(urlRegex, function(url) {_x000D_
    return '<a href="' + url + '">' + url + '</a>';_x000D_
  })_x000D_
  // or alternatively_x000D_
  // return text.replace(urlRegex, '<a href="$1">$1</a>')_x000D_
}_x000D_
_x000D_
var text = 'Find me at http://www.example.com and also at http://stackoverflow.com';_x000D_
var html = urlify(text);_x000D_
_x000D_
console.log(html)
_x000D_
_x000D_
_x000D_

// html now looks like:
// "Find me at <a href="http://www.example.com">http://www.example.com</a> and also at <a href="http://stackoverflow.com">http://stackoverflow.com</a>"

So in sum try:

$$('#pad dl dd').each(function(element) {
    element.innerHTML = urlify(element.innerHTML);
});

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

How to check if function exists in JavaScript?

I had the case where the name of the function varied according to a variable (var 'x' in this case) added to the functions name. This works:

if ( typeof window['afunction_'+x] === 'function' ) { window['afunction_'+x](); } 

How to change port number for apache in WAMP

Click on the WAMP server icon and from the menu under Config Files select httpd.conf. A long text file will open up in notepad. In this file scroll down to the line that reads Port 80 and change this to read Port 8080, Save the file and close notepad. Once again click on the wamp server icon and select restart all services. One more change needs to be made before we are done. In Windows Explorer find the location where WAMP server was installed which is by Default C:\Wamp.

How to overwrite the output directory in spark

df.write.mode('overwrite').parquet("/output/folder/path") works if you want to overwrite a parquet file using python. This is in spark 1.6.2. API may be different in later versions

How to copy marked text in notepad++

I had the same problem. You can list the regex matches in a new tab, every match in new line in PSPad Editor, which is very similar as Notepad++.

Hit Ctrl + F to search, check the regexp opion, put the regexp and click on List.

AngularJS - How can I do a redirect with a full page load?

Try this

$window.location.href="#page-name";
$window.location.reload();

How to get on scroll events?

Alternative to @HostListener and scroll output on the element I would suggest using fromEvent from RxJS since you can chain it with filter() and distinctUntilChanges() and can easily skip flood of potentially redundant events (and change detections).

Here is a simple example:

// {static: true} can be omitted if you don't need this element/listener in ngOnInit
@ViewChild('elementId', {static: true}) el: ElementRef;

// ...

fromEvent(this.el.nativeElement, 'scroll')
  .pipe(
    // Is elementId scrolled for more than 50 from top?
    map((e: Event) => (e.srcElement as Element).scrollTop > 50),
    // Dispatch change only if result from map above is different from previous result
    distinctUntilChanged());

jQuery - checkbox enable/disable

Change your markup slightly:

_x000D_
_x000D_
$(function() {_x000D_
  enable_cb();_x000D_
  $("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
  if (this.checked) {_x000D_
    $("input.group1").removeAttr("disabled");_x000D_
  } else {_x000D_
    $("input.group1").attr("disabled", true);_x000D_
  }_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
  <input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
  <input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
  <input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
_x000D_
_x000D_

You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.

Clear and reset form input fields

Using event.target.reset() only works for uncontrolled components, which is not recommended. For controlled components you would do something like this:

import React, { Component } from 'react'

class MyForm extends Component {
  initialState = { name: '' }

  state = this.initialState

  handleFormReset = () => {
    this.setState(() => this.initialState)
  }

  render() {

    return (
      <form onReset={this.handleFormReset}>
        <div>
          <label htmlFor="name">Name</label>
          <input
            type="text"
            placeholder="Enter name"
            name="name"
            value={name}
            onChange={this.handleInputOnChange}
          />
        </div>
        <div>
          <input
            type="submit"
            value="Submit"
          />
          <input
            type="reset"
            value="Reset"
          />
        </div>
      </form>
    )
  }
}

ContactAdd.propTypes = {}

export default MyForm

Open a local HTML file using window.open in Chrome

First, make sure that the source page and the target page are both served through the file URI scheme. You can't force an http page to open a file page (but it works the other way around).

Next, your script that calls window.open() should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open() won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

// Does nothing
window.open('http://google.com');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>
    </body>
</html>

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.

"Use of undeclared type" in Swift, even though type is internal, and exists in same module

I had the exact same problem. Some of the files in my framework were not reachable from other classes within the same module.

For some reason the files that had been added to the framework in Xcode was not part of the Compile Sources. If your Swift file is not part of the compile sources you need to add them by tapping the + and selecting them in the popup.

Screenshot 1

Also make sure the file is part of the framework target. (The little box in the screenshot below should be checked)

Screenshot 2

SQL SERVER, SELECT statement with auto generate row id

Select (Select count(y.au_lname) from dbo.authors y
where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
x.au_lname,x.au_fname from authors x group by au_lname,au_fname
order by Counterid --Alternatively that can be done which is equivalent as above..

Add a default value to a column through a migration

This is what you can do:

class Profile < ActiveRecord::Base
  before_save :set_default_val

  def set_default_val
    self.send_updates = 'val' unless self.send_updates
  end
end

EDIT: ...but apparently this is a Rookie mistake!

Set Canvas size using javascript

You can also use this script , just change the height and width

<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>

   <script>
      var canvas = document.getElementById("Canvas01");
      var ctx = canvas.getContext("2d");

Type List vs type ArrayList in Java

I think the people who use (2) don't know the Liskov substitution principle or the Dependency inversion principle. Or they really have to use ArrayList.

How to read multiple Integer values from a single line of input in Java?

You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.

String input = scanner.nextLine();    // get the entire line after the prompt 
String[] numbers = input.split(" "); // split by spaces

Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()

diff to output only the file names

From the diff man page:

-q   Report only whether the files differ, not the details of the differences.
-r   When comparing directories, recursively compare any subdirectories found.

Example command:

diff -qr dir1 dir2

Example output (depends on locale):

$ ls dir1 dir2
dir1:
same-file  different  only-1

dir2:
same-file  different  only-2
$ diff -qr dir1 dir2
Files dir1/different and dir2/different differ
Only in dir1: only-1
Only in dir2: only-2

Using 'make' on OS X

I found the Developer Tools not as readily available as others. In El Capitan, in terminal I just used gcc -v, it then said gcc wasn't available and asked if I wanted to install the command line Apple Developer Tools. No downloading of Xcode required. Terminal session below:

Pauls-MBP:~ paulhillman$ gcc -v
xcode-select: note: no developer tools were found at '/Applications/Xcode.app', requesting install. Choose an option in the dialog to download the command line developer tools.
Pauls-MBP:~ paulhillman$ gcc -v
Configured with: --prefix=/Library/Developer/CommandLineTools/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 7.3.0 (clang-703.0.31)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

Why does using an Underscore character in a LIKE filter give me all the results?

You can write the query as below:

SELECT * FROM Manager
WHERE managerid LIKE '\_%' escape '\'
AND managername LIKE '%\_%' escape '\';

it will solve your problem.

How to transfer paid android apps from one google account to another google account

It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

Listen for key press in .NET console app

According to my experience, in console apps the easiest way to read the last key pressed is as follows (Example with arrow keys):

ConsoleKey readKey = Console.ReadKey ().Key;
if (readKey == ConsoleKey.LeftArrow) {
    <Method1> ();  //Do something
} else if (readKey == ConsoleKey.RightArrow) {
    <Method2> ();  //Do something
}

I use to avoid loops, instead I write the code above within a method, and I call it at the end of both "Method1" and "Method2", so, after executing "Method1" or "Method2", Console.ReadKey().Key is ready to read the keys again.

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

Select query to get data from SQL Server

you have to add parameter also @zip

 SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");
      conn.Open();
      SqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);
      //
    // Add new SqlParameter to the command.
    //
      command.Parameters.AddWithValue("@zip","india");
      int result = (Int32) (command.ExecuteScalar());
      using (SqlDataReader reader = command.ExecuteReader())
      {
          // iterate your results here
       Console.WriteLine(String.Format("{0}",reader["id"]));

      }
      conn.Close();

AngularJS resource promise

You could also do:

Regions.query({}, function(response) {
    $scope.regions = response;
    // Do stuff that depends on $scope.regions here
});

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

I had same issue in Angular7 when I create dynamic components. There are two components(TreatListComponent, MyTreatComponent) that needs to be loaded dynamically. I just added entryComponents array in to my app.module.ts file.

    entryComponents: [
    TreatListComponent,
    MyTreatComponent
  ],

cancelling a handler.postdelayed process

Hope this gist help https://gist.github.com/imammubin/a587192982ff8db221da14d094df6fb4

MainActivity as Screen Launcher with handler & runnable function, the Runnable run to login page or feed page with base preference login user with firebase.

Returning JSON response from Servlet to Javascript/JSP page

Got it working! I should have been building a JSONArray of JSONObjects and then add the array to a final "Addresses" JSONObject. Observe the following:

JSONObject json      = new JSONObject();
JSONArray  addresses = new JSONArray();
JSONObject address;
try
{
   int count = 15;

   for (int i=0 ; i<count ; i++)
   {
       address = new JSONObject();
       address.put("CustomerName"     , "Decepticons" + i);
       address.put("AccountId"        , "1999" + i);
       address.put("SiteId"           , "1888" + i);
       address.put("Number"            , "7" + i);
       address.put("Building"          , "StarScream Skyscraper" + i);
       address.put("Street"            , "Devestator Avenue" + i);
       address.put("City"              , "Megatron City" + i);
       address.put("ZipCode"          , "ZZ00 XX1" + i);
       address.put("Country"           , "CyberTron" + i);
       addresses.add(address);
   }
   json.put("Addresses", addresses);
}
catch (JSONException jse)
{ 

}
response.setContentType("application/json");
response.getWriter().write(json.toString());

This worked and returned valid and parse-able JSON. Hopefully this helps someone else in the future. Thanks for your help Marcel

DISABLE the Horizontal Scroll

You can try this all of method in our html page..

1st way

body { overflow-x:hidden; }

2nd way You can use the following in your CSS body tag:

overflow-y: scroll; overflow-x: hidden;

That will remove your scrollbar.

3rd way

body { min-width: 1167px; }

5th way

html, body { max-width: 100%; overflow-x: hidden; }

6th way

element { max-width: 100vw; overflow-x: hidden; }

4th way..

var docWidth = document.documentElement.offsetWidth; [].forEach.call( document.querySelectorAll('*'), function(el) { if (el.offsetWidth > docWidth) { console.log(el); } } );

Now i m searching about more..!!!!

What is meant by the term "hook" in programming?

Essentially it's a place in code that allows you to tap in to a module to either provide different behavior or to react when something happens.

Easy way to use variables of enum types as string in C?

Check out the ideas at Mu Dynamics Research Labs - Blog Archive. I found this earlier this year - I forget the exact context where I came across it - and have adapted it into this code. We can debate the merits of adding an E at the front; it is applicable to the specific problem addressed, but not part of a general solution. I stashed this away in my 'vignettes' folder - where I keep interesting scraps of code in case I want them later. I'm embarrassed to say that I didn't keep a note of where this idea came from at the time.

Header: paste1.h

/*
@(#)File:           $RCSfile: paste1.h,v $
@(#)Version:        $Revision: 1.1 $
@(#)Last changed:   $Date: 2008/05/17 21:38:05 $
@(#)Purpose:        Automated Token Pasting
*/

#ifndef JLSS_ID_PASTE_H
#define JLSS_ID_PASTE_H

/*
 * Common case when someone just includes this file.  In this case,
 * they just get the various E* tokens as good old enums.
 */
#if !defined(ETYPE)
#define ETYPE(val, desc) E##val,
#define ETYPE_ENUM
enum {
#endif /* ETYPE */

   ETYPE(PERM,  "Operation not permitted")
   ETYPE(NOENT, "No such file or directory")
   ETYPE(SRCH,  "No such process")
   ETYPE(INTR,  "Interrupted system call")
   ETYPE(IO,    "I/O error")
   ETYPE(NXIO,  "No such device or address")
   ETYPE(2BIG,  "Arg list too long")

/*
 * Close up the enum block in the common case of someone including
 * this file.
 */
#if defined(ETYPE_ENUM)
#undef ETYPE_ENUM
#undef ETYPE
ETYPE_MAX
};
#endif /* ETYPE_ENUM */

#endif /* JLSS_ID_PASTE_H */

Example source:

/*
@(#)File:           $RCSfile: paste1.c,v $
@(#)Version:        $Revision: 1.2 $
@(#)Last changed:   $Date: 2008/06/24 01:03:38 $
@(#)Purpose:        Automated Token Pasting
*/

#include "paste1.h"

static const char *sys_errlist_internal[] = {
#undef JLSS_ID_PASTE_H
#define ETYPE(val, desc) desc,
#include "paste1.h"
    0
#undef ETYPE
};

static const char *xerror(int err)
{
    if (err >= ETYPE_MAX || err <= 0)
        return "Unknown error";
    return sys_errlist_internal[err];
}

static const char*errlist_mnemonics[] = {
#undef JLSS_ID_PASTE_H
#define ETYPE(val, desc) [E ## val] = "E" #val,
#include "paste1.h"
#undef ETYPE
};

#include <stdio.h>

int main(void)
{
    int i;

    for (i = 0; i < ETYPE_MAX; i++)
    {
        printf("%d: %-6s: %s\n", i, errlist_mnemonics[i], xerror(i));
    }
    return(0);
}

Not necessarily the world's cleanest use of the C pre-processor - but it does prevent writing the material out multiple times.

Are HTTP cookies port specific?

According to RFC2965 3.3.1 (which might or might not be followed by browsers), unless the port is explicitly specified via the port parameter of the Set-Cookie header, cookies might or might not be sent to any port.

Google's Browser Security Handbook says: by default, cookie scope is limited to all URLs on the current host name - and not bound to port or protocol information. and some lines later There is no way to limit cookies to a single DNS name only [...] likewise, there is no way to limit them to a specific port. (Also, keep in mind, that IE does not factor port numbers into its same-origin policy at all.)

So it does not seem to be safe to rely on any well-defined behavior here.

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

I had the exact same issue, I have kind of the same configuration as your exemple and I got it working by removing the line :

ssl on;

To quote the doc:

If HTTP and HTTPS servers are equal, a single server that handles both HTTP and HTTPS requests may be configured by deleting the directive “ssl on” and adding the ssl parameter for *:443 port

Android: Is it possible to display video thumbnails?

This solution will work for any version of Android. It has proven to work in 1.5 and 2.2 This is not another "This is for Android 2.0+" solution. I found this through an email message board collection page and cannot find the original link. All credit goes to the original poster.

In your app you would use this by calling:

Bitmap bm = getVideoFrame(VideoStringUri);

Somewhere in it's own function (outside the OnCreate, ect), you would need:

private Bitmap getVideoFrame(String uri) {
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setMode(MediaMetadataRetriever.MODE_CAPTURE_FRAME_ONLY);
            retriever.setDataSource(uri);
            return retriever.captureFrame();
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        } catch (RuntimeException ex) {
            ex.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
            }
        }
        return null;
    }

In your src folder, you need a new subdirectory android/media which will house the class (copied from the android source itself) which allows you to use this function. This part should not be changed, renamed, or placed anywhere else. MediaMetadataRetriever.java needs to be under android.media in your source folder for this all to work.

/*
 * Copyright (C) 2008 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.media;

import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.net.Uri;

/**
 * MediaMetadataRetriever class provides a unified interface for retrieving
 * frame and meta data from an input media file. {@hide}
 */
public class MediaMetadataRetriever {
    static {
        System.loadLibrary("media_jni");
        native_init();
    }

    // The field below is accessed by native methods
    private int mNativeContext;

    public MediaMetadataRetriever() {
        native_setup();
    }

    /**
     * Call this method before setDataSource() so that the mode becomes
     * effective for subsequent operations. This method can be called only once
     * at the beginning if the intended mode of operation for a
     * MediaMetadataRetriever object remains the same for its whole lifetime,
     * and thus it is unnecessary to call this method each time setDataSource()
     * is called. If this is not never called (which is allowed), by default the
     * intended mode of operation is to both capture frame and retrieve meta
     * data (i.e., MODE_GET_METADATA_ONLY | MODE_CAPTURE_FRAME_ONLY). Often,
     * this may not be what one wants, since doing this has negative performance
     * impact on execution time of a call to setDataSource(), since both types
     * of operations may be time consuming.
     * 
     * @param mode
     *            The intended mode of operation. Can be any combination of
     *            MODE_GET_METADATA_ONLY and MODE_CAPTURE_FRAME_ONLY: 1.
     *            MODE_GET_METADATA_ONLY & MODE_CAPTURE_FRAME_ONLY: For neither
     *            frame capture nor meta data retrieval 2.
     *            MODE_GET_METADATA_ONLY: For meta data retrieval only 3.
     *            MODE_CAPTURE_FRAME_ONLY: For frame capture only 4.
     *            MODE_GET_METADATA_ONLY | MODE_CAPTURE_FRAME_ONLY: For both
     *            frame capture and meta data retrieval
     */
    public native void setMode(int mode);

    /**
     * @return the current mode of operation. A negative return value indicates
     *         some runtime error has occurred.
     */
    public native int getMode();

    /**
     * Sets the data source (file pathname) to use. Call this method before the
     * rest of the methods in this class. This method may be time-consuming.
     * 
     * @param path
     *            The path of the input media file.
     * @throws IllegalArgumentException
     *             If the path is invalid.
     */
    public native void setDataSource(String path)
            throws IllegalArgumentException;

    /**
     * Sets the data source (FileDescriptor) to use. It is the caller's
     * responsibility to close the file descriptor. It is safe to do so as soon
     * as this call returns. Call this method before the rest of the methods in
     * this class. This method may be time-consuming.
     * 
     * @param fd
     *            the FileDescriptor for the file you want to play
     * @param offset
     *            the offset into the file where the data to be played starts,
     *            in bytes. It must be non-negative
     * @param length
     *            the length in bytes of the data to be played. It must be
     *            non-negative.
     * @throws IllegalArgumentException
     *             if the arguments are invalid
     */
    public native void setDataSource(FileDescriptor fd, long offset, long length)
            throws IllegalArgumentException;

    /**
     * Sets the data source (FileDescriptor) to use. It is the caller's
     * responsibility to close the file descriptor. It is safe to do so as soon
     * as this call returns. Call this method before the rest of the methods in
     * this class. This method may be time-consuming.
     * 
     * @param fd
     *            the FileDescriptor for the file you want to play
     * @throws IllegalArgumentException
     *             if the FileDescriptor is invalid
     */
    public void setDataSource(FileDescriptor fd)
            throws IllegalArgumentException {
        // intentionally less than LONG_MAX
        setDataSource(fd, 0, 0x7ffffffffffffffL);
    }

    /**
     * Sets the data source as a content Uri. Call this method before the rest
     * of the methods in this class. This method may be time-consuming.
     * 
     * @param context
     *            the Context to use when resolving the Uri
     * @param uri
     *            the Content URI of the data you want to play
     * @throws IllegalArgumentException
     *             if the Uri is invalid
     * @throws SecurityException
     *             if the Uri cannot be used due to lack of permission.
     */
    public void setDataSource(Context context, Uri uri)
            throws IllegalArgumentException, SecurityException {
        if (uri == null) {
            throw new IllegalArgumentException();
        }

        String scheme = uri.getScheme();
        if (scheme == null || scheme.equals("file")) {
            setDataSource(uri.getPath());
            return;
        }

        AssetFileDescriptor fd = null;
        try {
            ContentResolver resolver = context.getContentResolver();
            try {
                fd = resolver.openAssetFileDescriptor(uri, "r");
            } catch (FileNotFoundException e) {
                throw new IllegalArgumentException();
            }
            if (fd == null) {
                throw new IllegalArgumentException();
            }
            FileDescriptor descriptor = fd.getFileDescriptor();
            if (!descriptor.valid()) {
                throw new IllegalArgumentException();
            }
            // Note: using getDeclaredLength so that our behavior is the same
            // as previous versions when the content provider is returning
            // a full file.
            if (fd.getDeclaredLength() < 0) {
                setDataSource(descriptor);
            } else {
                setDataSource(descriptor, fd.getStartOffset(),
                        fd.getDeclaredLength());
            }
            return;
        } catch (SecurityException ex) {
        } finally {
            try {
                if (fd != null) {
                    fd.close();
                }
            } catch (IOException ioEx) {
            }
        }
        setDataSource(uri.toString());
    }

    /**
     * Call this method after setDataSource(). This method retrieves the meta
     * data value associated with the keyCode.
     * 
     * The keyCode currently supported is listed below as METADATA_XXX
     * constants. With any other value, it returns a null pointer.
     * 
     * @param keyCode
     *            One of the constants listed below at the end of the class.
     * @return The meta data value associate with the given keyCode on success;
     *         null on failure.
     */
    public native String extractMetadata(int keyCode);

    /**
     * Call this method after setDataSource(). This method finds a
     * representative frame if successful and returns it as a bitmap. This is
     * useful for generating a thumbnail for an input media source.
     * 
     * @return A Bitmap containing a representative video frame, which can be
     *         null, if such a frame cannot be retrieved.
     */
    public native Bitmap captureFrame();

    /**
     * Call this method after setDataSource(). This method finds the optional
     * graphic or album art associated (embedded or external url linked) the
     * related data source.
     * 
     * @return null if no such graphic is found.
     */
    public native byte[] extractAlbumArt();

    /**
     * Call it when one is done with the object. This method releases the memory
     * allocated internally.
     */
    public native void release();

    private native void native_setup();

    private static native void native_init();

    private native final void native_finalize();

    @Override
    protected void finalize() throws Throwable {
        try {
            native_finalize();
        } finally {
            super.finalize();
        }
    }

    public static final int MODE_GET_METADATA_ONLY = 0x01;
    public static final int MODE_CAPTURE_FRAME_ONLY = 0x02;

    /*
     * Do not change these values without updating their counterparts in
     * include/media/mediametadataretriever.h!
     */
    public static final int METADATA_KEY_CD_TRACK_NUMBER = 0;
    public static final int METADATA_KEY_ALBUM = 1;
    public static final int METADATA_KEY_ARTIST = 2;
    public static final int METADATA_KEY_AUTHOR = 3;
    public static final int METADATA_KEY_COMPOSER = 4;
    public static final int METADATA_KEY_DATE = 5;
    public static final int METADATA_KEY_GENRE = 6;
    public static final int METADATA_KEY_TITLE = 7;
    public static final int METADATA_KEY_YEAR = 8;
    public static final int METADATA_KEY_DURATION = 9;
    public static final int METADATA_KEY_NUM_TRACKS = 10;
    public static final int METADATA_KEY_IS_DRM_CRIPPLED = 11;
    public static final int METADATA_KEY_CODEC = 12;
    public static final int METADATA_KEY_RATING = 13;
    public static final int METADATA_KEY_COMMENT = 14;
    public static final int METADATA_KEY_COPYRIGHT = 15;
    public static final int METADATA_KEY_BIT_RATE = 16;
    public static final int METADATA_KEY_FRAME_RATE = 17;
    public static final int METADATA_KEY_VIDEO_FORMAT = 18;
    public static final int METADATA_KEY_VIDEO_HEIGHT = 19;
    public static final int METADATA_KEY_VIDEO_WIDTH = 20;
    public static final int METADATA_KEY_WRITER = 21;
    public static final int METADATA_KEY_MIMETYPE = 22;
    public static final int METADATA_KEY_DISCNUMBER = 23;
    public static final int METADATA_KEY_ALBUMARTIST = 24;
    // Add more here...
}

Unable to get provider com.google.firebase.provider.FirebaseInitProvider

1.

Add the applicationId to the application's build.gradle:

android {
    ...
    defaultConfig {
        applicationId "com.example.my.app"
        ...
    }
}

And than Clean Project -> Build or Rebuild Project


2. If your minSdkVersion <= 20 (https://developer.android.com/studio/build/multidex)

Use Multidex correctly.

application's build.gradle

android {
...               
    defaultConfig {
    ....
        multiDexEnabled true
    }
    ...
}

dependencies {
    implementation 'com.android.support:multidex:1.0.3'
    ...
}

manifest.xml

<application
    ...
    android:name="android.support.multidex.MultiDexApplication" >
    ...

3.

If you use a custom Application class

public class MyApplication extends MultiDexApplication {
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }
}

manifest.xml

<application
    ...
    android:name="com.example.my.app.MyApplication" >
    ...

How to clear mysql screen console in windows?

Just scroll down with your mouse

In Linux Ctrl+L will do but if your scroll up you will see the old commands

So I would suggest scrolling down in windows using mouse

error::make_unique is not a member of ‘std’

If you have latest compiler, you can change the following in your build settings:

 C++ Language Dialect    C++14[-std=c++14]

This works for me.

Should a function have only one return statement?

You know the adage - beauty is in the eyes of the beholder.

Some people swear by NetBeans and some by IntelliJ IDEA, some by Python and some by PHP.

In some shops you could lose your job if you insist on doing this:

public void hello()
{
   if (....)
   {
      ....
   }
}

The question is all about visibility and maintainability.

I am addicted to using boolean algebra to reduce and simplify logic and use of state machines. However, there were past colleagues who believed my employ of "mathematical techniques" in coding is unsuitable, because it would not be visible and maintainable. And that would be a bad practice. Sorry people, the techniques I employ is very visible and maintainable to me - because when I return to the code six months later, I would understand the code clearly rather seeing a mess of proverbial spaghetti.

Hey buddy (like a former client used to say) do what you want as long as you know how to fix it when I need you to fix it.

I remember 20 years ago, a colleague of mine was fired for employing what today would be called agile development strategy. He had a meticulous incremental plan. But his manager was yelling at him "You can't incrementally release features to users! You must stick with the waterfall." His response to the manager was that incremental development would be more precise to customer's needs. He believed in developing for the customers needs, but the manager believed in coding to "customer's requirement".

We are frequently guilty for breaking data normalization, MVP and MVC boundaries. We inline instead of constructing a function. We take shortcuts.

Personally, I believe that PHP is bad practice, but what do I know. All the theoretical arguments boils down to trying fulfill one set of rules

quality = precision, maintainability and profitability.

All other rules fade into the background. And of course this rule never fades:

Laziness is the virtue of a good programmer.

Android SDK Manager Not Installing Components

go to sdk folder and right click on SDK manager and run with administrator and enjoy installing.

How to make popup look at the centre of the screen?

In order to get the popup exactly centered, it's a simple matter of applying a negative top margin of half the div height, and a negative left margin of half the div width. For this example, like so:

.div {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 50%;
}

Setting Windows PowerShell environment variables

I tried to optimise SBF's and Michael's code a bit to make it more compact.

I am relying on PowerShell's type coercion where it automatically converts strings to enum values, so I didn't define the lookup dictionary.

I also pulled out the block that adds the new path to the list based on a condition, so that work is done once and stored in a variable for re-use.

It is then applied permanently or just to the Session depending on the $PathContainer parameter.

We can put the block of code in a function or a ps1 file that we call directly from the command prompt. I went with DevEnvAddPath.ps1.

param(
    [Parameter(Position=0,Mandatory=$true)][String]$PathChange,

    [ValidateSet('Machine', 'User', 'Session')]
    [Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session',
    [Parameter(Position=2,Mandatory=$false)][Boolean]$PathPrepend=$false
)

[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';

if ($PathPersisted -notcontains $PathChange) {
    $PathPersisted = $(switch ($PathPrepend) { $true{,$PathChange + $PathPersisted;} default{$PathPersisted + $PathChange;} }) | Where-Object { $_ };

    $ConstructedEnvPath = $PathPersisted -join ";";
}

if ($PathContainer -ne 'Session') 
{
    # Save permanently to Machine, User
    [Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}

# Update the current session
${env:Path} = $ConstructedEnvPath;

I do something similar for a DevEnvRemovePath.ps1.

param(
    [Parameter(Position=0,Mandatory=$true)][String]$PathChange,

    [ValidateSet('Machine', 'User', 'Session')]
    [Parameter(Position=1,Mandatory=$false)][String]$PathContainer='Session'
)

[String]$ConstructedEnvPath = switch ($PathContainer) { "Session"{${env:Path};} default{[Environment]::GetEnvironmentVariable('Path', $containerType);} };
$PathPersisted = $ConstructedEnvPath -split ';';

if ($PathPersisted -contains $PathChange) {
    $PathPersisted = $PathPersisted | Where-Object { $_ -ne $PathChange };

    $ConstructedEnvPath = $PathPersisted -join ";";
}

if ($PathContainer -ne 'Session') 
{
    # Save permanently to Machine, User
    [Environment]::SetEnvironmentVariable("Path", $ConstructedEnvPath, $PathContainer);
}

# Update the current session
${env:Path} = $ConstructedEnvPath;

So far, they seem to work.

header('HTTP/1.0 404 Not Found'); not doing anything

Another reason may be if you add any html tag before this redirect. Look carefully, you may left DOCTYPE or any html comment before this line.

React Native: How to select the next TextInput after pressing the "next" keyboard button?

<TextInput placeholder="Nombre"
    ref="1"
    editable={true}
    returnKeyType="next"
    underlineColorAndroid={'#4DB6AC'}
    blurOnSubmit={false}
    value={this.state.First_Name}
    onChangeText={First_Name => this.setState({ First_Name })}
    onSubmitEditing={() => this.focusNextField('2')}
    placeholderTextColor="#797a7a" style={{ marginBottom: 10, color: '#808080', fontSize: 15, width: '100%', }} />

<TextInput placeholder="Apellido"
    ref="2"
    editable={true}
    returnKeyType="next"
    underlineColorAndroid={'#4DB6AC'}
    blurOnSubmit={false}
    value={this.state.Last_Name}
    onChangeText={Last_Name => this.setState({ Last_Name })}
    onSubmitEditing={() => this.focusNextField('3')}
    placeholderTextColor="#797a7a" style={{ marginBottom: 10, color: '#808080', fontSize: 15, width: '100%', }} />

and add method

focusNextField(nextField) {
    this.refs[nextField].focus();
}

In a Git repository, how to properly rename a directory?

You can rename the directory using the file system. Then you can do git rm <old directory> and git add <new directory> (Help page). Then you can commit and push.

Git will detect that the contents are the same and that it's just a rename operation, and it'll appear as a rename entry in the history. You can check that this is the case before the commit using git status

How do I protect javascript files?

Just off the top of my head, you could do something like this (if you can create server-side scripts, which it sounds like you can):

Instead of loading the script like normal, send an AJAX request to a PHP page (it could be anything; I just use it myself). Have the PHP locate the file (maybe on a non-public part of the server), open it with file_get_contents, and return (read: echo) the contents as a string.

When this string returns to the JavaScript, have it create a new script tag, populate its innerHTML with the code you just received, and attach the tag to the page. (You might have trouble with this; innerHTML may not be what you need, but you can experiment.)

If you do this a lot, you might even want to set up a PHP page that accepts a GET variable with the script's name, so that you can dynamically grab different scripts using the same PHP. (Maybe you could use POST instead, to make it just a little harder for other people to see what you're doing. I don't know.)

EDIT: I thought you were only trying to hide the location of the script. This obviously wouldn't help much if you're trying to hide the script itself.

Google Authenticator available as a public service?

The project is open source. I have not used it. But it's using a documented algorithm (noted in the RFC listed on the open source project page), and the authenticator implementations support multiple accounts.

The actual process is straightforward. The one time code is, essentially, a pseudo random number generator. A random number generator is a formula that once given a seed, or starting number, continues to create a stream of random numbers. Given a seed, while the numbers may be random to each other, the sequence itself is deterministic. So, once you have your device and the server "in sync" then the random numbers that the device creates, each time you hit the "next number button", will be the same, random, numbers the server expects.

A secure one time password system is more sophisticated than a random number generator, but the concept is similar. There are also other details to help keep the device and server in sync.

So, there's no need for someone else to host the authentication, like, say OAuth. Instead you need to implement that algorithm that is compatible with the apps that Google provides for the mobile devices. That software is (should be) available on the open source project.

Depending on your sophistication, you should have all you need to implement the server side of this process give the OSS project and the RFC. I do not know if there is a specific implementation for your server software (PHP, Java, .NET, etc.)

But, specifically, you don't need an offsite service to handle this.

Eclipse: How do I add the javax.servlet package to a project?

Right click on your project -> properties -> build path. Add to your build path jar file(s) that have the javax.servlet implemenation. Ite depends on your servlet container or application server what file(s) you need to include, so search for that information.

What are good grep tools for Windows?

Well, beside the Windows port of the GNU grep at:

http://gnuwin32.sourceforge.net/

there's also Borland's grep (very similar to GNU one) available in the freeware Borland's Free C++ Compiler (it's a freeware with command line tools).

Selenium WebDriver How to Resolve Stale Element Reference Exception?

Try waiting for an element like this:

// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> stubbornWait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class)
    .ignoring(StaleElementReferenceException.class);

WebElement foo = stubbornWait.until(new Function<WebDriver, WebElement>() {
    public WebElement apply(WebDriver driver) {
        return driver.findElement(By.id("foo"));
    }
});

How do I get the find command to print out the file size with the file name?

$ find . -name "test*" -exec du -sh {} \;
4.0K    ./test1
0       ./test2
0       ./test3
0       ./test4
$

Scripter World reference

How to subtract days from a plain Date?

I find a problem with the getDate()/setDate() method is that it too easily turns everything into milliseconds, and the syntax is sometimes hard for me to follow.

Instead I like to work off the fact that 1 day = 86,400,000 milliseconds.

So, for your particular question:

today = new Date()
days = 86400000 //number of milliseconds in a day
fiveDaysAgo = new Date(today - (5*days))

Works like a charm.

I use this method all the time for doing rolling 30/60/365 day calculations.

You can easily extrapolate this to create units of time for months, years, etc.

Check If only numeric values were entered in input. (jQuery)

http://docs.jquery.com/Plugins/Validation/CustomMethods/phoneUS

Check that out. It should be just what you're looking for. A US phone validation plugin for jQuery.

If you want to do it on your own, you're going to be in for a good amount of work. Check out the isNaN() function. It tells you if it is not a number. You're also going to want to brush up on your regular expressions for validation. If you're using RegEx, you can go without isNaN(), as you'll be testing for that anyway.

How to find patterns across multiple lines using grep?

You can do that very easily if you can use Perl.

perl -ne 'if (/abc/) { $abc = 1; next }; print "Found in $ARGV\n" if ($abc && /efg/); }' yourfilename.txt

You can do that with a single regular expression too, but that involves taking the entire contents of the file into a single string, which might end up taking up too much memory with large files. For completeness, here is that method:

perl -e '@lines = <>; $content = join("", @lines); print "Found in $ARGV\n" if ($content =~ /abc.*efg/s);' yourfilename.txt

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

When your browser redirects the user to Google's oAuth page, are you passing as a parameter the redirect URI you want Google's server to return to with the token response? Setting a redirect URI in the console is not a way of telling Google where to go when a login attempt comes in, but rather it's a way of telling Google what the allowed redirect URIs are (so if someone else writes a web app with your client ID but a different redirect URI it will be disallowed); your web app should, when someone clicks the "login" button, send the browser to:

https://accounts.google.com/o/oauth2/auth?client_id=XXXXX&redirect_uri=http://localhost:8080/WEBAPP/youtube-callback.html&response_type=code&scope=https://www.googleapis.com/auth/youtube.upload

(the callback URI passed as a parameter must be url-encoded, btw).

When Google's server gets authorization from the user, then, it'll redirect the browser to whatever you sent in as the redirect_uri. It'll include in that request the token as a parameter, so your callback page can then validate the token, get an access token, and move on to the other parts of your app.

If you visit:

http://code.google.com/p/google-api-java-client/wiki/OAuth2#Authorization_Code_Flow

You can see better samples of the java client there, demonstrating that you have to override the getRedirectUri method to specify your callback path so the default isn't used.

The redirect URIs are in the client_secrets.json file for multiple reasons ... one big one is so that the oAuth flow can verify that the redirect your app specifies matches what your app allows.

If you visit https://developers.google.com/api-client-library/java/apis/youtube/v3 You can generate a sample application for yourself that's based directly off your app in the console, in which (again) the getRedirectUri method is overwritten to use your specific callbacks.

Error importing SQL dump into MySQL: Unknown database / Can't create database

Open the sql file and comment out the line that tries to create the existing database.

C# how to use enum with switch

 public enum Operator
    {
        PLUS, MINUS, MULTIPLY, DIVIDE
    }

    public class Calc
    {
        public void Calculate(int left, int right, Operator op)
        {

            switch (op)
            {
                case Operator.DIVIDE:
                    //Divide
                    break;
                case Operator.MINUS:
                    //Minus
                    break;
                case Operator.MULTIPLY:
                    //...
                    break;
                case Operator.PLUS:
                    //;;
                    break;
                default:
                    throw new InvalidOperationException("Couldn't process operation: " + op);
            }
        }
    }

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

I was using a duplicate Foreign Key Name.

Renaming the FK name solved my problem.

Clarification:

Both tables had a constraint called PK1, FK1, etc. Renaming them/making the names unique solved the problem.

How to empty a redis database?

tldr: flushdb clears one database and flushall clears all databases

Clear CURRENT

Delete default or currently selected database (usually `0) with

redis-cli flushdb

Clear SPECIFIC

Delete specific redis database with (e.g. 8 as my target database):

redis-cli -n 8 flushdb 

Clear ALL

Delete all redis databases with

redis-cli flushall

jQuery find() method not working in AngularJS directive

From the docs on angular.element:

find() - Limited to lookups by tag name

So if you're not using jQuery with Angular, but relying upon its jqlite implementation, you can't do elm.find('#someid').

You do have access to children(), contents(), and data() implementations, so you can usually find a way around it.

Checkbox for nullable boolean

Found answer in similar question - Rendering Nullable Bool as CheckBox. It's very straightforward and just works:

@Html.CheckBox("RFP.DatesFlexible", Model.RFP.DatesFlexible ?? false)
@Html.Label("RFP.DatesFlexible", "My Dates are Flexible")

It's like accepted answer from @afinkelstein except we don't need special 'editor template'

What is the best way to access redux store outside a react component?

An easy way to have access to the token, is to put the token in the LocalStorage or the AsyncStorage with React Native.

Below an example with a React Native project

authReducer.js

import { AsyncStorage } from 'react-native';
...
const auth = (state = initialState, action) => {
  switch (action.type) {
    case SUCCESS_LOGIN:
      AsyncStorage.setItem('token', action.payload.token);
      return {
        ...state,
        ...action.payload,
      };
    case REQUEST_LOGOUT:
      AsyncStorage.removeItem('token');
      return {};
    default:
      return state;
  }
};
...

and api.js

import axios from 'axios';
import { AsyncStorage } from 'react-native';

const defaultHeaders = {
  'Content-Type': 'application/json',
};

const config = {
  ...
};

const request = axios.create(config);

const protectedRequest = options => {
  return AsyncStorage.getItem('token').then(token => {
    if (token) {
      return request({
        headers: {
          ...defaultHeaders,
          Authorization: `Bearer ${token}`,
        },
        ...options,
      });
    }
    return new Error('NO_TOKEN_SET');
  });
};

export { request, protectedRequest };

For web you can use Window.localStorage instead of AsyncStorage

Ruby Arrays: select(), collect(), and map()

When dealing with a hash {}, use both the key and value to the block inside the ||.

details.map {|key,item|"" == item}

=>[false, false, true, false, false]

What is the purpose of the var keyword and when should I use it (or omit it)?

You should use var keyword unless you intend to have the variable attached to window object in browser. Here's a link that explains scoping and difference between glocal scoping and local scoping with and wihtout var keyword.

When variables get defined without the use of var keyword, what it looks like is a simple “assignment” operation.

When the value is assigned to a variable in javascript, the interpreter first tries to find the “variable declaration” in the same context/scope as that of assignment. When the interpreter executes dummyVariable = 20, it looks up for the declaration of dummyVariable at beginning of the function. (Since all Variable declarations are moved to the beginning of the context by javascript interpreter and this is called hoisting)

You may also want to look at hoisting in javascript

Shell script not running, command not found

Change the first line to the following as pointed out by Marc B

#!/bin/bash 

Then mark the script as executable and execute it from the command line

chmod +x MigrateNshell.sh
./MigrateNshell.sh

or simply execute bash from the command line passing in your script as a parameter

/bin/bash MigrateNshell.sh

Javascript : array.length returns undefined

try this

Object.keys(data).length

If IE < 9, you can loop through the object yourself with a for loop

var len = 0;
var i;

for (i in data) {
    if (data.hasOwnProperty(i)) {
        len++;
    }
}

What does %w(array) mean?

%w(foo bar) is a shortcut for ["foo", "bar"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in zenspider's quickref.

Installing PIL with pip

You should install as described here:

pip install image

What is the difference between encode/decode?

To represent a unicode string as a string of bytes is known as encoding. Use u'...'.encode(encoding).

Example:

    >>> u'æøå'.encode('utf8')
    '\xc3\x83\xc2\xa6\xc3\x83\xc2\xb8\xc3\x83\xc2\xa5'
    >>> u'æøå'.encode('latin1')
    '\xc3\xa6\xc3\xb8\xc3\xa5'
    >>> u'æøå'.encode('ascii')
    UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: 
    ordinal not in range(128)

You typically encode a unicode string whenever you need to use it for IO, for instance transfer it over the network, or save it to a disk file.

To convert a string of bytes to a unicode string is known as decoding. Use unicode('...', encoding) or '...'.decode(encoding).

Example:

   >>> u'æøå'
   u'\xc3\xa6\xc3\xb8\xc3\xa5' # the interpreter prints the unicode object like so
   >>> unicode('\xc3\xa6\xc3\xb8\xc3\xa5', 'latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'
   >>> '\xc3\xa6\xc3\xb8\xc3\xa5'.decode('latin1')
   u'\xc3\xa6\xc3\xb8\xc3\xa5'

You typically decode a string of bytes whenever you receive string data from the network or from a disk file.

I believe there are some changes in unicode handling in python 3, so the above is probably not correct for python 3.

Some good links:

Iterating over arrays in Python 3

While iterating over a list or array with this method:

ar = [10, 11, 12]
for i in ar:
    theSum = theSum + ar[i]

You are actually getting the values of list or array sequentially in i variable. If you print the variable i inside the for loop. You will get following output:

10
11
12

However, in your code you are confusing i variable with index value of array. Therefore, while doing ar[i] will mean ar[10] for the first iteration. Which is of course index out of range throwing IndexError

Edit You can read this for better understanding of different methods of iterating over array or list in Python

How to check if X server is running?

I wrote xdpyprobe program which is intended for this purpose. Unlike xset, xdpyinfo and other general tools, it does not do any extra actions (just checks X server and exits) and it may not produce any output (if "-q" option is specified).

How can strings be concatenated?

Just a comment, as someone may find it useful - you can concatenate more than one string in one go:

>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

Return a 2d array from a function

returning an array of pointers pointing to starting elements of all rows is the only decent way of returning 2d array.