Programs & Examples On #Gamma

Display rows with one or more NaN values in pandas dataframe

Can try this too, almost similar previous answers.

    d = {'filename': ['M66_MI_NSRh35d32kpoints.dat', 'F71_sMI_DMRI51d.dat', 'F62_sMI_St22d7.dat', 'F41_Car_HOC498d.dat', 'F78_MI_547d.dat'], 'alpha1': [0.8016, 0.0, 1.721, 1.167, 1.897], 'alpha2': [0.9283, 0.0, 3.833, 2.809, 5.459], 'gamma1': [1.0, np.nan, 0.23748000000000002, 0.36419, 0.095319], 'gamma2': [0.074804, 0.0, 0.15, 0.3, np.nan], 'chi2min': [39.855990000000006, 1e+25, 10.91832, 7.966335000000001, 25.93468]}
    df = pd.DataFrame(d).set_index('filename')

enter image description here

Count of null values in each column.

df.isnull().sum()

enter image description here

df.isnull().any(axis=1)

enter image description here

How to change icon on Google map marker

we can change the icon of markers, i did it on right click event. Lets see if it works for you...

// Create a Marker
var marker = new google.maps.Marker({
    position: location,
    map: map,
    title:'Sample Tool Tip'
  });


// Set Icon on any event
google.maps.event.addListener(marker, "rightclick", function() {
        marker.setIcon('blank.png'); // set image path here...
});

How can I group data with an Angular filter?

Update

I initially wrote this answer because the old version of the solution suggested by Ariel M. when combined with other $filters triggered an "Infite $diggest Loop Error" (infdig). Fortunately this issue has been solved in the latest version of the angular.filter.

I suggested the following implementation, that didn't have that issue:

angular.module("sbrpr.filters", [])
.filter('groupBy', function () {
  var results={};
    return function (data, key) {
        if (!(data && key)) return;
        var result;
        if(!this.$id){
            result={};
        }else{
            var scopeId = this.$id;
            if(!results[scopeId]){
                results[scopeId]={};
                this.$on("$destroy", function() {
                    delete results[scopeId];
                });
            }
            result = results[scopeId];
        }

        for(var groupKey in result)
          result[groupKey].splice(0,result[groupKey].length);

        for (var i=0; i<data.length; i++) {
            if (!result[data[i][key]])
                result[data[i][key]]=[];
            result[data[i][key]].push(data[i]);
        }

        var keys = Object.keys(result);
        for(var k=0; k<keys.length; k++){
          if(result[keys[k]].length===0)
            delete result[keys[k]];
        }
        return result;
    };
});

However, this implementation will only work with versions prior to Angular 1.3. (I will update this answer shortly providing a solution that works with all versions.)

I've actually wrote a post about the steps that I took to develop this $filter, the problems that I encountered and the things that I learned from it.

Non-conformable arrays error in code

The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

In particular, you'll have to replace this line:

omega   = rgamma(1,a0,1) / L0

with:

omega   = as.vector(rgamma(1,a0,1) / L0)

everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

Here's the modified code that should work:

gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                     a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
    m0      = c(m01, m02) 
    C0      = matrix(nrow = 2, ncol = 2) 
    C0[1,1] = 1 / k01 
    C0[1,2] = 0 
    C0[2,1] = 0 
    C0[2,2] = 1 / k02 
    beta    = mvrnorm(1,m0,C0) 
    omega   = as.vector(rgamma(1,a0,1) / L0)
    draws   = matrix(ncol = 3,nrow = ndraw) 
    it      = -nburn 

    while (it < ndraw) {
        it    = it + 1 
        C1    = solve(solve(C0) + omega * t(X) %*% X) 
        m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
        beta  = mvrnorm(1, m1, C1) 
        a1    = a0 + n / 2 
        L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
        omega = as.vector(rgamma(1, a1, 1) / L1)
        if (it > 0) { 
            draws[it,1] = beta[1]
            draws[it,2] = beta[2]
            draws[it,3] = omega
        }
    }
    return(draws)
}

Matplotlib 2 Subplots, 1 Colorbar

Using make_axes is even easier and gives a better result. It also provides possibilities to customise the positioning of the colorbar. Also note the option of subplots to share x and y axes.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True, sharey=True)
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

cax,kw = mpl.colorbar.make_axes([ax for ax in axes.flat])
plt.colorbar(im, cax=cax, **kw)

plt.show()

How can I query a value in SQL Server XML column

I came up with a simple work around below which is easy to remember too :-)

select * from  
(select cast (xmlCol as varchar(max)) texty
 from myTable (NOLOCK) 
) a 
where texty like '%MySearchText%'

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

PHP compare two arrays and get the matched values not the difference

OK.. We needed to compare a dynamic number of product names...

There's probably a better way... but this works for me...

... because....Strings are just Arrays of characters.... :>}

//  Compare Strings ...  Return Matching Text and Differences with Product IDs...

//  From MySql...
$productID1 = 'abc123';
$productName1 = "EcoPlus Premio Jet 600";   

$productID2 = 'xyz789';
$productName2 = "EcoPlus Premio Jet 800";   

$ProductNames = array(
    $productID1 => $productName1,
    $productID2 => $productName2
);


function compareNames($ProductNames){   

    //  Convert NameStrings to Arrays...    
    foreach($ProductNames as $id => $product_name){
        $Package1[$id] = explode(" ",$product_name);    
    }

    // Get Matching Text...
    $Matching = call_user_func_array('array_intersect', $Package1 );
    $MatchingText = implode(" ",$Matching);

    //  Get Different Text...
    foreach($Package1 as $id => $product_name_chunks){
        $Package2 = array($product_name_chunks,$Matching);
        $diff = call_user_func_array('array_diff', $Package2 );
        $DifferentText[$id] = trim(implode(" ", $diff));
    }

    $results[$MatchingText]  = $DifferentText;              
    return $results;    
}

$Results =  compareNames($ProductNames);

print_r($Results);

// Gives us this...
[EcoPlus Premio Jet] 
        [abc123] => 600
        [xyz789] => 800

"inconsistent use of tabs and spaces in indentation"

I use Notepad++ and got this error.

In Notepad++ you will see that both the tab and the four spaces are the same, but when you copy your code to Python IDLE you would see the difference and the line with a tab would have more space before it than the others.

To solve the problem, I just deleted the tab before the line then added four spaces.

How to recursively find and list the latest modified files in a directory with subdirectories and times

I have this alias in my .profile that I use quite often:

$ alias | grep xlogs
xlogs='sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R'

So it does what you are looking for (with exception it doesn't traverse change date/time multiple levels) - looks for latest files (*.log and *.trc files in this case); also it only finds files modified in the last day, and then sorts by time and pipes the output through less:

sudo find . \( -name "*.log" -o -name "*.trc" \) -mtime -1 | sudo xargs ls -ltr --color | less -R

PS.: Notice I don't have root on some of the servers, but always have sudo, so you may not need that part.

How to check if a character is upper-case in Python?

x="Alpha_beta_Gamma"
is_uppercase_letter = True in map(lambda l: l.isupper(), x)
print is_uppercase_letter
>>>>True

So you can write it in 1 string

Determine project root from a running node.js application

1- create a file in the project root call it settings.js

2- inside this file add this code

module.exports = {
    POST_MAX_SIZE : 40 , //MB
    UPLOAD_MAX_FILE_SIZE: 40, //MB
    PROJECT_DIR : __dirname
};

3- inside node_modules create a new module name it "settings" and inside the module index.js write this code:

module.exports = require("../../settings");

4- and any time you want your project directory just use

var settings = require("settings");
settings.PROJECT_DIR; 

in this way you will have all project directories relative to this file ;)

How to know if .keyup() is a character key (jQuery)

I wanted to do exactly this, and I thought of a solution involving both the keyup and the keypress events.

(I haven't tested it in all browsers, but I used the information compiled at http://unixpapa.com/js/key.html)

Edit: rewrote it as a jQuery plugin.

(function($) {
    $.fn.normalkeypress = function(onNormal, onSpecial) {
        this.bind('keydown keypress keyup', (function() {
            var keyDown = {}, // keep track of which buttons have been pressed
                lastKeyDown;
            return function(event) {
                if (event.type == 'keydown') {
                    keyDown[lastKeyDown = event.keyCode] = false;
                    return;
                }
                if (event.type == 'keypress') {
                    keyDown[lastKeyDown] = event; // this keydown also triggered a keypress
                    return;
                }

                // 'keyup' event
                var keyPress = keyDown[event.keyCode];
                if ( keyPress &&
                     ( ( ( keyPress.which >= 32 // not a control character
                           //|| keyPress.which == 8  || // \b
                           //|| keyPress.which == 9  || // \t
                           //|| keyPress.which == 10 || // \n
                           //|| keyPress.which == 13    // \r
                           ) &&
                         !( keyPress.which >= 63232 && keyPress.which <= 63247 ) && // not special character in WebKit < 525
                         !( keyPress.which == 63273 )                            && //
                         !( keyPress.which >= 63275 && keyPress.which <= 63277 ) && //
                         !( keyPress.which === event.keyCode && // not End / Home / Insert / Delete (i.e. in Opera < 10.50)
                            ( keyPress.which == 35  || // End
                              keyPress.which == 36  || // Home
                              keyPress.which == 45  || // Insert
                              keyPress.which == 46  || // Delete
                              keyPress.which == 144    // Num Lock
                              )
                            )
                         ) ||
                       keyPress.which === undefined // normal character in IE < 9.0
                       ) &&
                     keyPress.charCode !== 0 // not special character in Konqueror 4.3
                     ) {

                    // Normal character
                    if (onNormal) onNormal.call(this, keyPress, event);
                } else {
                    // Special character
                    if (onSpecial) onSpecial.call(this, event);
                }
                delete keyDown[event.keyCode];
            };
        })());
    };
})(jQuery);

Get parent of current directory from Python script

This worked for me (I am on Ubuntu):

import os
os.path.dirname(os.getcwd())

Xcode is not currently available from the Software Update server

Command + Space

Search for Xcode

Open it and accept license

Then run again from terminal xcode-select --install

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

The solution for me was to set the AppPool from using the AppPoolIdentity to the NetworkService identity.

Oracle: Import CSV file

Another solution you can use is SQL Developer.

With it, you have the ability to import from a csv file (other delimited files are available).

Just open the table view, then:

  • choose actions
  • import data
  • find your file
  • choose your options.

You have the option to have SQL Developer do the inserts for you, create an sql insert script, or create the data for a SQL Loader script (have not tried this option myself).

Of course all that is moot if you can only use the command line, but if you are able to test it with SQL Developer locally, you can always deploy the generated insert scripts (for example).

Just adding another option to the 2 already very good answers.

How to set recurring schedule for xlsm file using Windows Task Scheduler

Better to use a as you indicated

  1. Create a simple vbs, which is a text file with a .vbs extension (see sample code below)
  2. Use the Task Scheduler to run the vbs
  3. Use the vbs to open the workbook at the scheduled time and then either:
    • use the Private Sub Workbook_Open() event in the ThisWorkbook module to run code when the file is opened
    • more robustly (as macros may be disabled on open), use Application.Run in the vbs to run the macro

See this example of the later approach at Running Excel on Windows Task Scheduler

sample vbs

Dim ObjExcel, ObjWB
Set ObjExcel = CreateObject("excel.application")
'vbs opens a file specified by the path below
Set ObjWB = ObjExcel.Workbooks.Open("C:\temp\rod.xlsm")
'either use the Workbook Open event (if macros are enabled), or Application.Run

ObjWB.Close False
ObjExcel.Quit
Set ObjExcel = Nothing

How to get first object out from List<Object> using Linq

[0] or .First() will give you the same performance whatever happens.
But your Dictionary could contains IEnumerable<Component> instead of List<Component>, and then you cant use the [] operator. That is where the difference is huge.

So for your example, it doesn't really matters, but for this code, you have no choice to use First():

var dic = new Dictionary<String, IEnumerable<Component>>();
foreach (var components in dic.Values)
{
    // you can't use [0] because components is an IEnumerable<Component>
    var firstComponent = components.First(); // be aware that it will throw an exception if components is empty.
    var depCountry = firstComponent.ComponentValue("Dep");
}

Python Write bytes to file

Write bytes and Create the file if not exists:

f = open('./put/your/path/here.png', 'wb')
f.write(data)
f.close()

wb means open the file in write binary mode.

Credentials for the SQL Server Agent service are invalid

In my case password was expired. Change the password and try the step again.

How to round up the result of integer division?

A generic method, whose result you can iterate over may be of interest:

public static Object[][] chunk(Object[] src, int chunkSize) {

    int overflow = src.length%chunkSize;
    int numChunks = (src.length/chunkSize) + (overflow>0?1:0);
    Object[][] dest = new Object[numChunks][];      
    for (int i=0; i<numChunks; i++) {
        dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];
        System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); 
    }
    return dest;
}

Java: Instanceof and Generics

Or you could catch a failed attempt to cast into E eg.

public int indexOf(Object arg0){
  try{
    E test=(E)arg0;
    return doStuff(test);
  }catch(ClassCastException e){
    return -1;
  }
}

Converting int to string in C

If you really want to use itoa, you need to include the standard library header.

#include <stdlib.h>

I also believe that if you're on Windows (using MSVC), then itoa is actually _itoa.

See http://msdn.microsoft.com/en-us/library/yakksftt(v=VS.100).aspx

Then again, since you're getting a message from collect2, you're likely running GCC on *nix.

How do I increment a DOS variable in a FOR /F loop?

What about this simple code, works for me and on Windows 7

set cntr=1
:begin
echo %cntr%
set /a cntr=%cntr%+1
if %cntr% EQU 1000 goto end
goto begin

:end

Remove accents/diacritics in a string in JavaScript

There's a lot out there, but I think this one is simple and good enough:

 function remove_accents(strAccents) {
    var strAccents = strAccents.split('');
    var strAccentsOut = new Array();
    var strAccentsLen = strAccents.length;
    var accents =    "ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž";
    var accentsOut = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
    for (var y = 0; y < strAccentsLen; y++) {
        if (accents.indexOf(strAccents[y]) != -1) {
            strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
        } else
            strAccentsOut[y] = strAccents[y];
    }
    strAccentsOut = strAccentsOut.join('');

    return strAccentsOut;
}

If you also want to remove special characters and transform spaces and hyphens in underscores, do this:

string = remove_accents(string);
string = string.replace(/[^a-z0-9\s]/gi, '').replace(/[-\s]/g, '_');

Loading inline content using FancyBox

The solution is very simple, but took me about 2 hours and half the hair on my head to find it.

Simply wrap your content with a (redundant) div that has display: none and Bob is your uncle.

<div style="display: none">
    <div id="content-div">Some content here</div>
</div>

Voila

HTTP requests and JSON parsing in Python

just import requests and use from json() method :

source = requests.get("url").json()
print(source)

OR you can use this :

import json,urllib.request
data = urllib.request.urlopen("url").read()
output = json.loads(data)
print (output)

How to download a Nuget package without nuget.exe or Visual Studio extension?

Although building the URL or using tools is still possible, it is not needed anymore.

https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.

(at the bottom of the right column).


Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)

Example of EntityFramework's detail page

How to place object files in separate subdirectory

The VPATH lines are wrong, they should be

vpath %.c  src
vpath %.h  src

i.e. not capital and without the = . As it is now, it doesn't find the .h file and thinks it is a target to be made.

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

Making a POST call instead of GET using urllib2

url="https://myserver/post_service"
data["name"] = "joe"
data["age"] = "20"
data_encoded = urllib2.urlencode(data)
print urllib2.urlopen(url + "?" + data_encoded).read()

May be this can help

Mocking methods of local scope objects with Mockito

If you really want to avoid touching this code, you can use Powermockito (PowerMock for Mockito).

With this, amongst many other things, you can mock the construction of new objects in a very easy way.

"column not allowed here" error in INSERT statement

Try using varchar2 instead of varchar and use this :

INSERT INTO LOCATION VALUES('PQ95VM','HAPPY_STREET','FRANCE');

What parameters should I use in a Google Maps URL to go to a lat-lon?

If you only have degrees minutes seconds you can pass them on the url :

https://maps.google.com/maps?q=latDegrees latMinutes latSeconds longDegrees longMinutes longSeconds 

substitute in %20 for the spaces

python list in sql query as parameter

If you're using PostgreSQL with the Psycopg2 library you can let its tuple adaption do all the escaping and string interpolation for you, e.g:

ids = [1,2,3]
cur.execute(
  "SELECT * FROM foo WHERE id IN %s",
  [tuple(ids)])

i.e. just make sure that you're passing the IN parameter as a tuple. if it's a list you can use the = ANY array syntax:

cur.execute(
  "SELECT * FROM foo WHERE id = ANY (%s)",
  [list(ids)])

note that these both will get turned into the same query plan so you should just use whichever is easier. e.g. if your list comes in a tuple use the former, if they're stored in a list use the latter.

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

Getting only hour/minute of datetime

Just use Hour and Minute properties

var date = DateTime.Now;
date.Hour;
date.Minute;

Or you can easily zero the seconds using

var zeroSecondDate = date.AddSeconds(-date.Second);

How to append data to div using JavaScript?

you can use jQuery. which make it very simple.

just download the jQuery file add jQuery into your HTML
or you can user online link:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

and try this:

 $("#divID").append(data);

load json into variable

_x000D_
_x000D_
var itens = null;_x000D_
$.getJSON("yourfile.json", function(data) {_x000D_
  itens = data;_x000D_
  itens.forEach(function(item) {_x000D_
    console.log(item);_x000D_
  });_x000D_
});_x000D_
console.log(itens);
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How might I schedule a C# Windows Service to perform a task daily?

I would suggest that you use a timer, but set it to check every 45 seconds, not minute. Otherwise you can run into situations where with heavy load, the check for a particular minute is missed, because between the time the timer triggers and the time your code runs and checks the current time, you might have missed the target minute.

Android - Back button in the title bar

If your activity does extend Activity

public class YourActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xxx);

        getActionBar().setHomeButtonEnabled(true);

        [...]
    }

    [...]
}

If your action extends AppCompatActivity

public class YourActivity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_xxx);

            getSupportActionBar().setHomeButtonEnabled(true);

            [...]
        }

        [...]
    }

Nothing more to do, See Add up action

[OPTIONAL] To explicitly define parent activity modify your Manifest.xml like this:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.YourActivity "
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

See Specify the Parent Activity

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

Solutions revolve around:

  • changing MySQL's permissions

    sudo chown -R _mysql:mysql /usr/local/var/mysql
    
  • Starting a MySQL process

    sudo mysql.server start
    

Just to add on a lot of great and useful answers that have been provided here and from many different posts, try specifying the host if the above commands did not resolve this issue for you, i.e

mysql -u root -p h127.0.0.1

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Most of what I write has already been covered by Pressacco, but this is specific to SpecFlow.

I was getting this message for the <specFlow> element and therefore I added a specflow.xsd file to the solution this answer (with some modifications to allow for the <plugins> element).

Thereafter I (like Pressacco), right clicked within the file buffer of app.config and selected properties, and within Schemas, I added "specflow.xsd" to the end. The entirety of Schemas now reads:

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\1033\DotNetConfig.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\EntityFrameworkConfig_6_1_0.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\RazorCustomSchema.xsd" "specflow.xsd"

Easiest way to toggle 2 classes in jQuery

If your element exposes class A from the start, you can write:

$(element).toggleClass("A B");

This will remove class A and add class B. If you do that again, it will remove class B and reinstate class A.

If you want to match the elements that expose either class, you can use a multiple class selector and write:

$(".A, .B").toggleClass("A B");

HTML 5 Favicon - Support?

The answers provided (at the time of this post) are link only answers so I thought I would summarize the links into an answer and what I will be using.

When working to create Cross Browser Favicons (including touch icons) there are several things to consider.

The first (of course) is Internet Explorer. IE does not support PNG favicons until version 11. So our first line is a conditional comment for favicons in IE 9 and below:

<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

To cover the uses of the icon create it at 32x32 pixels. Notice the rel="shortcut icon" for IE to recognize the icon it needs the word shortcut which is not standard. Also we wrap the .ico favicon in a IE conditional comment because Chrome and Safari will use the .ico file if it is present, despite other options available, not what we would like.

The above covers IE up to IE 9. IE 11 accepts PNG favicons, however, IE 10 does not. Also IE 10 does not read conditional comments thus IE 10 won't show a favicon. With IE 11 and Edge available I don't see IE 10 in widespread use, so I ignore this browser.

For the rest of the browsers we are going to use the standard way to cite a favicon:

<link rel="icon" href="path/to/favicon.png">

This icon should be 196x196 pixels in size to cover all devices that may use this icon.

To cover touch icons on mobile devices we are going to use Apple's proprietary way to cite a touch icon:

<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

Using rel="apple-touch-icon-precomposed" will not apply the reflective shine when bookmarked on iOS. To have iOS apply the shine use rel="apple-touch-icon". This icon should be sized to 180x180 pixels as that is the current size recommend by Apple for the latest iPhones and iPads. I have read Blackberry will also use rel="apple-touch-icon-precomposed".

As a note: Chrome for Android states:

The apple-touch-* are deprecated, and will be supported only for a short time. (Written as of beta for m31 of Chrome).

Custom Tiles for IE 11+ on Windows 8.1+

IE 11+ on Windows 8.1+ does offer a way to create pinned tiles for your site.

Microsoft recommends creating a few tiles at the following size:

Small: 128 x 128

Medium: 270 x 270

Wide: 558 x 270

Large: 558 x 558

These should be transparent images as we will define a color background next.

Once these images are created you should create an xml file called browserconfig.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<browserconfig>
  <msapplication>
    <tile>
      <square70x70logo src="images/smalltile.png"/>
      <square150x150logo src="images/mediumtile.png"/>
      <wide310x150logo src="images/widetile.png"/>
      <square310x310logo src="images/largetile.png"/>
      <TileColor>#009900</TileColor>
    </tile>
  </msapplication>
</browserconfig>

Save this xml file in the root of your site. When a site is pinned IE will look for this file. If you want to name the xml file something different or have it in a different location add this meta tag to the head:

<meta name="msapplication-config" content="path-to-browserconfig/custom-name.xml" />

For additional information on IE 11+ custom tiles and using the XML file visit Microsoft's website.

Putting it all together:

To put it all together the above code would look like this:

<!-- For IE 9 and below. ICO should be 32x32 pixels in size -->
<!--[if IE]><link rel="shortcut icon" href="path/to/favicon.ico"><![endif]-->

<!-- Touch Icons - iOS and Android 2.1+ 180x180 pixels in size. --> 
<link rel="apple-touch-icon-precomposed" href="apple-touch-icon-precomposed.png">

<!-- Firefox, Chrome, Safari, IE 11+ and Opera. 196x196 pixels in size. -->
<link rel="icon" href="path/to/favicon.png">

Windows Phone Live Tiles

If a user is using a Windows Phone they can pin a website to the start screen of their phone. Unfortunately, when they do this it displays a screenshot of your phone, not a favicon (not even the MS specific code referenced above). To make a "Live Tile" for Windows Phone Users for your website one must use the following code:

Here are detailed instructions from Microsoft but here is a synopsis:

Step 1

Create a square image for your website, to support hi-res screens create it at 768x768 pixels in size.

Step 2

Add a hidden overlay of this image. Here is example code from Microsoft:

<div id="TileOverlay" onclick="ToggleTileOverlay()" style='background-color: Highlight; height: 100%; width: 100%; top: 0px; left: 0px; position: fixed; color: black; visibility: hidden'>
  <img src="customtile.png" width="320" height="320" />
  <div style='margin-top: 40px'>
     Add text/graphic asking user to pin to start using the menu...
  </div>
</div>

Step 3

You then can add thew following line to add a pin to start link:

<a href="javascript:ToggleTileOverlay()">Pin this site to your start screen</a>

Microsoft recommends that you detect windows phone and only show that link to those users since it won't work for other users.

Step 4

Next you add some JS to toggle the overlay visibility

<script>
function ToggleTileOverlay() {
 var newVisibility =     (document.getElementById('TileOverlay').style.visibility == 'visible') ? 'hidden' : 'visible';
 document.getElementById('TileOverlay').style.visibility =    newVisibility;
}
</script>

Note on Sizes

I am using one size as every browser will scale down the image as necessary. I could add more HTML to specify multiple sizes if desired for those with a lower bandwidth but I am already compressing the PNG files heavily using TinyPNG and I find this unnecessary for my purposes. Also, according to philippe_b's answer Chrome and Firefox have bugs that cause the browser to load all sizes of icons. Using one large icon may be better than multiple smaller ones because of this.

Further Reading

For those who would like more details see the links below:

How to generate random colors in matplotlib?

Improving the answer https://stackoverflow.com/a/14720445/6654512 to work with Python3. That piece of code would sometimes generate numbers greater than 1 and matplotlib would throw an error.

for X,Y in data:
   scatter(X, Y, c=numpy.random.random(3))

In php, is 0 treated as empty?

From a linguistic point of view empty has a meaning of without value. Like the others said you'll have to use isset() in order to check if a variable has been defined, which is what you do.

How to correctly use the extern keyword in C

When you have that function defined on a different dll or lib, so that the compiler defers to the linker to find it. Typical case is when you are calling functions from the OS API.

Set time to 00:00:00

If you need format 00:00:00 in string, you should use SimpleDateFormat as below. Using "H "instead "h".

Date today = new Date();
SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss"); 
//not SimpleDateFormat("dd-MM-yyyy hh:mm:ss")
Calendar calendarDM = Calendar.getInstance();
calendarDM.setTime(today);
calendarDM.set(Calendar.HOUR, 0);
calendarDM.set(Calendar.MINUTE, 0);
calendarDM.set(Calendar.SECOND, 0);
System.out.println("Current Date: " + ft.format(calendarDM.getTime()));

//Result is: Current Date: 29-10-2018 00:00:00

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

Change Timezone in Lumen or Laravel 5

In Lumen's .env file, specify the timezones. For India, it would be like:

APP_TIMEZONE = 'Asia/Calcutta'
DB_TIMEZONE = '+05:30'

Center Triangle at Bottom of Div

I know this isn't a direct answer to your question, but you could also consider using clip-path, as in this question: https://stackoverflow.com/a/18208889/23341.

What is the correct way to declare a boolean variable in Java?

Not only there is no need to declare it as false first, I would add few other improvements:

  • use boolean instead of Boolean (which can also be null for no reason)

  • assign during declaration:

    boolean isMatch = email1.equals(email2);
    
  • ...and use final keyword if you can:

    final boolean isMatch = email1.equals(email2);
    

Last but not least:

if (isMatch == true)

can be expressed as:

if (isMatch)

which renders the isMatch flag not that useful, inlining it might not hurt readability. I suggest looking for some better courses/tutorials out there...

Uncaught syntaxerror: unexpected identifier?

There are errors here :

var formTag = document.getElementsByTagName("form"), // form tag is an array
selectListItem = $('select'),
makeSelect = document.createElement('select'),
makeSelect.setAttribute("id", "groups");

The code must change to:

var formTag = document.getElementsByTagName("form");
var selectListItem = $('select');
var makeSelect = document.createElement('select');
makeSelect.setAttribute("id", "groups");

By the way, there is another error at line 129 :

var createLi.appendChild(createSubList);

Replace it with:

createLi.appendChild(createSubList);

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

How do I find the location of Python module sources?

I realize this answer is 4 years late, but the existing answers are misleading people.

The right way to do this is never __file__, or trying to walk through sys.path and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).

It's the inspect module—in particular, getfile or getsourcefile.

Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping .pyc to .py files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to .so/.pyd files that don't support __file__; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it.

Meanwhile, every Python version's source from 2.0+ is available online at http://hg.python.org/cpython/file/X.Y/ (e.g., 2.7 or 3.3). So, once you discover that inspect.getfile(datetime) is a .so or .pyd file like /usr/local/lib/python2.7/lib-dynload/datetime.so, you can look it up inside the Modules directory. Strictly speaking, there's no way to be sure of which file defines which module, but nearly all of them are either foo.c or foomodule.c, so it shouldn't be hard to guess that datetimemodule.c is what you want.

ActiveXObject is not defined and can't find variable: ActiveXObject

ActiveXObject is available only on IE browser. So every other useragent will throw an error

On modern browser you could use instead File API or File writer API (currently implemented only on Chrome)

IE8 css selector

2013 update: IE10+ no longer supports conditional comments.

Original answer:

Some people seem to be confused because this does not answer the letter of the question, only the spirit - so for clarification:

There is no such thing as a browser selector. There are hacks that take advantage of bugs and/or glitches in specific browsers' CSS parsers, but relying on these are setting yourself up for failure. There is a standard, accepted way to deal with this:

Use conditional comments to target IE only.

Example:

<!--[if gte IE 8]>
<style>
(your style here)
</style>
<![endif]-->

Everything inside the two <!--> will be ignored by all non-IE browsers as a comment, and IE versions that are less than IE8 will skip it. Only IE8 and greater will process it. 2013 update: IE10+ will also ignore it as a comment.

Differences between ConstraintLayout and RelativeLayout

In addition to @dhaval-jivani answer.

I've updated the project github project to latest version of constraint layout v.1.1.0-beta3

I've measured and compared the time of onCreate method and time between a start of onCreate and end of execution of last preformDraw method which visible in CPU monitor. All test were done on Samsung S5 mini with android 6.0.1 Here results:

Fresh start (first screen opening after application launch)

Relative Layout

OnCreate: 123ms

Last preformDraw time - OnCreate time: 311.3ms

Constraint Layout

OnCreate: 120.3ms

Last preformDraw time - OnCreate time: 310ms

Besides that, I've checked performance test from this article , here the code and found that on loop counts less than 100 constraint layout variant is faster during execution of inflating, measure, and layout then variants with Relative Layout. And on old Android devices, like Samsung S3 with Android 4.3, the difference is bigger.

As a conclusion I agree with comments from the article:

Does it worth to refactor old views switch on it from RelativeLayout or LinearLayout?

As always: It depends

I wouldn’t refactor anything unless you either have a performance problem with your current layout hierarchy or you want to make significant changes to the layout anyway. Though I haven’t measured it lately, I haven’t found any performance issues in the last releases. So I think you should be safe to use it. but – as I’v said – don’t just migrate for the sake of migrating. Only do so, if there’s a need for and benefit from it. For new layouts, though, I nearly always use ConstraintLayout. It’s so much better compare to what we had before.

How to keep footer at bottom of screen

use this style

min-height:250px;
height:auto;

CSS3 Fade Effect

It's possible, use the structure below:

<li><a><span></span></a></li>
<li><a><span></span></a></li>

etc...

Where the <li> contains an <a> anchor tag that contains a span as shown above. Then insert the following css:

  • LI get position: relative;
  • Give <a> tag a height, width
  • Set <span> width & height to 100%, so that both <a> and <span> have same dimensions
  • Both <a> and <span> get position: relative;.
  • Assign the same background image to each element
  • <a> tag will have the 'OFF' background-position, and the <span> will have the 'ON' background-poisiton.
  • For 'OFF' state use opacity 0 for <span>
  • For 'ON' :hover state use opacity 1 for <span>
  • Set the -webkit or -moz transition on the <span> element

You'll have the ability to use the transition effect while still defaulting to the old background-position swap. Don't forget to insert IE alpha filter.

Java program to get the current date without timestamp

A java.util.Date object is a kind of timestamp - it contains a number of milliseconds since January 1, 1970, 00:00:00 UTC. So you can't use a standard Date object to contain just a day / month / year, without a time.

As far as I know, there's no really easy way to compare dates by only taking the date (and not the time) into account in the standard Java API. You can use class Calendar and clear the hour, minutes, seconds and milliseconds:

Calendar cal = Calendar.getInstance();
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.AM_PM);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);

Do the same with another Calendar object that contains the date that you want to compare it to, and use the after() or before() methods to do the comparison.

As explained into the Javadoc of java.util.Calendar.clear(int field):

The HOUR_OF_DAY, HOUR and AM_PM fields are handled independently and the the resolution rule for the time of day is applied. Clearing one of the fields doesn't reset the hour of day value of this Calendar. Use set(Calendar.HOUR_OF_DAY, 0) to reset the hour value.

edit - The answer above is from 2010; in Java 8, there is a new date and time API in the package java.time which is much more powerful and useful than the old java.util.Date and java.util.Calendar classes. Use the new date and time classes instead of the old ones.

How to show only next line after the matched one?

Piping is your friend...

Use grep -A1 to show the next line after a match, then pipe the result to tail and only grab 1 line,

cat logs/info.log | grep "term" -A1 | tail -n 1

How can I read an input string of unknown length?

Take a character pointer to store required string.If you have some idea about possible size of string then use function

char *fgets (char *str, int size, FILE* file);`

else you can allocate memory on runtime too using malloc() function which dynamically provides requested memory.

Form Validation With Bootstrap (jQuery)

Check this library, it's completable with booth bootstrap 3 and bootstrap 4

jQuery

<form>
    <div class="form-group">
        <input class="form-control" data-validator="required|min:4|max:10">
    </div>
</form>

Javascript

$(document).on('blur', '[data-validator]', function () {
    new Validator($(this));
});

push() a two-dimensional array

You have some errors in your code:

  1. Use myArray[i].push( 0 ); to add a new column. Your code (myArray[i][j].push(0);) would work in a 3-dimensional array as it tries to add another element to an array at position [i][j].
  2. You only expand (col-d)-many columns in all rows, even in those, which haven't been initialized yet and thus have no entries so far.

One correct, although kind of verbose version, would be the following:

var r = 3; //start from rows 3

var rows = 8;
var cols = 7;

// expand to have the correct amount or rows
for( var i=r; i<rows; i++ ) {
  myArray.push( [] );
}

// expand all rows to have the correct amount of cols
for (var i = 0; i < rows; i++)
{
    for (var j =  myArray[i].length; j < cols; j++)
    {
        myArray[i].push(0);
    }
}

What is tempuri.org?

http://en.wikipedia.org/wiki/Tempuri

tempuri.org is the default namespace URI used by Microsoft development products, like Visual Studio.

How do I update Anaconda?

On Mac, open a terminal and run the following two commands.

conda update conda
conda update anaconda

Make sure to run each command multiple times to update to the current version.

How to store a dataframe using Pandas

Although there are already some answers I found a nice comparison in which they tried several ways to serialize Pandas DataFrames: Efficiently Store Pandas DataFrames.

They compare:

  • pickle: original ASCII data format
  • cPickle, a C library
  • pickle-p2: uses the newer binary format
  • json: standardlib json library
  • json-no-index: like json, but without index
  • msgpack: binary JSON alternative
  • CSV
  • hdfstore: HDF5 storage format

In their experiment, they serialize a DataFrame of 1,000,000 rows with the two columns tested separately: one with text data, the other with numbers. Their disclaimer says:

You should not trust that what follows generalizes to your data. You should look at your own data and run benchmarks yourself

The source code for the test which they refer to is available online. Since this code did not work directly I made some minor changes, which you can get here: serialize.py I got the following results:

time comparison results

They also mention that with the conversion of text data to categorical data the serialization is much faster. In their test about 10 times as fast (also see the test code).

Edit: The higher times for pickle than CSV can be explained by the data format used. By default pickle uses a printable ASCII representation, which generates larger data sets. As can be seen from the graph however, pickle using the newer binary data format (version 2, pickle-p2) has much lower load times.

Some other references:

Garbage collector in Android

I would say no, because the Developer docs on RAM usage state:

...
GC_EXPLICIT

An explicit GC, such as when you call gc() (which you should avoid calling and instead trust the GC to run when needed).

...

I've highlighted the relevant part in bold.

Have a look at the YouTube series, Android Performance Patterns - it will show you tips on managing your app's memory usage (such as using Android's ArrayMaps and SparseArrays instead of HashMaps).

How to check identical array in most efficient way?

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

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

    return true;
}

angular 2 how to return data from subscribe

You just can't return the value directly because it is an async call. An async call means it is running in the background (actually scheduled for later execution) while your code continues to execute.

You also can't have such code in the class directly. It needs to be moved into a method or the constructor.

What you can do is not to subscribe() directly but use an operator like map()

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }
}

In addition, you can combine multiple .map with the same Observables as sometimes this improves code clarity and keeps things separate. Example:

validateResponse = (response) => validate(response);

parseJson = (json) => JSON.parse(json);

fetchUnits() {
    return this.http.get(requestUrl).map(this.validateResponse).map(this.parseJson);
}

This way an observable will be return the caller can subscribe to

export class DataComponent{
    someMethod() {
      return this.http.get(path).map(res => {
        return res.json();
      });
    }

    otherMethod() {
      this.someMethod().subscribe(data => this.data = data);
    }
}

The caller can also be in another class. Here it's just for brevity.

data => this.data = data

and

res => return res.json()

are arrow functions. They are similar to normal functions. These functions are passed to subscribe(...) or map(...) to be called from the observable when data arrives from the response. This is why data can't be returned directly, because when someMethod() is completed, the data wasn't received yet.

Password encryption/decryption code in .NET

You can use the managed .Net cryptography library, then save the encrypted string into the database. When you want to verify the password you can compare the stored database string with the hashed value of the user input. See here for more info about SHA512Managed

using System.Security.Cryptography;

    public static string EncryptSHA512Managed(string password)
    {
        UnicodeEncoding uEncode = new UnicodeEncoding();
        byte[] bytPassword = uEncode.GetBytes(password);
        SHA512Managed sha = new SHA512Managed();
        byte[] hash = sha.ComputeHash(bytPassword);
        return Convert.ToBase64String(hash);
    }

Python copy files to a new directory and rename if file name already exists

I would say you have an indentation problem, at least as you wrote it here:

while not os.path.exists(file + "_" + str(i) + extension):
   i+=1
   print "Already 2x exists..."
   print "Renaming"
   shutil.copy(path, file + "_" + str(i) + extension)

should be:

while os.path.exists(file + "_" + str(i) + extension):
    i+=1
print "Already 2x exists..."
print "Renaming"
shutil.copy(path, file + "_" + str(i) + extension)

Check this out, please!

MySQL select rows where left join is null

You could use the following query:

SELECT  table1.id 
FROM    table1 
        LEFT JOIN table2 
            ON table1.id IN (table2.user_one, table2.user_two)
WHERE   table2.user_one IS NULL;

Although, depending on your indexes on table2 you may find that two joins performs better:

SELECT  table1.id 
FROM    table1 
        LEFT JOIN table2 AS t1
            ON table1.id = t1.user_one
        LEFT JOIN table2 AS t2
            ON table1.id = t2.user_two
WHERE   t1.user_one IS NULL
AND     t2.user_two IS NULL;

How to avoid 'undefined index' errors?

In my case, I get it worked by defining the default value if the submitted data is empty. Here is what I finally did (using PHP7.3.5):

if(empty($_POST['auto'])){ $_POST['auto'] = ""; }

link_to image tag. how to add class to a tag

You can also try this

<li><%= link_to "", application_welcome_path, class: "navbar-brand metas-logo"    %></li>

Where "metas-logo" is a css class with a background image

Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence?

It's a pity that both of the answers analyze the problem but didn't give a direct answer. Let's see the code.

Z = np.array([1.0, 1.0, 1.0, 1.0])  

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N+1, Nlayers))
kOUT = np.zeros(N + 1)

for i in xrange(N):
    # store the i-th result of
    # function "func" in i-th item in kOUT
    kOUT[i] = func(TempLake[i], Z)

The error shows that you set the ith item of kOUT(dtype:int) into an array. Here every item in kOUT is an int, can't directly assign to another datatype. Hence you should declare the data type of kOUT when you create it. For example, like:

Change the statement below:

kOUT = np.zeros(N + 1)

into:

kOUT = np.zeros(N + 1, dtype=object)

or:

kOUT = np.zeros((N + 1, N + 1))

All code:

import numpy as np
Z = np.array([1.0, 1.0, 1.0, 1.0])

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B

Nlayers = Z.size
N = 3
TempLake = np.zeros((N + 1, Nlayers))

kOUT = np.zeros(N + 1, dtype=object)
for i in xrange(N):
    kOUT[i] = func(TempLake[i], Z)

Hope it can help you.

jQuery, checkboxes and .is(":checked")

If you anticipate this rather unwanted behaviour, then one away around it would be to pass an extra parameter from the jQuery.trigger() to the checkbox's click handler. This extra parameter is to notify the click handler that click has been triggered programmatically, rather than by the user directly clicking on the checkbox itself. The checkbox's click handler can then invert the reported check status.

So here's how I'd trigger the click event on a checkbox with the ID "myCheckBox". Note that I'm also passing an object parameter with an single member, nonUI, which is set to true:

$("#myCheckbox").trigger('click', {nonUI : true})

And here's how I handle that in the checkbox's click event handler. The handler function checks for the presence of the nonUI object as its second parameter. (The first parameter is always the event itself.) If the parameter is present and set to true then I invert the reported .checked status. If no such parameter is passed in - which there won't be if the user simply clicked on the checkbox in the UI - then I report the actual .checked status:

$("#myCheckbox").click(function(e, parameters) {
   var nonUI = false;
        try {
            nonUI = parameters.nonUI;
        } catch (e) {}
        var checked = nonUI ? !this.checked : this.checked;
        alert('Checked = ' + checked);
    });

JSFiddle version at http://jsfiddle.net/BrownieBoy/h5mDZ/

I've tested with Chrome, Firefox and IE 8.

What does InitializeComponent() do, and how does it work in WPF?

The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!

How to create a file in a directory in java?

To create a file and write some string there:

BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write("");         // for empty file
bufferedWriter.close();

This works for Mac and PC.

How to get a vCard (.vcf file) into Android contacts from website

Just to let you know: I just tried it using a vCard 2.1 file created according to the vCard 2.1 spec. I found that vCard 2.1, despite being an old version, already covered everything I needed, including a base64-encoded photo and international character sets.

It worked perfectly on my unmodified Android 4.1.1 device (Galaxy S3). It also worked on an old iPhone 3GS (iOS 5, via the Evernote app) and a coworker's unmodified old Android 2.1 device. You only need to set the Content-disposition to attachment as suggested above.

A minor problem was that I triggered the VCF download using a QR code, which I scanned with the Microsoft Tag app. That app told me Android couldn't handle the text/x-vcard media type (or just text/vcard, no matter). Once I opened the link in a Web browser (I tried Chrome and the Android default browser), it worked fine.

How to reference a file for variables using Bash?

For preventing naming conflicts, only import the variables that you need:

variableInFile () {
    variable="${1}"
    file="${2}"

    echo $(
        source "${file}";
        eval echo \$\{${variable}\}
    )
}

What are the differences between "git commit" and "git push"?

in layman terms, git commit is the step before git push you run them in that order to successfully git your file to github.

What does += mean in Python?

a += b is essentially the same as a = a + b, except that:

  • + always returns a newly allocated object, but += should (but doesn't have to) modify the object in-place if it's mutable (e.g. list or dict, but int and str are immutable).

  • In a = a + b, a is evaluated twice.

  • Python: Simple Statements

    • A simple statement is comprised within a single logical line.

If this is the first time you encounter the += operator, you may wonder why it matters that it may modify the object in-place instead of building a new one. Here is an example:

# two variables referring to the same list
>>> list1 = []
>>> list2 = list1

# += modifies the object pointed to by list1 and list2
>>> list1 += [0]
>>> list1, list2
([0], [0])

# + creates a new, independent object
>>> list1 = []
>>> list2 = list1
>>> list1 = list1 + [0]
>>> list1, list2
([0], [])

Use of for_each on map elements

I wrote this awhile back to do just what you're looking for.

namespace STLHelpers
{
    //
    // iterator helper type for iterating through the *values* of key/value collections
    //

    /////////////////////////////////////////////
    template<typename _traits>
    struct _value_iterator
    {
        explicit _value_iterator(typename _traits::iterator_type _it)
            : it(_it)
        {
        }

        _value_iterator(const _value_iterator &_other)
            : it(_other.it)
        {
        }

        friend bool operator==(const _value_iterator &lhs, const _value_iterator &rhs)
        {
            return lhs.it == rhs.it;
        }

        friend bool operator!=(const _value_iterator &lhs, const _value_iterator &rhs)
        {
            return !(lhs == rhs);
        }

        _value_iterator &operator++()
        {
            ++it;
            return *this;
        }

        _value_iterator operator++(int)
        {
            _value_iterator t(*this);
            ++*this;
            return t;
        }

        typename _traits::value_type &operator->()
        {
            return **this;
        }

        typename _traits::value_type &operator*()
        {
            return it->second;
        }

        typename _traits::iterator_type it;
    };

    template<typename _tyMap>
    struct _map_iterator_traits
    {
        typedef typename _tyMap::iterator iterator_type;
        typedef typename _tyMap::mapped_type value_type;
    };

    template<typename _tyMap>
    struct _const_map_iterator_traits
    {
        typedef typename _tyMap::const_iterator iterator_type;
        typedef const typename _tyMap::mapped_type value_type;
    };
}

setBackground vs setBackgroundDrawable (Android)

It's deprecated but it still works so you could just use it. But if you want to be completly correct, just for the completeness of it... You'd do something like following:

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    setBackgroundDrawable();
} else {
    setBackground();
}

For this to work you need to set buildTarget api 16 and min build to 7 or something similar.

How to reload/refresh jQuery dataTable?

Try destroy datatable first then setup it again, example

var table;
$(document).ready(function() {
    table = $("#my-datatable").datatable()
    $("#my-button").click(function() {
        table.fnDestroy();
        table = $("#my-datatable").dataTable();
    });
});

How do I tidy up an HTML file's indentation in VI?

With filetype indent on inside my .vimrc, Vim indents HTML files quite nicely.

Simple example with a shiftwidth of 2:

<html>
  <body>
    <p>
    text
    </p>
  </body>
</html>

Using a Glyphicon as an LI bullet point (Bootstrap 3)

If you want happen to be using LESS it can be achieved like so:

li {
    .glyphicon-ok();

    &:before {            
        .glyphicon();            
        margin-left:-25px;
       float:left;
    }
}

PDF Editing in PHP?

We use pdflib to create PDF files from our rails apps. It has bindings for PHP, and a ton of other languages.

We use the commmercial version, but they also have a free/open source version which has some limitations.

Unfortunately, this only allows creation of PDF's.

If you want to open and 'edit' existing files, pdflib do provide a product which does this this, but costs a LOT

AngularJS - Passing data between pages

app.factory('persistObject', function () {

        var persistObject = [];

        function set(objectName, data) {
            persistObject[objectName] = data;
        }
        function get(objectName) {
            return persistObject[objectName];
        }

        return {
            set: set,
            get: get
        }
    });

Fill it with data like this

persistObject.set('objectName', data); 

Get the object data like this

persistObject.get('objectName'); 

How do I center an SVG in a div?

None of these answers worked for me. This is how I did it.

position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);

How can I find where Python is installed on Windows?

To know where Python is installed you can execute where python in your cmd.exe.

what's the default value of char?

The default value of char is null which is '\u0000' as per Unicode chart. Let us see how it works while printing out.

public class Test_Class {   
     char c;
     void printAll() {  
       System.out.println("c = " + c);
    }   
    public static void main(String[] args) {    
    Test_Class f = new Test_Class();    
    f.printAll();   
    } }

Note: The output is blank.

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

I use this simple function for JQuery based project

    var pointerEventToXY = function(e){
      var out = {x:0, y:0};
      if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
        var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
        out.x = touch.pageX;
        out.y = touch.pageY;
      } else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
        out.x = e.pageX;
        out.y = e.pageY;
      }
      return out;
    };

example:

$('a').on('mousedown touchstart', function(e){
  console.log(pointerEventToXY(e)); // will return obj ..kind of {x:20,y:40}
})

hope this will be usefull for you ;)

How to get HTTP Response Code using Selenium WebDriver

I was also having same issue and stuck for some days, but after some research i figured out that we can actually use chrome's "--remote-debugging-port" to intercept requests in conjunction with selenium web driver. Use following Pseudocode as a reference:-

create instance of chrome driver with remote debugging

int freePort = findFreePort();

chromeOptions.addArguments("--remote-debugging-port=" + freePort);

ChromeDriver driver = new ChromeDriver(chromeOptions);`

make a get call to http://127.0.0.1:freePort

String response = makeGetCall( "http://127.0.0.1" + freePort  + "/json" );

Extract chrome's webSocket Url to listen, you can see response and figure out how to extract

String webSocketUrl = response.substring(response.indexOf("ws://127.0.0.1"), response.length() - 4);

Connect to this socket, u can use asyncHttp

socket = maketSocketConnection( webSocketUrl );

Enable network capture

socket.send( { "id" : 1, "method" : "Network.enable" } );

Now chrome will send all network related events and captures them as follows

socket.onMessageReceived( String message ){

    Json responseJson = toJson(message);
    if( responseJson.method == "Network.responseReceived" ){
       //extract status code
    }
}

driver.get("http://stackoverflow.com");

you can do everything mentioned in dev tools site. see https://chromedevtools.github.io/devtools-protocol/ Note:- use chromedriver 2.39 or above.

I hope it helps someone.

reference : Using Google Chrome remote debugging protocol

Execution failed for task ':app:compileDebugAidl': aidl is missing

In my case I downloaded version 22 of Android M and Android 5.1.1 using Android Studio 1.2.1.1 but when I try to do a Hello World this same error showed me

So the solution for me was doing right click in app like the image below and choose "Open Module Settings"

Image 1

then there you have 2 options. I've changed both with the last version I had.

Compile SDK version to API 21 Lollipop

enter image description here

and Build Tools Version to 21.1.2

enter image description here

Finally clean the project and Build

UPDATED

TO Get Android Studio 1.3 follow these steps

  1. Open the Settings window by choosing File > Settings.
  2. Choose the Appearance & Behavior > System Settings > Updates panel.
  3. On the Updates panel, choose the option Automatically check updates for: Canary Chanel.
  4. On the Updates panel, select Check Now to check for the latest canary build. Download and install the build when you are prompted.

Then you'll have something like this to update your Androud Studio to 1.3 and with this you can test Android M

Android 1.3

Update: Real Cause

This bug happens when the versions of SDK, Build Tools and Gradle Plugins doesn't match (in terms of compatibility). The solution is to verify whether you are using the latest version of them or not. The gradle plugins are placed in the build.gradle of the project, and the other versions are on the build.gradle of the module. For example, for SDK 23, you must use the Build Tools 23.0.1 and gradle plugins version 1.3.1.

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

This means that you should filter the properties of evtListeners with the hasOwnProperty method.

Accessing the web page's HTTP Headers in JavaScript

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

Bash Templating: How to build configuration files from templates with Bash?

Taking the answer from ZyX using pure bash but with new style regex matching and indirect parameter substitution it becomes:

#!/bin/bash
regex='\$\{([a-zA-Z_][a-zA-Z_0-9]*)\}'
while read line; do
    while [[ "$line" =~ $regex ]]; do
        param="${BASH_REMATCH[1]}"
        line=${line//${BASH_REMATCH[0]}/${!param}}
    done
    echo $line
done

How can two strings be concatenated?

> tmp = paste("GAD", "AB", sep = ",")
> tmp
[1] "GAD,AB"

I found this from Google by searching for R concatenate strings: http://stat.ethz.ch/R-manual/R-patched/library/base/html/paste.html

Delete files in subfolder using batch script

Use powershell inside your bat file

PowerShell Remove-Item c:\scripts\* -include *.txt -exclude *test* -force -recurse

You can also exclude from removing some specific folder or file:

PowerShell Remove-Item C:/*  -Exclude WINDOWS,autoexec.bat -force -recurse

Get input type="file" value when it has multiple files selected

You use input.files property. It's a collection of File objects and each file has a name property:

onmouseout="for (var i = 0; i < this.files.length; i++) alert(this.files[i].name);"

Zip lists in Python

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: "pip install ipython"

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

jQuery counter to count up to a target number

Try jCounter, it has a customRange setting where you can specify the start and end number, it can count up as well including the fallback you want at the end.

Change the encoding of a file in Visual Studio Code

The existing answers show a possible solution for single files or file types. However, you can define the charset standard in VS Code by following this path:

File > Preferences > Settings > Encoding > Choose your option

This will define a character set as default. Besides that, you can always change the encoding in the lower right corner of the editor (blue symbol line) for the current project.

Create aar file in Android Studio

After following the first and second steps mentioned in the hcpl's answer in the same thread, we added , '*.aar'], dir: 'libs' in the our-android-app-project-based-on-gradle/app/build.gradle file as shown below:

...

dependencies {
       implementation fileTree(include: ['*.jar', '*.aar'], dir: 'libs')

...

Our gradle version is com.android.tools.build:gradle:3.2.1

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.

If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.

Good luck!

(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)

How do I move a file from one location to another in Java?

Try this :-

  boolean success = file.renameTo(new File(Destdir, file.getName()));

How to vertically align <li> elements in <ul>?

Here's a good one:

Set line-height equal to whatever the height is; works like a charm!

E.g:

li {
    height: 30px;
    line-height: 30px;
}

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

How to access Winform textbox control from another class?

Form frm1 = new Form1();
frm1.Controls.Find("control_name",true)[0].Text = "I changed this from another form";

How to find out the MySQL root password

System:

  • CentOS Linux 7
  • mysql Ver 14.14 Distrib 5.7.25

Procedure:

  1. Open two shell sessions, logging in to one as the Linux root user and the other as a nonroot user with access to the mysql command.

  2. In your root session, stop the normal mysqld listener and start a listener which bypasses password authentication (note: this is a significant security risk as anyone with access to the mysql command may access your databases without a password. You may want to close active shell sessions and/or disable shell access before doing this):

    # systemctl stop mysqld
    # /usr/sbin/mysqld --skip-grant-tables -u mysql &

  3. In your nonroot session, log in to mysql and set the mysql root password:

    $ mysql
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

    mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
    Query OK, 0 rows affected, 1 warning (0.01 sec)

    mysql> quit;

  4. In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:

    # kill %1
    # systemctl start mysqld

  5. In your nonroot session, test the new root password you configured above:

    $ mysql -u root -p
    Enter password:
    Welcome to the MySQL monitor. Commands end with ; or \g.
    ...
    mysql>

In C#, how to check if a TCP port is available?

ipGlobalProperties.GetActiveTcpConnections() doesn't return connections in Listen State.

Port can be used for listening, but with no one connected to it the method described above will not work.

How to set a primary key in MongoDB?

The other way is to create Indexes for your collection and make sure that they are unique.

You can find more on the following link

I actually find this pretty simple and easy to implement.

How to use the 'og' (Open Graph) meta tag for Facebook share

Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

The way we do that is with og:meta tags.

The tags look something like this -

  <meta property="og:title" content="Stuffed Cookies" />
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
  <meta property="og:description" content="The Turducken of Cookies" />
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">

You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

Getting value of HTML Checkbox from onclick/onchange events

Use this

<input type="checkbox" onclick="onClickHandler()" id="box" />

<script>
function onClickHandler(){
    var chk=document.getElementById("box").value;

    //use this value

}
</script>

hexadecimal string to byte array in python

Assuming you have a byte string like so

"\x12\x45\x00\xAB"

and you know the amount of bytes and their type you can also use this approach

import struct

bytes = '\x12\x45\x00\xAB'
val = struct.unpack('<BBH', bytes)

#val = (18, 69, 43776)

As I specified little endian (using the '<' char) at the start of the format string the function returned the decimal equivalent.

0x12 = 18

0x45 = 69

0xAB00 = 43776

B is equal to one byte (8 bit) unsigned

H is equal to two bytes (16 bit) unsigned

More available characters and byte sizes can be found here

The advantages are..

You can specify more than one byte and the endian of the values

Disadvantages..

You really need to know the type and length of data your dealing with

How to count the number of files in a directory using Python

os.listdir() will be slightly more efficient than using glob.glob. To test if a filename is an ordinary file (and not a directory or other entity), use os.path.isfile():

import os, os.path

# simple version for working with CWD
print len([name for name in os.listdir('.') if os.path.isfile(name)])

# path joining version for other paths
DIR = '/tmp'
print len([name for name in os.listdir(DIR) if os.path.isfile(os.path.join(DIR, name))])

Evaluating a mathematical expression in a string

eval is evil

eval("__import__('os').remove('important file')") # arbitrary commands
eval("9**9**9**9**9**9**9**9", {'__builtins__': None}) # CPU, memory

Note: even if you use set __builtins__ to None it still might be possible to break out using introspection:

eval('(1).__class__.__bases__[0].__subclasses__()', {'__builtins__': None})

Evaluate arithmetic expression using ast

import ast
import operator as op

# supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
             ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
             ast.USub: op.neg}

def eval_expr(expr):
    """
    >>> eval_expr('2^6')
    4
    >>> eval_expr('2**6')
    64
    >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
    -5.0
    """
    return eval_(ast.parse(expr, mode='eval').body)

def eval_(node):
    if isinstance(node, ast.Num): # <number>
        return node.n
    elif isinstance(node, ast.BinOp): # <left> <operator> <right>
        return operators[type(node.op)](eval_(node.left), eval_(node.right))
    elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
        return operators[type(node.op)](eval_(node.operand))
    else:
        raise TypeError(node)

You can easily limit allowed range for each operation or any intermediate result, e.g., to limit input arguments for a**b:

def power(a, b):
    if any(abs(n) > 100 for n in [a, b]):
        raise ValueError((a,b))
    return op.pow(a, b)
operators[ast.Pow] = power

Or to limit magnitude of intermediate results:

import functools

def limit(max_=None):
    """Return decorator that limits allowed returned values."""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            ret = func(*args, **kwargs)
            try:
                mag = abs(ret)
            except TypeError:
                pass # not applicable
            else:
                if mag > max_:
                    raise ValueError(ret)
            return ret
        return wrapper
    return decorator

eval_ = limit(max_=10**100)(eval_)

Example

>>> evil = "__import__('os').remove('important file')"
>>> eval_expr(evil) #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError:
>>> eval_expr("9**9")
387420489
>>> eval_expr("9**9**9**9**9**9**9**9") #doctest:+IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError:

JQuery get all elements by class name

Alternative solution (you can replace createElement with a your own element)

var mvar = $('.mbox').wrapAll(document.createElement('div')).closest('div').text();
console.log(mvar);

How to check edittext's text is email address or not?

Please follow the following Steps

Step 1 :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_below="@+id/textView_email"
        android:layout_marginTop="40dp"
        android:hint="Email Adderess"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/textView_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Email Validation Example" />

</RelativeLayout>

Step 2:

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

Step 3:

public class MainActivity extends Activity {

private EditText email;

private String valid_email;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initilizeUI();
}

/**
 * This method is used to initialize UI Components
 */
private void initilizeUI() {
    // TODO Auto-generated method stub

    email = (EditText) findViewById(R.id.editText_email);

    email.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            Is_Valid_Email(email); // pass your EditText Obj here.
        }

        public void Is_Valid_Email(EditText edt) {
            if (edt.getText().toString() == null) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else if (isEmailValid(edt.getText().toString()) == false) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else {
                valid_email = edt.getText().toString();
            }
        }

        boolean isEmailValid(CharSequence email) {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
                    .matches();
        } // end of TextWatcher (email)
    });

}

}

How to make <input type="date"> supported on all browsers? Any alternatives?

I was having problems with this, maintaining the UK dd/mm/yyyy format, I initially used the answer from adeneo https://stackoverflow.com/a/18021130/243905 but that didnt work in safari for me so changed to this, which as far as I can tell works all over - using the jquery-ui datepicker, jquery validation.

if ($('[type="date"]').prop('type') !== 'date') {
    //for reloading/displaying the ISO format back into input again
    var val = $('[type="date"]').each(function () {
        var val = $(this).val();
        if (val !== undefined && val.indexOf('-') > 0) {
            var arr = val.split('-');
            $(this).val(arr[2] + '/' + arr[1] + '/' + arr[0]);
        }
    });

    //add in the datepicker
    $('[type="date"]').datepicker(datapickeroptions);

    //stops the invalid date when validated in safari
    jQuery.validator.methods["date"] = function (value, element) {
        var shortDateFormat = "dd/mm/yy";
        var res = true;
        try {
            $.datepicker.parseDate(shortDateFormat, value);
        } catch (error) {
            res = false;
        }
        return res;
    }
}

ORDER BY using Criteria API

For Hibernate 5.2 and above, use CriteriaBuilder as follows

CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
CriteriaQuery<Cat> query = builder.createQuery(Cat.class);
Root<Cat> rootCat = query.from(Cat.class);
Join<Cat,Mother> joinMother = rootCat.join("mother");  // <-attribute name
Join<Mother,Kind> joinMotherKind = joinMother.join("kind");
query.select(rootCat).orderBy(builder.asc(joinMotherKind.get("value")));
Query<Cat> q = sessionFactory.getCurrentSession().createQuery(query);
List<Cat> cats = q.getResultList();

Passing Variable through JavaScript from one html page to another page

Your best option here, is to use the Query String to 'send' the value.

how to get query string value using javascript

  • So page 1 redirects to page2.html?someValue=ABC
  • Page 2 can then read the query string and specifically the key 'someValue'

If this is anything more than a learning exercise you may want to consider the security implications of this though.

Global variables wont help you here as once the page is re-loaded they are destroyed.

How to put/get multiple JSONObjects to JSONArray?

From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:

JSONArray jsonArray=new JSONArray(jsonObject);

JSONArray has constructor to accept object.

Table Naming Dilemma: Singular vs. Plural Names

A TABLE name is ONE definition of a table structure. A VIEW or QUERY name is ONE definition of a view or query of (a or many) tables. A TABLE, VIEW or QUERY may contain one of the following:

0 records 1 record Many records.

Why on earth would you want to put an 's' on the end of a single object name? What do you want to signify by placing this 's' on the end of an object name?

If you want to differentiate, then add '_tbl'. A View is '_vew' (not the silly '_v' convention).

Minimum 3 character suffixing - that stops this discussion dead.

A table is a DB object - no different to any other.

The saving of 3 characters saves nothing except clarity of meaning.

Red ;-)

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

I make it simple, if the layout is same i just put the intent it.

My code like this:

public class RegistrationMenuActivity extends AppCompatActivity implements View.OnClickListener {


    private Button btnCertificate, btnSeminarKit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration_menu);

        initClick();
    }

    private void initClick() {
        btnCertificate = (Button) findViewById(R.id.btn_Certificate);
        btnCertificate.setOnClickListener(this);

        btnSeminarKit = (Button) findViewById(R.id.btn_SeminarKit);
        btnSeminarKit.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_Certificate:
                break;
            case R.id.btn_SeminarKit:
                break;
        }
        Intent intent = new Intent(RegistrationMenuActivity.this, ScanQRCodeActivity.class);
        startActivity(intent);
    }
}

Cannot find pkg-config error

Answer to my question (after several Google searches) revealed the following:

$ curl https://pkgconfig.freedesktop.org/releases/pkg-config-0.29.tar.gz -o pkgconfig.tgz
$ tar -zxf pkgconfig.tgz && cd pkg-config-0.29
$ ./configure && make install

from the following link: Link showing above

Thanks to everyone for their comments, and sorry for my linux/OSX ignorance!

Doing this fixed my issues as mentioned above.

How do you clone a Git repository into a specific folder?

From some reason this syntax is not standing out:

git clone repo-url [folder]

Here folder is an optional path to the local folder (which will be a local repository).

Git clone will also pull code from remote repository into the local repository. In fact it is true:

git clone repo-url  =  git init + git remote add origin repo-url + git pull

Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Got the same error, CHECK THIS : MINOR SILLY MISTAKE

check findviewbyid(R.id.yourID); If you have put the id correct or not.

How to create a generic array in Java?

I have found a quick and easy way that works for me. Note that i have only used this on Java JDK 8. I don't know if it will work with previous versions.

Although we cannot instantiate a generic array of a specific type parameter, we can pass an already created array to a generic class constructor.

class GenArray <T> {
    private T theArray[]; // reference array

    // ...

    GenArray(T[] arr) {
        theArray = arr;
    }

    // Do whatever with the array...
}

Now in main we can create the array like so:

class GenArrayDemo {
    public static void main(String[] args) {
        int size = 10; // array size
        // Here we can instantiate the array of the type we want, say Character (no primitive types allowed in generics)
        Character[] ar = new Character[size];

        GenArray<Character> = new Character<>(ar); // create the generic Array

        // ...

    }
}

For more flexibility with your arrays you can use a linked list eg. the ArrayList and other methods found in the Java.util.ArrayList class.

How do I combine a background-image and CSS3 gradient on the same element?

I was trying to do the same thing. While background-color and background-image exist on separate layers within an object -- meaning they can co-exist -- CSS gradients seem to co-opt the background-image layer.

From what I can tell, border-image seems to have wider support than multiple backgrounds, so maybe that's an alternative approach.

http://articles.sitepoint.com/article/css3-border-images

UPDATE: A bit more research. Seems Petra Gregorova has something working here --> http://petragregorova.com/demos/css-gradient-and-bg-image-final.html

How to draw vertical lines on a given plot in matplotlib

If someone wants to add a legend and/or colors to some vertical lines, then use this:


import matplotlib.pyplot as plt

# x coordinates for the lines
xcoords = [0.1, 0.3, 0.5]
# colors for the lines
colors = ['r','k','b']

for xc,c in zip(xcoords,colors):
    plt.axvline(x=xc, label='line at x = {}'.format(xc), c=c)

plt.legend()
plt.show()

Results:

my amazing plot seralouk

Chrome Fullscreen API

The following test works in Chrome 16 (dev branch) on X86 and Chrome 15 on Mac OSX Lion

http://html5-demos.appspot.com/static/fullscreen.html

Java : Accessing a class within a package, which is the better way?

Import package is for better readability;

Fully qualified class has to be used in special scenarios. For example, same class name in different package, or use reflect such as Class.forName().

Counting Number of Letters in a string variable

string yourWord = "Derp derp";

Console.WriteLine(new string(yourWord.Select(c => char.IsLetter(c) ? '_' : c).ToArray()));

Yields:

____ ____

ObjectiveC Parse Integer from String

Basically, the third parameter in loggedIn should not be an integer, it should be an object of some kind, but we can't know for sure because you did not name the parameters in the method call. Provide the method signature so we can see for sure. Perhaps it takes an NSNumber or something.

How to add color to Github's README.md file

Here is the code you can write color texts

<h3 style="color:#ff0000">Danger</h3>

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

DO NOT Use GUID For Key

ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) 
       Guid.NewGuid().ToString(), myScript, true);

and if you want to do that , call Something Like this function

 public static string GetGuidClear(string x)
 {
      return x.Replace("-", "").Replace("0", "").Replace("1", "")
              .Replace("2",  "").Replace("3", "").Replace("4", "")
              .Replace("5", "").Replace("6", "").Replace("7", "")
              .Replace("8", "").Replace("9", "");
 }

Are duplicate keys allowed in the definition of binary search trees?

Any definition is valid. As long as you are consistent in your implementation (always put equal nodes to the right, always put them to the left, or never allow them) then you're fine. I think it is most common to not allow them, but it is still a BST if they are allowed and place either left or right.

To find first N prime numbers in python

This is my version

import timeit
import math

__author__ = 'rain'


primes = [2]

def is_prime(n):
    for prime in primes:
        if n % prime == 0:
            return False
    return True


def find_nth_prime(n):
    current_index = 0
    while(len(primes) < n):
        if current_index == 0:
            start_value = 3
            end_value = 2 * 2
        else:
            start_value = primes[current_index - 1] * primes[current_index - 1] + 1
            end_value = primes[current_index] * primes[current_index]
        for i in range(start_value, end_value):
            if is_prime(i):
                primes.append(i)
        current_index += 1
    return primes[n-1]


def solve():
    return find_nth_prime(10001)

print solve()

print timeit.timeit(solve, number=10)

I use a sieve to scan primes, it's quite quick

It's take only 3.8e-06 seconds to get 10001th prime (10 times).

How to order a data frame by one descending and one ascending column?

Simple one without rank :

rum[order(rum$I1, -rum$I2, decreasing = TRUE), ]

Get the value of checked checkbox?

This does not directly answer the question, but may help future visitors.


If you want to have a variable always be the current state of the checkbox (rather than having to keep checking its state), you can modify the onchange event to set that variable.

This can be done in the HTML:

<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>

or with JavaScript:

cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})

How to re-index all subarray elements of a multidimensional array?

$result = ['5' => 'cherry', '7' => 'apple'];
array_multisort($result, SORT_ASC);
print_r($result);

Array ( [0] => apple [1] => cherry )

//...
array_multisort($result, SORT_DESC);
//...

Array ( [0] => cherry [1] => apple )

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

Git: How to squash all commits on branch

Checkout the branch for which you would like to squash all the commits into one commit. Let's say it's called feature_branch.

git checkout feature_branch

Step 1:

Do a soft reset of your origin/feature_branch with your local main branch (depending on your needs, you can reset with origin/main as well). This will reset all the extra commits in your feature_branch, but without changing any of your file changes locally.

git reset --soft main

Step 2:

Add all of the changes in your git repo directory, to the new commit that is going to be created. And commit the same with a message.

git add -A && git commit -m "commit message goes here"

Eclipse - "Workspace in use or cannot be created, chose a different one."

I've seen 3 other fixes so far:

  1. in .metadata/, rm .lock file
  2. if 1) doesn't work, try end process javaw.exe etc. to exit the IDE
  3. if 1)&2) doesn't work, try rm .log file in .metadata/, and double check .plugin/.
  4. This always worked for me: relocate .metadata/, open and close eclipse, then overwrite .metadata back

The solution boils down to clean up the .metadata folder with correct contents

How to draw a graph in PHP?

There are a number of libraries available for generating graphs.

More are listed above and here.

How to stretch the background image to fill a div

by using property css:

background-size: cover;

Algorithm to compare two images

Read the paper: Porikli, Fatih, Oncel Tuzel, and Peter Meer. “Covariance Tracking Using Model Update Based on Means on Riemannian Manifolds”. (2006) IEEE Computer Vision and Pattern Recognition.

I was successfully able to detect overlapping regions in images captured from adjacent webcams using the technique presented in this paper. My covariance matrix was composed of Sobel, canny and SUSAN aspect/edge detection outputs, as well as the original greyscale pixels.

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

How can I get the current user's username in Bash?

On the command line, enter

whoami

or

echo "$USER"

To save these values to a variable, do

myvariable=$(whoami)

or

myvariable=$USER

Of course, you don't need to make a variable since that is what the $USER variable is for.

What's the function like sum() but for multiplication? product()?

Actually, Guido vetoed the idea: http://bugs.python.org/issue1093

But, as noted in that issue, you can make one pretty easily:

from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator

reduce(operator.mul, (3, 4, 5), 1)

Conversion failed when converting date and/or time from character string in SQL SERVER 2008

If you're trying to insert in to last_accessed_on, which is a DateTime2, then your issue is with the fact that you are converting it to a varchar in a format that SQL doesn't understand.

If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:

UPDATE  student_queues 
SET  Deleted=0, 
     last_accessed_by='raja', 
     last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'

Or if you want to use CAST, replace with:

CAST('2014-07-23 09:37:00.000' AS datetime2)

This is using the SQL ISO Date Format.

SQL update statement in C#

command.Text = "UPDATE Student 
  SET Address = @add, City = @cit
  Where FirstName = @fn and LastName = @add";

 

Adding a directory to the PATH environment variable in Windows

Aside from all the answers, if you want a nice GUI tool to edit your Windows environment variables you can use Rapid Environment Editor.

Try it! It's safe to use and is awesome!

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

For IIS 7+, as well as adding the httpRuntime maxRequestLength setting you also need to add:

  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="52428800" /> <!--50MB-->
      </requestFiltering>
    </security>
  </system.webServer>

Or in IIS (7):

  • Select the website you want enable to accept large file uploads.
  • In the main window double click 'Request filtering'
  • Select "Edit Feature Settings"
  • Modify the "Maximum allowed content length (bytes)"

How to replicate vector in c?

They would start by hiding the defining a structure that would hold members necessary for the implementation. Then providing a group of functions that would manipulate the contents of the structure.

Something like this:

typedef struct vec
{
    unsigned char* _mem;
    unsigned long _elems;
    unsigned long _elemsize;
    unsigned long _capelems;
    unsigned long _reserve;
};

vec* vec_new(unsigned long elemsize)
{
    vec* pvec = (vec*)malloc(sizeof(vec));
    pvec->_reserve = 10;
    pvec->_capelems = pvec->_reserve;
    pvec->_elemsize = elemsize;
    pvec->_elems = 0;
    pvec->_mem = (unsigned char*)malloc(pvec->_capelems * pvec->_elemsize);
    return pvec;
}

void vec_delete(vec* pvec)
{
    free(pvec->_mem);
    free(pvec);
}

void vec_grow(vec* pvec)
{
    unsigned char* mem = (unsigned char*)malloc((pvec->_capelems + pvec->_reserve) * pvec->_elemsize);
    memcpy(mem, pvec->_mem, pvec->_elems * pvec->_elemsize);
    free(pvec->_mem);
    pvec->_mem = mem;
    pvec->_capelems += pvec->_reserve;
}

void vec_push_back(vec* pvec, void* data, unsigned long elemsize)
{
    assert(elemsize == pvec->_elemsize);
    if (pvec->_elems == pvec->_capelems) {
        vec_grow(pvec);
    }
    memcpy(pvec->_mem + (pvec->_elems * pvec->_elemsize), (unsigned char*)data, pvec->_elemsize);
    pvec->_elems++;    
}

unsigned long vec_length(vec* pvec)
{
    return pvec->_elems;
}

void* vec_get(vec* pvec, unsigned long index)
{
    assert(index < pvec->_elems);
    return (void*)(pvec->_mem + (index * pvec->_elemsize));
}

void vec_copy_item(vec* pvec, void* dest, unsigned long index)
{
    memcpy(dest, vec_get(pvec, index), pvec->_elemsize);
}

void playwithvec()
{
    vec* pvec = vec_new(sizeof(int));

    for (int val = 0; val < 1000; val += 10) {
        vec_push_back(pvec, &val, sizeof(val));
    }

    for (unsigned long index = (int)vec_length(pvec) - 1; (int)index >= 0; index--) {
        int val;
        vec_copy_item(pvec, &val, index);
        printf("vec(%d) = %d\n", index, val);
    }

    vec_delete(pvec);
}

Further to this they would achieve encapsulation by using void* in the place of vec* for the function group, and actually hide the structure definition from the user by defining it within the C module containing the group of functions rather than the header. Also they would hide the functions that you would consider to be private, by leaving them out from the header and simply prototyping them only in the C module.

How to uninstall a package installed with pip install --user

example to uninstall package 'oauth2client' on MacOS:

pip uninstall oauth2client

Rendering HTML elements to <canvas>

Here is code to render arbitrary HTML into a canvas:

function render_html_to_canvas(html, ctx, x, y, width, height) {
    var xml = html_to_xml(html);
    xml = xml.replace(/\#/g, '%23');
    var data = "data:image/svg+xml;charset=utf-8,"+'<svg xmlns="http://www.w3.org/2000/svg" width="'+width+'" height="'+height+'">' +
                        '<foreignObject width="100%" height="100%">' +
                        xml+
                        '</foreignObject>' +
                        '</svg>';

    var img = new Image();
    img.onload = function () {
        ctx.drawImage(img, x, y);
    }
    img.src = data;
}

function html_to_xml(html) {
    var doc = document.implementation.createHTMLDocument('');
    doc.write(html);

    // You must manually set the xmlns if you intend to immediately serialize     
    // the HTML document to a string as opposed to appending it to a
    // <foreignObject> in the DOM
    doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);

    // Get well-formed markup
    html = (new XMLSerializer).serializeToString(doc.body);
    return html;
}

example:

_x000D_
_x000D_
const ctx = document.querySelector('canvas').getContext('2d');
const html = `
<p>this
<p>is <span style="color:red; font-weight: bold;">not</span>
<p><i>xml</i>!
<p><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAABWElEQVQ4jZ2Tu07DQBBFz9jjvEAQqAlQ0CHxERQ0/AItBV9Ew8dQUNBQIho6qCFE4Nhex4u85OHdWAKxzfWsx0d3HpazdGITA4kROjl0ckFrnYJmQlJrKsQZxFOIMyEqIMpADGhSZpikB1hAGsovdxABGuepC/4L0U7xRTG/riG3J8fuvdifPKnmasXp5c2TB1HNPl24gNTnpeqsgmj1eFgayoHvRDWbLBOKJbn9WLGYflCCpmM/2a4Au6/PTjdH+z9lCJQ9vyeq0w/ve2kA3vaOnI6k4Pz+0Y24yP3Gapy+Bw6qdfsCRZfWSWgclCCVXTZu5LZFXKJJ2sepW2KYNCENB3U5pw93zLoDjNK6E7rTFcgbkGYJtiLckxCiw4W1OURsxUE5BokQiQj3JIToVtKwlhsurq+YDYbMBjuU/W3KtT3xIbrpAD7E60lwQohuaMtP8ldI0uMbGfC1r1zyWPUAAAAASUVORK5CYII=">`;
render_html_to_canvas(html, ctx, 0, 0, 300, 150);


function render_html_to_canvas(html, ctx, x, y, width, height) {
  var data = "data:image/svg+xml;charset=utf-8," + '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">' +
    '<foreignObject width="100%" height="100%">' +
    html_to_xml(html) +
    '</foreignObject>' +
    '</svg>';

  var img = new Image();
  img.onload = function() {
    ctx.drawImage(img, x, y);
  }
  img.src = data;
}

function html_to_xml(html) {
  var doc = document.implementation.createHTMLDocument('');
  doc.write(html);

  // You must manually set the xmlns if you intend to immediately serialize     
  // the HTML document to a string as opposed to appending it to a
  // <foreignObject> in the DOM
  doc.documentElement.setAttribute('xmlns', doc.documentElement.namespaceURI);

  // Get well-formed markup
  html = (new XMLSerializer).serializeToString(doc.body);
  return html;
}
_x000D_
<canvas></canvas>
_x000D_
_x000D_
_x000D_

How can I force a hard reload in Chrome for Android

I'm using window.location.reload(true) according to MDN (and this similar question) it forces page to reload from server.

You can execute this code in the browser by typing javascript:location.reload(true) in the address bar.

What is exactly the base pointer and stack pointer? To what do they point?

esp stands for "Extended Stack Pointer".....ebp for "Something Base Pointer"....and eip for "Something Instruction Pointer"...... The stack Pointer points to the offset address of the stack segment. The Base Pointer points to the offset address of the extra segment. The Instruction Pointer points to the offset address of the code segment. Now, about the segments...they are small 64KB divisions of the processors memory area.....This process is known as Memory Segmentation. I hope this post was helpful.

Check if character is number?

you can either use parseInt and than check with isNaN

or if you want to work directly on your string you can use regexp like this:

function is_numeric(str){
    return /^\d+$/.test(str);
}

How to implement a Boolean search with multiple columns in pandas

All the considerations made by @EdChum in 2014 are still valid, but the pandas.Dataframe.ix method is deprecated from the version 0.0.20 of pandas. Directly from the docs:

Warning: Starting in 0.20.0, the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

In subsequent versions of pandas, this method has been replaced by new indexing methods pandas.Dataframe.loc and pandas.Dataframe.iloc.

If you want to learn more, in this post you can find comparisons between the methods mentioned above.

Ultimately, to date (and there does not seem to be any change in the upcoming versions of pandas from this point of view), the answer to this question is as follows:

foo = df.loc[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]

Detect touch press vs long press vs movement?

This code can distinguish between click and movement (drag, scroll). In onTouchEvent set a flag isOnClick, and initial X, Y coordinates on ACTION_DOWN. Clear the flag on ACTION_MOVE (minding that unintentional movement is often detected which can be solved with a THRESHOLD const).

private float mDownX;
private float mDownY;
private final float SCROLL_THRESHOLD = 10;
private boolean isOnClick;

@Override
public boolean onTouchEvent(MotionEvent ev) {
    switch (ev.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mDownX = ev.getX();
            mDownY = ev.getY();
            isOnClick = true;
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            if (isOnClick) {
                Log.i(LOG_TAG, "onClick ");
                //TODO onClick code
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (isOnClick && (Math.abs(mDownX - ev.getX()) > SCROLL_THRESHOLD || Math.abs(mDownY - ev.getY()) > SCROLL_THRESHOLD)) {
                Log.i(LOG_TAG, "movement detected");
                isOnClick = false;
            }
            break;
        default:
            break;
    }
    return true;
}

For LongPress as suggested above, GestureDetector is the way to go. Check this Q&A:

Detecting a long press with Android

Call a global variable inside module

// global.d.ts
declare global {
  namespace NodeJS {
    interface Global {
      bootbox: string // Specify ur type here,use `string` for brief
    }
  }
}

// somewhere else
const bootbox = global.bootbox
// somewhere else
global.bootbox = 'boom'

How can I check if a View exists in a Database?

You can check the availability of the view in various ways

FOR SQL SERVER

use sys.objects

IF EXISTS(
   SELECT 1
   FROM   sys.objects
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
          AND Type_Desc = 'VIEW'
)
BEGIN
    PRINT 'View Exists'
END

use sysobjects

IF NOT EXISTS (
   SELECT 1
   FROM   sysobjects
   WHERE  NAME = '[schemaName].[ViewName]'
          AND xtype = 'V'
)
BEGIN
    PRINT 'View Exists'
END

use sys.views

IF EXISTS (
   SELECT 1
   FROM sys.views
   WHERE OBJECT_ID = OBJECT_ID(N'[schemaName].[ViewName]')
)
BEGIN
    PRINT 'View Exists'
END

use INFORMATION_SCHEMA.VIEWS

IF EXISTS (
   SELECT 1
   FROM   INFORMATION_SCHEMA.VIEWS
   WHERE  table_name = 'ViewName'
          AND table_schema = 'schemaName'
)
BEGIN
    PRINT 'View Exists'
END

use OBJECT_ID

IF EXISTS(
   SELECT OBJECT_ID('ViewName', 'V')
)
BEGIN
    PRINT 'View Exists'
END

use sys.sql_modules

IF EXISTS (
   SELECT 1
   FROM   sys.sql_modules
   WHERE  OBJECT_ID = OBJECT_ID('[schemaName].[ViewName]')
)
BEGIN
   PRINT 'View Exists'
END

Creating a BAT file for python script

If this is a BAT file in a different directory than the current directory, you may see an error like "python: can't open file 'somescript.py': [Errno 2] No such file or directory". This can be fixed by specifying an absolute path to the BAT file using %~dp0 (the drive letter and path of that batch file).

@echo off
python %~dp0\somescript.py %*

(This way you can ignore the c:\ or whatever, because perhaps you may want to move this script)

Get the last element of a std::string

In C++11 and beyond, you can use the back member function:

char ch = myStr.back();

In C++03, std::string::back is not available due to an oversight, but you can get around this by dereferencing the reverse_iterator you get back from rbegin:

char ch = *myStr.rbegin();

In both cases, be careful to make sure the string actually has at least one character in it! Otherwise, you'll get undefined behavior, which is a Bad Thing.

Hope this helps!

How do I do an OR filter in a Django query?

You can use the | operator to combine querysets directly without needing Q objects:

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)

(edit - I was initially unsure if this caused an extra query but @spookylukey pointed out that lazy queryset evaluation takes care of that)

How to auto generate migrations with Sequelize CLI from Sequelize models?

If you don't want to recreate your model from scratch, you can manually generate a migration file using the following CLI command:

sequelize migration:generate --name [name_of_your_migration]

This will generate a blank skeleton migration file. While it doesn't copy your model structure over to the file, I do find it easier and cleaner than regenerating everything. Note: make sure to run the command from the containing directory of your migrations directory; otherwise the CLI will generate a new migration dir for you

How to import functions from different js file in a Vue+webpack+vue-loader project

Say I want to import data into a component from src/mylib.js:

var test = {
  foo () { console.log('foo') },
  bar () { console.log('bar') },
  baz () { console.log('baz') }
}

export default test

In my .Vue file I simply imported test from src/mylib.js:

<script> 
  import test from '@/mylib'

  console.log(test.foo())
  ...
</script>

Batch program to to check if process exists

That's why it's not working because you code something that is not right, that's why it always exit and the script executer will read it as not operable batch file that prevent it to exit and stop so it must be

tasklist /fi "IMAGENAME eq Notepad.exe" 2>NUL | find /I /N "Notepad.exe">NUL
if "%ERRORLEVEL%"=="0" (
msg * Program is running
goto Exit
)
else if "%ERRORLEVEL%"=="1" (
msg * Program is not running
goto Exit
)

rather than

@echo off
tasklist /fi "imagename eq notepad.exe" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

window.open with headers

If you are in control of server side, it might be possible to set header value in query string and send it like that? That way you could parse it from query string if it's not found in the headers.

Just an idea... And you asked for a cunning hack :)

How to convert DateTime to a number with a precision greater than days in T-SQL?

Well, I would do it like this:

select datediff(minute,'1990-1-1',datetime)

where '1990-1-1' is an arbitrary base datetime.

ConnectivityManager getNetworkInfo(int) deprecated

This works for me in Kotlin. Lot of API's are deprecated in Network Manager class so below answer cover all API support.

fun isNetworkAvailable(context: Context): Boolean {
    var result = false
    (context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager).apply {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                result = isCapableNetwork(this,this.activeNetwork)
            } else {
                val networkInfos = this.allNetworks
                for (tempNetworkInfo in networkInfos) {
                    if(isCapableNetwork(this,tempNetworkInfo))
                        result =  true
                }
            }
        }

    return result
}

fun isCapableNetwork(cm: ConnectivityManager,network: Network?): Boolean{
     cm.getNetworkCapabilities(network)?.also {
        if (it.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
            return true
        } else if (it.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
            return true
        }
    }
    return false
}

You will also add below

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

Cannot implicitly convert type from Task<>

You need to make TestGetMethod async too and attach await in front of GetIdList(); will unwrap the task to List<int>, So if your helper function is returning Task make sure you have await as you are calling the function async too.

public Task<List<int>> TestGetMethod()
{
    return GetIdList();
}    

async Task<List<int>> GetIdList()
{
    using (HttpClient proxy = new HttpClient())
    {
        string response = await proxy.GetStringAsync("www.test.com");
        List<int> idList = JsonConvert.DeserializeObject<List<int>>();
        return idList;
    }
}

Another option

public async void TestGetMethod(List<int> results)
{
    results = await GetIdList(); // await will unwrap the List<int>
}

Return Index of an Element in an Array Excel VBA

The only (& even though cumbersome but yet expedient / relatively quick) way I can do this, is to concatenate the any-dimensional array, and reduce it to 1 dimension, with "/[column number]//\|" as the delimiter.

& use a single-cell result multiple lookupall macro function on the this 1-d column.

& then index match to pull out the positions. (usuing multiple find match)

That way you get all matching occurrences of the element/string your looking for, in the original any-dimension array, and their positions. In one cell.

Wish I could write a macro / function for this entire process. It would save me more fuss.

Execute the setInterval function without delay the first time

I stumbled upon this question due to the same problem but none of the answers helps if you need to behave exactly like setInterval() but with the only difference that the function is called immediately at the beginning.

Here is my solution to this problem:

function setIntervalImmediately(func, interval) {
  func();
  return setInterval(func, interval);
}

The advantage of this solution:

  • existing code using setInterval can easily be adapted by substitution
  • works in strict mode
  • it works with existing named functions and closures
  • you can still use the return value and pass it to clearInterval() later

Example:

// create 1 second interval with immediate execution
var myInterval = setIntervalImmediately( _ => {
        console.log('hello');
    }, 1000);

// clear interval after 4.5 seconds
setTimeout( _ => {
        clearInterval(myInterval);
    }, 4500);

To be cheeky, if you really need to use setInterval then you could also replace the original setInterval. Hence, no change of code required when adding this before your existing code:

var setIntervalOrig = setInterval;

setInterval = function(func, interval) {
    func();
    return setIntervalOrig(func, interval);
}

Still, all advantages as listed above apply here but no substitution is necessary.

How to Update a Component without refreshing full page - Angular

Angular will automatically update a component when it detects a variable change .

So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts or via an @Input variable...


an example...

main.html

<app-header [header-data]="headerData"></app-header>

main.component.ts

public headerData:int = 0;

ngOnInit(){
    setInterval(()=>{this.headerData++;}, 250);
}

header.html

<p>{{data}}</p>

header.ts

@Input('header-data') data;

In the above example, the header will recieve the new data every 250ms and thus update the component.


For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks

Get url parameters from a string in .NET

Looks like you should loop over the values of myUri.Query and parse it from there.

 string desiredValue;
 foreach(string item in myUri.Query.Split('&'))
 {
     string[] parts = item.Replace("?", "").Split('=');
     if(parts[0] == "desiredKey")
     {
         desiredValue = parts[1];
         break;
     }
 }

I wouldn't use this code without testing it on a bunch of malformed URLs however. It might break on some/all of these:

  • hello.html?
  • hello.html?valuelesskey
  • hello.html?key=value=hi
  • hello.html?hi=value?&b=c
  • etc

postgresql - sql - count of `true` values

In MySQL, you can do this as well:

SELECT count(*) AS total
     , sum(myCol) AS countTrue --yes, you can add TRUEs as TRUE=1 and FALSE=0 !!
FROM yourTable
;

I think that in Postgres, this works:

SELECT count(*) AS total
     , sum(myCol::int) AS countTrue --convert Boolean to Integer
FROM yourTable
;

or better (to avoid :: and use standard SQL syntax):

SELECT count(*) AS total
     , sum(CAST(myCol AS int)) AS countTrue --convert Boolean to Integer
FROM yourTable
;

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

Git merge develop into feature branch outputs "Already up-to-date" while it's not

Step by step self explaining commands for update of feature branch with the latest code from origin "develop" branch:

git checkout develop
git pull -p
git checkout feature_branch
git merge develop
git push origin feature_branch

Split string into strings by length?

# spliting a string by the length of the string

def len_split(string,sub_string):
    n,sub,str1=list(string),len(sub_string),')/^0*/-'
    for i in range(sub,len(n)+((len(n)-1)//sub),sub+1):
        n.insert(i,str1)   
    n="".join(n)
    n=n.split(str1)
    return n

x="divyansh_looking_for_intership_actively_contact_Me_here"
sub="four"
print(len_split(x,sub))

# Result-> ['divy', 'ansh', 'tiwa', 'ri_l', 'ooki', 'ng_f', 'or_i', 'nter', 'ship', '_con', 'tact', '_Me_', 'here']

How to get selected value from Dropdown list in JavaScript

Direct value should work just fine:

var sv = sel.value;
alert(sv);

The only reason your code might fail is when there is no item selected, then the selectedIndex returns -1 and the code breaks.

How do I subtract minutes from a date in javascript?

This is what I did: see on Codepen

var somedate = 1473888180593;
var myStartDate;
//var myStartDate = somedate - durationInMuntes;

myStartDate = new Date(dateAfterSubtracted('minutes', 100));

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());

function dateAfterSubtracted(range, amount){
    var now = new Date();
    if(range === 'years'){
        return now.setDate(now.getYear() - amount);
    }
    if(range === 'months'){
        return now.setDate(now.getMonth() - amount);
    }
    if(range === 'days'){
        return now.setDate(now.getDate() - amount);
    }
    if(range === 'hours'){
        return now.setDate(now.getHours() - amount);
    }
    if(range === 'minutes'){
        return now.setDate(now.getMinutes() - amount);
    }
    else {
        return null;
    }
}

Check if process returns 0 with batch file

To check whether a process/command returned 0 or not, use the operators && == 0 or not == 0 ||:

Just add operator to your script:

execute_command && (

       echo\Return 0, with no execution error
) || (
        echo\Return non 0, something went wrong
     )

command && echo\Return 0 || echo\Return non 0

How can I check if a URL exists via PHP?

function url_exists($url) {
    $headers = @get_headers($url);
    return (strpos($headers[0],'200')===false)? false:true;
}

MySQL Great Circle Distance (Haversine formula)

I thought my javascript implementation would be a good reference to:

/*
 * Check to see if the second coord is within the precision ( meters )
 * of the first coord and return accordingly
 */
function checkWithinBound(coord_one, coord_two, precision) {
    var distance = 3959000 * Math.acos( 
        Math.cos( degree_to_radian( coord_two.lat ) ) * 
        Math.cos( degree_to_radian( coord_one.lat ) ) * 
        Math.cos( 
            degree_to_radian( coord_one.lng ) - degree_to_radian( coord_two.lng ) 
        ) +
        Math.sin( degree_to_radian( coord_two.lat ) ) * 
        Math.sin( degree_to_radian( coord_one.lat ) ) 
    );
    return distance <= precision;
}

/**
 * Get radian from given degree
 */
function degree_to_radian(degree) {
    return degree * (Math.PI / 180);
}

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

Why not copy Microsoft.Web.Infrastructure.dll file manually to the server BIN folder. This works for. My project is VS2010 Website.

This file can be located:

C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 4\Packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40

Just copy and paste it in the BIN folder.

You probably need to include this in the web.config if you don't have it already

<compilation debug="true" targetFramework="4.0">
  <assemblies>
    <add assembly="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </assemblies>
</compilation>

Reference: http://thedeveloperblog.com/

Oracle - How to create a readonly user

A user in an Oracle database only has the privileges you grant. So you can create a read-only user by simply not granting any other privileges.

When you create a user

CREATE USER ro_user
 IDENTIFIED BY ro_user
 DEFAULT TABLESPACE users
 TEMPORARY TABLESPACE temp;

the user doesn't even have permission to log in to the database. You can grant that

GRANT CREATE SESSION to ro_user

and then you can go about granting whatever read privileges you want. For example, if you want RO_USER to be able to query SCHEMA_NAME.TABLE_NAME, you would do something like

GRANT SELECT ON schema_name.table_name TO ro_user

Generally, you're better off creating a role, however, and granting the object privileges to the role so that you can then grant the role to different users. Something like

Create the role

CREATE ROLE ro_role;

Grant the role SELECT access on every table in a particular schema

BEGIN
  FOR x IN (SELECT * FROM dba_tables WHERE owner='SCHEMA_NAME')
  LOOP
    EXECUTE IMMEDIATE 'GRANT SELECT ON schema_name.' || x.table_name || 
                                  ' TO ro_role';
  END LOOP;
END;

And then grant the role to the user

GRANT ro_role TO ro_user;

List of special characters for SQL LIKE clause

Potential answer for SQL Server

Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.

Records .Where(r => r.Name.Contains("lkjwer--_~[]"))

-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'

So I haven't tested it yet but it looks like potentially the ESCAPE '~' keyword may allow for automatic escaping of a string for use within a like expression.

convert month from name to number

$nmonth = date("m", strtotime($month));

Get img src with PHP

There could be two easy solutions:

  1. HTML it self is an xml so you can use any XML parsing method if u load the tag as XML and get its attribute tottally dynamically even dom data attribute (like data-time or anything).....
  2. Use any html parser for php like http://mbe.ro/2009/06/21/php-html-to-array-working-one/ or php parse html to array Google this

How can I get the browser's scrollbar sizes?

Create an empty div and make sure it's present on all pages (i.e. by putting it in the header template).

Give it this styling:

#scrollbar-helper {
    // Hide it beyond the borders of the browser
    position: absolute;
    top: -100%;

    // Make sure the scrollbar is always visible
    overflow: scroll;
}

Then simply check for the size of #scrollbar-helper with Javascript:

var scrollbarWidth = document.getElementById('scrollbar-helper').offsetWidth;
var scrollbarHeight = document.getElementById('scrollbar-helper').offsetHeight;

No need to calculate anything, as this div will always have the width and height of the scrollbar.

The only downside is that there will be an empty div in your templates.. But on the other hand, your Javascript files will be cleaner, as this only takes 1 or 2 lines of code.

How to parse XML using shellscript?

This really is beyond the capabilities of shell script. Shell script and the standard Unix tools are okay at parsing line oriented files, but things change when you talk about XML. Even simple tags can present a problem:

<MYTAG>Data</MYTAG>

<MYTAG>
     Data
</MYTAG>

<MYTAG param="value">Data</MYTAG>

<MYTAG><ANOTHER_TAG>Data
</ANOTHER_TAG><MYTAG>

Imagine trying to write a shell script that can read the data enclosed in . The three very, very simply XML examples all show different ways this can be an issue. The first two examples are the exact same syntax in XML. The third simply has an attribute attached to it. The fourth contains the data in another tag. Simple sed, awk, and grep commands cannot catch all possibilities.

You need to use a full blown scripting language like Perl, Python, or Ruby. Each of these have modules that can parse XML data and make the underlying structure easier to access. I've use XML::Simple in Perl. It took me a few tries to understand it, but it did what I needed, and made my programming much easier.

Android - Set text to TextView

You should use ButterKnife Library http://jakewharton.github.io/butterknife/

And use it like

@InjectView(R.id.texto)
TextView err;

in onCreate method

ButterKnife.inject(this)
err.setText("Escriba su mensaje y luego seleccione el canal.");

Python Matplotlib Y-Axis ticks on Right Side of Plot

joaquin's answer works, but has the side effect of removing ticks from the left side of the axes. To fix this, follow up tick_right() with a call to set_ticks_position('both'). A revised example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')
plt.plot([2,3,4,5])
plt.show()

The result is a plot with ticks on both sides, but tick labels on the right.

enter image description here

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Creating a recursive method for Palindrome

String source = "liril";
StringBuffer sb = new StringBuffer(source);
String r = sb.reverse().toString();
if (source.equals(r)) {
    System.out.println("Palindrome ...");
} else {
    System.out.println("Not a palindrome...");
}

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

How can I get a user's media from Instagram without authenticating as a user?

You can use this API to retrieve public info of the instagram user:

https://api.lityapp.com/instagrams/thebrainscoop?limit=2 (edit: broken/malware link on Feb 2021)

If you don't set the limit parameter, the posts are limited at 12 by default

This api was made in SpringBoot with HtmlUnit as you can see in the code:

public JSONObject getPublicInstagramByUserName(String userName, Integer limit) {
    String html;
    WebClient webClient = new WebClient();

    try {
        webClient.getOptions().setCssEnabled(false);
        webClient.getOptions().setJavaScriptEnabled(false);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getCookieManager().setCookiesEnabled(true);

        Page page = webClient.getPage("https://www.instagram.com/" + userName);
        WebResponse response = page.getWebResponse();

        html = response.getContentAsString();
    } catch (Exception ex) {
        ex.printStackTrace();

        throw new RuntimeException("Ocorreu um erro no Instagram");
    }

    String prefix = "static/bundles/es6/ProfilePageContainer.js";
    String suffix = "\"";
    String script = html.substring(html.indexOf(prefix));

    script = script.substring(0, script.indexOf(suffix));

    try {
        Page page = webClient.getPage("https://www.instagram.com/" + script);
        WebResponse response = page.getWebResponse();

        script = response.getContentAsString();
    } catch (Exception ex) {
        ex.printStackTrace();

        throw new RuntimeException("Ocorreu um erro no Instagram");
    }

    prefix = "l.pagination},queryId:\"";

    String queryHash = script.substring(script.indexOf(prefix) + prefix.length());

    queryHash = queryHash.substring(0, queryHash.indexOf(suffix));
    prefix = "<script type=\"text/javascript\">window._sharedData = ";
    suffix = ";</script>";
    html = html.substring(html.indexOf(prefix) + prefix.length());
    html = html.substring(0, html.indexOf(suffix));

    JSONObject json = new JSONObject(html);
    JSONObject entryData = json.getJSONObject("entry_data");
    JSONObject profilePage = (JSONObject) entryData.getJSONArray("ProfilePage").get(0);
    JSONObject graphql = profilePage.getJSONObject("graphql");
    JSONObject user = graphql.getJSONObject("user");
    JSONObject response = new JSONObject();

    response.put("id", user.getString("id"));
    response.put("username", user.getString("username"));
    response.put("fullName", user.getString("full_name"));
    response.put("followedBy", user.getJSONObject("edge_followed_by").getLong("count"));
    response.put("following", user.getJSONObject("edge_follow").getLong("count"));
    response.put("isBusinessAccount", user.getBoolean("is_business_account"));
    response.put("photoUrl", user.getString("profile_pic_url"));
    response.put("photoUrlHD", user.getString("profile_pic_url_hd"));

    JSONObject edgeOwnerToTimelineMedia = user.getJSONObject("edge_owner_to_timeline_media");
    JSONArray posts = new JSONArray();

    try {
        loadPublicInstagramPosts(webClient, queryHash, user.getString("id"), posts, edgeOwnerToTimelineMedia, limit == null ? 12 : limit);
    } catch (Exception ex) {
        ex.printStackTrace();

        throw new RuntimeException("Você fez muitas chamadas, tente mais tarde");
    }

    response.put("posts", posts);

    return response;
}

private void loadPublicInstagramPosts(WebClient webClient, String queryHash, String userId, JSONArray posts, JSONObject edgeOwnerToTimelineMedia, Integer limit) throws IOException {
    JSONArray edges = edgeOwnerToTimelineMedia.getJSONArray("edges");

    for (Object elem : edges) {
        if (limit != null && posts.length() == limit) {
            return;
        }

        JSONObject node = ((JSONObject) elem).getJSONObject("node");

        if (node.getBoolean("is_video")) {
            continue;
        }

        JSONObject post = new JSONObject();

        post.put("id", node.getString("id"));
        post.put("shortcode", node.getString("shortcode"));

        JSONArray captionEdges = node.getJSONObject("edge_media_to_caption").getJSONArray("edges");

        if (captionEdges.length() > 0) {
            JSONObject captionNode = ((JSONObject) captionEdges.get(0)).getJSONObject("node");

            post.put("caption", captionNode.getString("text"));
        } else {
            post.put("caption", (Object) null);
        }

        post.put("photoUrl", node.getString("display_url"));

        JSONObject dimensions = node.getJSONObject("dimensions");

        post.put("photoWidth", dimensions.getLong("width"));
        post.put("photoHeight", dimensions.getLong("height"));

        JSONArray thumbnailResources = node.getJSONArray("thumbnail_resources");
        JSONArray thumbnails = new JSONArray();

        for (Object elem2 : thumbnailResources) {
            JSONObject obj = (JSONObject) elem2;
            JSONObject thumbnail = new JSONObject();

            thumbnail.put("photoUrl", obj.getString("src"));
            thumbnail.put("photoWidth", obj.getLong("config_width"));
            thumbnail.put("photoHeight", obj.getLong("config_height"));
            thumbnails.put(thumbnail);
        }

        post.put("thumbnails", thumbnails);
        posts.put(post);
    }

    JSONObject pageInfo = edgeOwnerToTimelineMedia.getJSONObject("page_info");

    if (!pageInfo.getBoolean("has_next_page")) {
        return;
    }

    String endCursor = pageInfo.getString("end_cursor");
    String variables = "{\"id\":\"" + userId + "\",\"first\":12,\"after\":\"" + endCursor + "\"}";

    String url = "https://www.instagram.com/graphql/query/?query_hash=" + queryHash + "&variables=" + URLEncoder.encode(variables, "UTF-8");
    Page page = webClient.getPage(url);
    WebResponse response = page.getWebResponse();
    String content = response.getContentAsString();
    JSONObject json = new JSONObject(content);

    loadPublicInstagramPosts(webClient, queryHash, userId, posts, json.getJSONObject("data").getJSONObject("user").getJSONObject("edge_owner_to_timeline_media"), limit);
}

It's an example of response:
{
  "id": "290482318",
  "username": "thebrainscoop",
  "fullName": "Official Fan Page",
  "followedBy": 1023,
  "following": 6,
  "isBusinessAccount": false,
  "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/447ffd0262082f373acf3d467435f130/5C709C77/t51.2885-19/11351770_612904665516559_678168252_a.jpg",
  "photoUrlHD": "https://scontent-gru2-1.cdninstagram.com/vp/447ffd0262082f373acf3d467435f130/5C709C77/t51.2885-19/11351770_612904665516559_678168252_a.jpg",
  "posts": [
    {
      "id": "1430331382090378714",
      "shortcode": "BPZjtBUly3a",
      "caption": "If I have any active followers anymore; hello! I'm Brianna, and I created this account when I was just 12 years old to show my love for The Brain Scoop. I'm now nearly finished high school, and just rediscovered it. I just wanted to see if anyone is still active on here, and also correct some of my past mistakes - being a child at the time, I didn't realise I had to credit artists for their work, so I'm going to try to correct that post haste. Also; the font in my bio is horrendous. Why'd I think that was a good idea? Anyway, this is a beautiful artwork of the long-tailed pangolin by @chelsealinaeve . Check her out!",
      "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/ab823331376ca46136457f4654bf2880/5CAD48E4/t51.2885-15/e35/16110915_400942200241213_3503127351280009216_n.jpg",
      "photoWidth": 640,
      "photoHeight": 457,
      "thumbnails": [
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/43b195566d0ef2ad5f4663ff76d62d23/5C76D756/t51.2885-15/e35/c91.0.457.457/s150x150/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 150,
          "photoHeight": 150
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/ae39043a7ac050c56d741d8b4355c185/5C93971C/t51.2885-15/e35/c91.0.457.457/s240x240/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 240,
          "photoHeight": 240
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/ae7a22d09e3ef98d0a6bbf31d621a3b7/5CACBBA6/t51.2885-15/e35/c91.0.457.457/s320x320/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 320,
          "photoHeight": 320
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/1439dc72b70e7c0c0a3afcc30970bb13/5C8E2923/t51.2885-15/e35/c91.0.457.457/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 480,
          "photoHeight": 480
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/1439dc72b70e7c0c0a3afcc30970bb13/5C8E2923/t51.2885-15/e35/c91.0.457.457/16110915_400942200241213_3503127351280009216_n.jpg",
          "photoWidth": 640,
          "photoHeight": 640
        }
      ]
    },
    {
      "id": "442527661838057235",
      "shortcode": "YkLJBXJD8T",
      "caption": null,
      "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/dc94b38da679826b9ac94ccd2bcc4928/5C7CDF93/t51.2885-15/e15/11327349_860747310663863_2105199307_n.jpg",
      "photoWidth": 612,
      "photoHeight": 612,
      "thumbnails": [
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/c1153c6513c44a6463d897e14b2d8f06/5CB13ADD/t51.2885-15/e15/s150x150/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 150,
          "photoHeight": 150
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/47e60ec8bca5a1382cd9ac562439d48c/5CAE6A82/t51.2885-15/e15/s240x240/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 240,
          "photoHeight": 240
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/da0ee5b666ab40e4adc1119e2edca014/5CADCB59/t51.2885-15/e15/s320x320/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 320,
          "photoHeight": 320
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/02ee23571322ea8d0992e81e72f80ef2/5C741048/t51.2885-15/e15/s480x480/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 480,
          "photoHeight": 480
        },
        {
          "photoUrl": "https://scontent-gru2-1.cdninstagram.com/vp/dc94b38da679826b9ac94ccd2bcc4928/5C7CDF93/t51.2885-15/e15/11327349_860747310663863_2105199307_n.jpg",
          "photoWidth": 640,
          "photoHeight": 640
        }
      ]
    }
  ]
}

How do I get the absolute directory of a file in bash?

Try our new Bash library product realpath-lib over at GitHub that we have given to the community for free and unencumbered use. It's clean, simple and well documented so it's great to learn from. You can do:

get_realpath <absolute|relative|symlink|local file path>

This function is the core of the library:

if [[ -f "$1" ]]
then
    # file *must* exist
    if cd "$(echo "${1%/*}")" &>/dev/null
    then
        # file *may* not be local
        # exception is ./file.ext
        # try 'cd .; cd -;' *works!*
        local tmppwd="$PWD"
        cd - &>/dev/null
    else
        # file *must* be local
        local tmppwd="$PWD"
    fi
else
    # file *cannot* exist
    return 1 # failure
fi

# reassemble realpath
echo "$tmppwd"/"${1##*/}"
return 0 # success

}

It's Bash 4+, does not require any dependencies and also provides get_dirname, get_filename, get_stemname and validate_path.