Programs & Examples On #Photography

Photography is the art, science, and practice of creating durable images by recording light or other electromagnetic radiation, either chemically by means of a light-sensitive material such as photographic film, or electronically by means of an image sensor.

How to get the EXIF data from a file using C#

As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:

I say "it’s the most flexible" because .NET does not try to interpret or coalesce the data in any way. For each EXIF you basically get an array of bytes. This may be good or bad depending on how much control you actually want.

Also, I should point out that the property list does not in fact directly correspond to the EXIF values. EXIF itself is stored in multiple tables with overlapping ID’s, but .NET puts everything in one list and redefines ID’s of some items. But as long as you don’t care about the precise EXIF ID’s, you should be fine with the .NET mapping.


Edit: It's possible to do it without loading the full image following this answer: https://stackoverflow.com/a/552642/2097240

how do you increase the height of an html textbox

I'm assuming from the way you worded the question that you want to change the size after the page has rendered?

In Javascript, you can manipulate DOM CSS properties, for example:

document.getElementById('textboxid').style.height="200px";
document.getElementById('textboxid').style.fontSize="14pt";

If you simply want to specify the height and font size, use CSS or style attributes, e.g.

//in your CSS file or <style> tag
#textboxid
{
    height:200px;
    font-size:14pt;
}

<!--in your HTML-->
<input id="textboxid" ...>

Or

<input style="height:200px;font-size:14pt;" .....>

Inserting data to table (mysqli insert)

Warning: Never ever refer to w3schools for learning purposes. They have so many mistakes in their tutorials.

According to the mysqli_query documentation, the first parameter must be a connection string:

$link = mysqli_connect("localhost","root","","web_table");

mysqli_query($link,"INSERT INTO web_formitem (`ID`, `formID`, `caption`, `key`, `sortorder`, `type`, `enabled`, `mandatory`, `data`)
VALUES (105, 7, 'Tip izdelka (6)', 'producttype_6', 42, 5, 1, 0, 0)") 
or die(mysqli_error($link));

Note: Add backticks ` for column names in your insert query as some of your column names are reserved words.

PDOException SQLSTATE[HY000] [2002] No such file or directory

Building on the answer from @dcarrith ...

Instead of editing the config files, I created an alias in the location that PHP is looking that connects to the real mysql.sock. (source)

Just run these two commands (no restart needed):

mkdir /var/mysql
ln -s /tmp/mysql.sock /var/mysql/mysql.sock

curl posting with header application/x-www-form-urlencoded

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>

Best way to format integer as string with leading zeros?

You have at least two options:

  • str.zfill: lambda n, cnt=2: str(n).zfill(cnt)
  • % formatting: lambda n, cnt=2: "%0*d" % (cnt, n)

If on Python >2.5, see a third option in clorz's answer.

Font is not available to the JVM with Jasper Reports

You can do it by installing fonts, that means everywhere you want to run that particular application. Simplest way is just add this bl line to your jrxml file:

 <property name="net.sf.jasperreports.awt.ignore.missing.font" value="true"/>

Hope it helps.

exception in thread 'main' java.lang.NoClassDefFoundError:

I found one another common reason. If you create the java file inside a package using IDE like eclipse, you will find the package name on the top of your java file like "package pkgName". If you try to run this file from command prompt, you will get the NoClassDefFoundError error. Remove the package name from the java file and use the commands in the command prompt. Wasted 3 hours for this. -- Abhi

How to allow users to check for the latest app version from inside the app?

Navigate to your play page:

https://play.google.com/store/apps/details?id=com.yourpackage

Using a standard HTTP GET. Now the following jQuery finds important info for you:

Current Version

$("[itemprop='softwareVersion']").text()

What's new

$(".recent-change").each(function() { all += $(this).text() + "\n"; })

Now that you can extract these information manually, simply make a method in your app that executes this for you.

public static String[] getAppVersionInfo(String playUrl) {
    HtmlCleaner cleaner = new HtmlCleaner();
    CleanerProperties props = cleaner.getProperties();
    props.setAllowHtmlInsideAttributes(true);
    props.setAllowMultiWordAttributes(true);
    props.setRecognizeUnicodeChars(true);
    props.setOmitComments(true);
    try {
        URL url = new URL(playUrl);
        URLConnection conn = url.openConnection();
        TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
        Object[] new_nodes = node.evaluateXPath("//*[@class='recent-change']");
        Object[] version_nodes = node.evaluateXPath("//*[@itemprop='softwareVersion']");

        String version = "", whatsNew = "";
        for (Object new_node : new_nodes) {
            TagNode info_node = (TagNode) new_node;
            whatsNew += info_node.getAllChildren().get(0).toString().trim()
                    + "\n";
        }
        if (version_nodes.length > 0) {
            TagNode ver = (TagNode) version_nodes[0];
            version = ver.getAllChildren().get(0).toString().trim();
        }
        return new String[]{version, whatsNew};
    } catch (IOException | XPatherException e) {
        e.printStackTrace();
        return null;
    }
}

Uses HtmlCleaner

C++ String Declaring

C++ supplies a string class that can be used like this:

#include <string>
#include <iostream>

int main() {
    std::string Something = "Some text";
    std::cout << Something << std::endl;
}

Check time difference in Javascript

This function returns a string with the difference from a datetime string and the current datetime.

function get_time_diff( datetime )
{
    var datetime = typeof datetime !== 'undefined' ? datetime : "2014-01-01 01:02:03.123456";

    var datetime = new Date( datetime ).getTime();
    var now = new Date().getTime();

    if( isNaN(datetime) )
    {
        return "";
    }

    console.log( datetime + " " + now);

    if (datetime < now) {
        var milisec_diff = now - datetime;
    }else{
        var milisec_diff = datetime - now;
    }

    var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));

    var date_diff = new Date( milisec_diff );

    return days + " Days "+ date_diff.getHours() + " Hours " + date_diff.getMinutes() + " Minutes " + date_diff.getSeconds() + " Seconds";
}

Tested in the Google Chrome console (press F12)

get_time_diff()
1388534523123 1375877555722
"146 Days 12 Hours 49 Minutes 27 Seconds"

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

How to check if an element does NOT have a specific class?

use the .not() method and check for an attribute:

$('p').not('[class]');

Check it here: http://jsfiddle.net/AWb79/

How to get the last day of the month?

To get the last date of the month we do something like this:

from datetime import date, timedelta
import calendar
last_day = date.today().replace(day=calendar.monthrange(date.today().year, date.today().month)[1])

Now to explain what we are doing here we will break it into two parts:

first is getting the number of days of the current month for which we use monthrange which Blair Conrad has already mentioned his solution:

calendar.monthrange(date.today().year, date.today().month)[1]

second is getting the last date itself which we do with the help of replace e.g

>>> date.today()
datetime.date(2017, 1, 3)
>>> date.today().replace(day=31)
datetime.date(2017, 1, 31)

and when we combine them as mentioned on the top we get a dynamic solution.

selenium get current url after loading a page

It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:

boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0

What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)

In the shell, what does " 2>&1 " mean?

Some tricks about redirection

Some syntax particularity about this may have important behaviours. There is some little samples about redirections, STDERR, STDOUT, and arguments ordering.

1 - Overwriting or appending?

Symbol > means redirection.

  • > means send to as a whole completed file, overwriting target if exist (see noclobber bash feature at #3 later).
  • >> means send in addition to would append to target if exist.

In any case, the file would be created if they not exist.

2 - The shell command line is order dependent!!

For testing this, we need a simple command which will send something on both outputs:

$ ls -ld /tmp /tnt
ls: cannot access /tnt: No such file or directory
drwxrwxrwt 118 root root 196608 Jan  7 11:49 /tmp

$ ls -ld /tmp /tnt >/dev/null
ls: cannot access /tnt: No such file or directory

$ ls -ld /tmp /tnt 2>/dev/null
drwxrwxrwt 118 root root 196608 Jan  7 11:49 /tmp

(Expecting you don't have a directory named /tnt, of course ;). Well, we have it!!

So, let's see:

$ ls -ld /tmp /tnt >/dev/null
ls: cannot access /tnt: No such file or directory

$ ls -ld /tmp /tnt >/dev/null 2>&1

$ ls -ld /tmp /tnt 2>&1 >/dev/null
ls: cannot access /tnt: No such file or directory

The last command line dumps STDERR to the console, and it seem not to be the expected behaviour... But...

If you want to make some post filtering about standard output, error output or both:

$ ls -ld /tmp /tnt | sed 's/^.*$/<-- & --->/'
ls: cannot access /tnt: No such file or directory
<-- drwxrwxrwt 118 root root 196608 Jan  7 12:02 /tmp --->

$ ls -ld /tmp /tnt 2>&1 | sed 's/^.*$/<-- & --->/'
<-- ls: cannot access /tnt: No such file or directory --->
<-- drwxrwxrwt 118 root root 196608 Jan  7 12:02 /tmp --->

$ ls -ld /tmp /tnt >/dev/null | sed 's/^.*$/<-- & --->/'
ls: cannot access /tnt: No such file or directory

$ ls -ld /tmp /tnt >/dev/null 2>&1 | sed 's/^.*$/<-- & --->/'

$ ls -ld /tmp /tnt 2>&1 >/dev/null | sed 's/^.*$/<-- & --->/'
<-- ls: cannot access /tnt: No such file or directory --->

Notice that the last command line in this paragraph is exactly same as in previous paragraph, where I wrote seem not to be the expected behaviour (so, this could even be an expected behaviour).

Well, there is a little tricks about redirections, for doing different operation on both outputs:

$ ( ls -ld /tmp /tnt | sed 's/^/O: /' >&9 ) 9>&2  2>&1  | sed 's/^/E: /'
O: drwxrwxrwt 118 root root 196608 Jan  7 12:13 /tmp
E: ls: cannot access /tnt: No such file or directory

Note: &9 descriptor would occur spontaneously because of ) 9>&2.

Addendum: nota! With the new version of (>4.0) there is a new feature and more sexy syntax for doing this kind of things:

$ ls -ld /tmp /tnt 2> >(sed 's/^/E: /') > >(sed 's/^/O: /')
O: drwxrwxrwt 17 root root 28672 Nov  5 23:00 /tmp
E: ls: cannot access /tnt: No such file or directory

And finally for such a cascading output formatting:

$ ((ls -ld /tmp /tnt |sed 's/^/O: /' >&9 ) 2>&1 |sed 's/^/E: /') 9>&1| cat -n
     1  O: drwxrwxrwt 118 root root 196608 Jan  7 12:29 /tmp
     2  E: ls: cannot access /tnt: No such file or directory

Addendum: nota! Same new syntax, in both ways:

$ cat -n <(ls -ld /tmp /tnt 2> >(sed 's/^/E: /') > >(sed 's/^/O: /'))
     1  O: drwxrwxrwt 17 root root 28672 Nov  5 23:00 /tmp
     2  E: ls: cannot access /tnt: No such file or directory

Where STDOUT go through a specific filter, STDERR to another and finally both outputs merged go through a third command filter.

3 - A word about noclobber option and >| syntax

That's about overwriting:

While set -o noclobber instruct bash to not overwrite any existing file, the >| syntax let you pass through this limitation:

$ testfile=$(mktemp /tmp/testNoClobberDate-XXXXXX)

$ date > $testfile ; cat $testfile
Mon Jan  7 13:18:15 CET 2013

$ date > $testfile ; cat $testfile
Mon Jan  7 13:18:19 CET 2013

$ date > $testfile ; cat $testfile
Mon Jan  7 13:18:21 CET 2013

The file is overwritten each time, well now:

$ set -o noclobber

$ date > $testfile ; cat $testfile
bash: /tmp/testNoClobberDate-WW1xi9: cannot overwrite existing file
Mon Jan  7 13:18:21 CET 2013

$ date > $testfile ; cat $testfile
bash: /tmp/testNoClobberDate-WW1xi9: cannot overwrite existing file
Mon Jan  7 13:18:21 CET 2013

Pass through with >|:

$ date >| $testfile ; cat $testfile
Mon Jan  7 13:18:58 CET 2013

$ date >| $testfile ; cat $testfile
Mon Jan  7 13:19:01 CET 2013

Unsetting this option and/or inquiring if already set.

$ set -o | grep noclobber
noclobber           on

$ set +o noclobber

$ set -o | grep noclobber
noclobber           off

$ date > $testfile ; cat $testfile
Mon Jan  7 13:24:27 CET 2013

$ rm $testfile

4 - Last trick and more...

For redirecting both output from a given command, we see that a right syntax could be:

$ ls -ld /tmp /tnt >/dev/null 2>&1

for this special case, there is a shortcut syntax: &> ... or >&

$ ls -ld /tmp /tnt &>/dev/null

$ ls -ld /tmp /tnt >&/dev/null

Nota: if 2>&1 exist, 1>&2 is a correct syntax too:

$ ls -ld /tmp /tnt 2>/dev/null 1>&2

4b- Now, I will let you think about:

$ ls -ld /tmp /tnt 2>&1 1>&2  | sed -e s/^/++/
++/bin/ls: cannot access /tnt: No such file or directory
++drwxrwxrwt 193 root root 196608 Feb  9 11:08 /tmp/

$ ls -ld /tmp /tnt 1>&2 2>&1  | sed -e s/^/++/
/bin/ls: cannot access /tnt: No such file or directory
drwxrwxrwt 193 root root 196608 Feb  9 11:08 /tmp/

4c- If you're interested in more information

You could read the fine manual by hitting:

man -Len -Pless\ +/^REDIRECTION bash

in a console ;-)

Show MySQL host via SQL Command

To get current host name :-

select @@hostname;
show variables where Variable_name like '%host%';

To get hosts for all incoming requests :-

select host from information_schema.processlist;

Based on your last comment,
I don't think you can resolve IP for the hostname using pure mysql function,
as it require a network lookup, which could be taking long time.

However, mysql document mention this :-

resolveip google.com.sg

docs :- http://dev.mysql.com/doc/refman/5.0/en/resolveip.html

Matplotlib make tick labels font size smaller

Another alternative

I have two plots side by side and would like to adjust tick labels separately.

The above solutions were close however they were not working out for me. I found my solution from this matplotlib page.

ax.xaxis.set_tick_params(labelsize=20)

This did the trick and was straight to the point. For my use case, it was the plot on the right that needed to be adjusted. For the plot on the left since I was creating new tick labels I was able to adjust the font in the same process as seting the labels.

ie

ax1.set_xticklabels(ax1_x, fontsize=15)
ax1.set_yticklabels(ax1_y, fontsize=15)

thus I used for the right plot,

ax2.xaxis.set_tick_params(labelsize=24)
ax2.yaxis.set_tick_params(labelsize=24)

A minor subtlety... I know... but I hope this helps someone :)

Bonus points if anyone knows how to adjust the font size of the order of magnitude label.

enter image description here

change array size

You can use Array.Resize() in .net 3.5 and higher. This method allocates a new array with the specified size, copies elements from the old array to the new one, and then replaces the old array with the new one. (So you will need the memory available for both arrays as this probably uses Array.Copy under the covers)

nvarchar(max) vs NText

I want to add that you can use the .WRITE clause for partial or full updates and high performance appends to varchar(max)/nvarchar(max) data types.

Here you can found full example of using .WRITE clause.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

You are single quoting your SQL statement which is making the variables text instead of variables.

$sql = "SELECT * 
    FROM $usertable 
    WHERE PartNumber = $partid";

Sublime 3 - Set Key map for function Goto Definition

If you want to see how to do a proper definition go into Sublime Text->Preferences->Key Bindings - Default and search for the command you want to override.

{ "keys": ["f12"], "command": "goto_definition" },
{ "keys": ["super+alt+down"], "command": "goto_definition" }

Those are two that show in my Default.

On Mac I copied the second to override.

in Sublime Text -> Preferences -> Key Bindings - User I added this

/* Beginning of File */

[
    {
        "keys": ["super+shift+i"], "command": "goto_definition" 
    }
]

/* End of File */

This binds it to the Command + Shift + 1 combination on mac.

How to hide Soft Keyboard when activity starts

You can set config on AndroidManifest.xml

Example:

<activity
    android:name="Activity"
    android:configChanges="orientation|keyboardHidden"
    android:theme="@*android:style/Theme.NoTitleBar"
    android:launchMode="singleTop"
    android:windowSoftInputMode="stateHidden"/>

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

How to change Toolbar home icon color

Here is what you are looking for. But this also changes the color of radioButton etc. So you might want to use a theme for it.

<item name="colorControlNormal">@color/colorControlNormal</item>

PHP Include for HTML?

First: what the others said. Forget the echo statement and just write your navbar.php as a regular HTML file.

Second: your include paths are probably messed up. To make sure you include files that are in the same directory as the current file, use __DIR__:

include __DIR__.'/navbar.php'; // PHP 5.3 and later
include dirname(__FILE__).'/navbar.php'; // PHP 5.2

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

allowing only alphabets in text box using java script

You can try:

 function onlyAlphabets(e, t) {
        return (e.charCode > 64 && e.charCode < 91) || (e.charCode > 96 && e.charCode < 123) || e.charCode == 32;   
    }

How to detect browser using angularjs?

So, you can declare more utilities for angular by create file with content (I follow RGraph Library)

(function(window, angular, undefined) {'use strict';
    var agl = angular || {};
    var ua  = navigator.userAgent;

    agl.ISFF     = ua.indexOf('Firefox') != -1;
    agl.ISOPERA  = ua.indexOf('Opera') != -1;
    agl.ISCHROME = ua.indexOf('Chrome') != -1;
    agl.ISSAFARI = ua.indexOf('Safari') != -1 && !agl.ISCHROME;
    agl.ISWEBKIT = ua.indexOf('WebKit') != -1;

    agl.ISIE   = ua.indexOf('Trident') > 0 || navigator.userAgent.indexOf('MSIE') > 0;
    agl.ISIE6  = ua.indexOf('MSIE 6') > 0;
    agl.ISIE7  = ua.indexOf('MSIE 7') > 0;
    agl.ISIE8  = ua.indexOf('MSIE 8') > 0;
    agl.ISIE9  = ua.indexOf('MSIE 9') > 0;
    agl.ISIE10 = ua.indexOf('MSIE 10') > 0;
    agl.ISOLD  = agl.ISIE6 || agl.ISIE7 || agl.ISIE8; // MUST be here

    agl.ISIE11UP = ua.indexOf('MSIE') == -1 && ua.indexOf('Trident') > 0;
    agl.ISIE10UP = agl.ISIE10 || agl.ISIE11UP;
    agl.ISIE9UP  = agl.ISIE9 || agl.ISIE10UP;

})(window, window.angular);

after that, in your function use can use it like

function SampleController($scope){
    $scope.click = function () {
        if(angular.ISCHROME) {
        alert("is chrome");
    }
}

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

CSS disable text selection

you can disable all selection

.disable-all{-webkit-touch-callout: none;  -webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;}

now you can enable input and text-area enable

input, textarea{
-webkit-touch-callout:default;
-webkit-user-select:text;
-khtml-user-select: text;
-moz-user-select:text;
-ms-user-select:text;
user-select:text;}

How many bytes does one Unicode character take?

From Wiki:

UTF-8, an 8-bit variable-width encoding which maximizes compatibility with ASCII;

UTF-16, a 16-bit, variable-width encoding;

UTF-32, a 32-bit, fixed-width encoding.

These are the three most popular different encoding.

  • In UTF-8 each character is encoded into 1 to 4 bytes ( the dominant encoding )
  • In UTF16 each character is encoded into 1 to two 16-bit words and
  • in UTF-32 every character is encoded as a single 32-bit word.

Move to next item using Java 8 foreach loop in stream

Another solution: go through a filter with your inverted conditions : Example :

if(subscribtion.isOnce() && subscribtion.isCalled()){
                continue;
}

can be replaced with

.filter(s -> !(s.isOnce() && s.isCalled()))

The most straightforward approach seem to be using "return;" though.

Read String line by line

There is also Scanner. You can use it just like the BufferedReader:

Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  // process the line
}
scanner.close();

I think that this is a bit cleaner approach that both of the suggested ones.

How to set gradle home while importing existing project in Android studio

For Ubuntu default version is /usr/lib/gradle/default. In case of update, you don't need to reassign link in idea/studio.

How do I empty an input value with jQuery?

Usual way to empty textbox using jquery is:

$('#txtInput').val('');

If above code is not working than please check that you are able to get the input element.

console.log($('#txtInput')); // should return element in the console.

If still facing the same problem, please post your code.

How to create a directory if it doesn't exist using Node.js?

The mkdir method has the ability to recursively create any directories in a path that don't exist, and ignore the ones that do.

From the Node v10/11 docs:

// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
    if (err) throw err;
});

NOTE: You'll need to import the built-in fs module first.

Now here's a little more robust example that leverages native ES Modules (with flag enabled and .mjs extension), handles non-root paths, and accounts for full pathnames:

import fs from 'fs';
import path from 'path';

createDirectories(pathname) {
   const __dirname = path.resolve();
   pathname = pathname.replace(/^\.*\/|\/?[^\/]+\.[a-z]+|\/$/g, ''); // Remove leading directory markers, and remove ending /file-name.extension
   fs.mkdir(path.resolve(__dirname, pathname), { recursive: true }, e => {
       if (e) {
           console.error(e);
       } else {
           console.log('Success');
       }
    });
}

You can use it like createDirectories('/components/widget/widget.js');.

And of course, you'd probably want to get more fancy by using promises with async/await to leverage file creation in a more readable synchronous-looking way when the directories are created; but, that's beyond the question's scope.

Remove Null Value from String array in java

Using Google's guava library

String[] firstArray = {"test1","","test2","test4","",null};

Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
    @Override
    public boolean apply(String arg0) {
        if(arg0==null) //avoid null strings 
            return false;
        if(arg0.length()==0) //avoid empty strings 
            return false;
        return true; // else true
    }
});

How to convert String to Date value in SAS?

As stated above, the simple answer is:

date = input(monyy,date9.);

with the addition of:

put date=yymmdd.;

The reason why this works, and what you did doesn't, is because of a common misunderstanding in SAS. DATE9. is an INFORMAT. In an INPUT statement, it provides the SAS interpreter with a set of translation commands it can send to the compiler to turn your text into the right numbers, which will then look like a date once the right FORMAT is applied. FORMATs are just visible representations of numbers (or characters). So by using YYMMDD., you confused the INPUT function by handing it a FORMAT instead of an INFORMAT, and probably got a helpful error that said:

Invalid argument to INPUT function at line... etc...

Which told you absolutely nothing about what to do next.

In summary, to represent your character date as a YYMMDD. In SAS you need to:

  1. change the INFORMAT - date = input(monyy,date9.);
  2. apply the FORMAT - put date=YYMMDD10.;

jQuery UI Color Picker

Had the same problem (is not a method) with jQuery when working on autocomplete. It appeared the code was executed before the autocomplete.js was loaded. So make sure the ui.colorpicker.js is loaded before calling colorpicker.

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

How to select an option from drop down using Selenium WebDriver C#?

If you are looking for just any selection from the drop-down box, I also find "select by index" method very useful.

if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
{
    new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
    WaitForAjax();
    Thread.Sleep(3000);
}
else
{
     Console.WriteLine("Your comment here);
}

SyntaxError: missing ; before statement

I got this error, hope this will help someone:

const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';

The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.

Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

How to set focus on input field?

I don't think $timeout is a good way to focus the element on creation. Here is a method using built-in angular functionality, dug out from the murky depths of the angular docs. Notice how the "link" attribute can be split into "pre" and "post", for pre-link and post-link functions.

Working Example: http://plnkr.co/edit/Fj59GB

// this is the directive you add to any element you want to highlight after creation
Guest.directive('autoFocus', function() {
    return {
        link: {
            pre: function preLink(scope, element, attr) {
                console.debug('prelink called');
                // this fails since the element hasn't rendered
                //element[0].focus();
            },
            post: function postLink(scope, element, attr) {
                console.debug('postlink called');
                // this succeeds since the element has been rendered
                element[0].focus();
            }
        }
    }
});
<input value="hello" />
<!-- this input automatically gets focus on creation -->
<input value="world" auto-focus />

Full AngularJS Directive Docs: https://docs.angularjs.org/api/ng/service/$compile

PostgreSQL column 'foo' does not exist

It could be quotes themselves that are the entire problem. I had a similar problem and it was due to quotes around the column name in the CREATE TABLE statement. Note there were no whitespace issues, just quotes causing problems.

The column looked like it was called anID but was really called "anID". The quotes don't appear in typical queries so it was hard to detect (for this postgres rookie). This is on postgres 9.4.1

Some more detail:

Doing postgres=# SELECT * FROM test; gave:

  anID | value 
 ------+-------
     1 | hello
     2 | baz
     3 | foo (3 rows)

but trying to select just the first column SELECT anID FROM test; resulted in an error:

ERROR:  column "anid" does not exist 
LINE 1: SELECT anID FROM test;
                ^

Just looking at the column names didn't help: postgres=# \d test;

          Table "public.test"
 Column |       Type        | Modifiers 
--------+-------------------+-----------
 anID   | integer           | not null
 value  | character varying | 
Indexes:
    "PK on ID" PRIMARY KEY, btree ("anID")

but in pgAdmin if you click on the column name and look in the SQL pane it populated with:

ALTER TABLE test ADD COLUMN "anID" integer;
ALTER TABLE test ALTER COLUMN "anID" SET NOT NULL;

and lo and behold there are the quoutes around the column name. So then ultimately postgres=# select "anID" FROM test; works fine:

 anID 
------
    1
    2
    3
(3 rows)

Same moral, don't use quotes.

How to use switch statement inside a React component?

You can't have a switch in render. The psuedo-switch approach of placing an object-literal that accesses one element isn't ideal because it causes all views to process and that can result in dependency errors of props that don't exist in that state.

Here's a nice clean way to do it that doesn't require each view to render in advance:

render () {
  const viewState = this.getViewState();

  return (
    <div>
      {viewState === ViewState.NO_RESULTS && this.renderNoResults()}
      {viewState === ViewState.LIST_RESULTS && this.renderResults()}
      {viewState === ViewState.SUCCESS_DONE && this.renderCompleted()}
    </div>
  )

If your conditions for which view state are based on more than a simple property – like multiple conditions per line, then an enum and a getViewState function to encapsulate the conditions is a nice way to separate this conditional logic and cleanup your render.

CSS vertical alignment text inside li

Surprisingly (or not), the vertical-align tool actually works best for this job. Best of all, no Javascript is required.

In the following example, I am positioning the outer class in the middle of the body, and the inner class in the middle of the outer class.

Preview: http://jsfiddle.net/tLkSV/513/

HTML:

<div id="container">
    <span></span><div class="outer">
        <span></span><div class="inner">

        </div>
    </div>
</div>

CSS:

html, body {
    height: 100%;
    margin: 0;
    padding: 0; }
#container {
    text-align: center;
    height: 100%; }
span { 
    height: 100%;
    vertical-align: middle;
    display: inline-block; }
.outer {
    width: 100px;
    height: 200px;
    padding: 0;
    border: 1px solid #000;
    vertical-align: middle;
    display: inline-block; }
.inner {
    background: red;
    width: 30px;
    height: 20px;    
    vertical-align: middle;
    display: inline-block; }

Vertical align works by aligning the centers of elements that are next to each other. Applying vertical-align to a single element does absolutely nothing. If you add a second element that has no width but is the height of the container, your single element will move to vertically center with this no-width element, thus vertically centering it. The only requirements are that you set both elements to inline (or inline-block), and set their vertical-align attribute to vertical-align: middle.

Note: You may notice in my code below that my <span> tag and <div> tag are touching. Because they are both inline elements, a space will actually add a space between the no-width element and your div, so be sure to leave it out.

Disable the postback on an <ASP:LinkButton>

I think you should investigate using a HyperLink control. It's a server-side control (so you can manipulate visibility and such from code), but it omits a regular ol' anchor tag and doesn't cause a postback.

Class type check in TypeScript

4.19.4 The instanceof operator

The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type, and the right operand to be of type Any or a subtype of the 'Function' interface type. The result is always of the Boolean primitive type.

So you could use

mySprite instanceof Sprite;

Note that this operator is also in ActionScript but it shouldn't be used there anymore:

The is operator, which is new for ActionScript 3.0, allows you to test whether a variable or expression is a member of a given data type. In previous versions of ActionScript, the instanceof operator provided this functionality, but in ActionScript 3.0 the instanceof operator should not be used to test for data type membership. The is operator should be used instead of the instanceof operator for manual type checking, because the expression x instanceof y merely checks the prototype chain of x for the existence of y (and in ActionScript 3.0, the prototype chain does not provide a complete picture of the inheritance hierarchy).

TypeScript's instanceof shares the same problems. As it is a language which is still in its development I recommend you to state a proposal of such facility.

See also:

How do I use Docker environment variable in ENTRYPOINT array?

I tried to resolve with the suggested answer and still ran into some issues...

This was a solution to my problem:

ARG APP_EXE="AppName.exe"
ENV _EXE=${APP_EXE}

# Build a shell script because the ENTRYPOINT command doesn't like using ENV
RUN echo "#!/bin/bash \n mono ${_EXE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh

# Run the generated shell script.
ENTRYPOINT ["./entrypoint.sh"]

Specifically targeting your problem:

RUN echo "#!/bin/bash \n ./greeting --message ${ADDRESSEE}" > ./entrypoint.sh
RUN chmod +x ./entrypoint.sh
ENTRYPOINT ["./entrypoint.sh"]

semaphore implementation

Your Fundamentals are wrong, the program won't work, so go through the basics and rewrite the program.

Some of the corrections you must make are:

1) You must make a variable of semaphore type

sem_t semvar;

2) The functions sem_wait(), sem_post() require the semaphore variable but you are passing the semaphore id, which makes no sense.

sem_wait(&semvar);
   //your critical section code
sem_post(&semvar);

3) You are passing the semaphore to sem_wait() and sem_post() without initializing it. You must initialize it to 1 (in your case) before using it, or you will have a deadlock.

ret = semctl( semid, 1, SETVAL, sem);
if (ret == 1)
     perror("Semaphore failed to initialize");

Study the semaphore API's from the man page and go through this example.

How to Delete a directory from Hadoop cluster which is having comma(,) in its name?

In hadoop1.0:

hadoop fs -rmr /PATH/ON/HDFS

In hadoop2.0:

hdfs dfs -rm -R /PATH/ON/HDFS

Use \ to escape , in path

A div with auto resize when changing window width\height

Code Snippet:

div{height: calc(100vh - 10vmax)}

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

How to make a div have a fixed size?

Thats the natural behavior of the buttons. You could try putting a max-width/max-height on the parent container, but I'm not sure if that would do it.

max-width:something px;
max-height:something px;

The other option would be to use the devlopr tools and see if you can remove the natural padding.

padding: 0;

How to install mongoDB on windows?

Mongo Installation Process in Windows

Are you ready for the installation … and use … Technically, it’s not an installation it’s just Downloading…

I. Download the zip file http://www.mongodb.org/downloads

II. Extract it and copy the files into your desired location.

III. Start the DB engine.

IV. Test the installation and use it.

That's it! So simple, right? Ok let’s start


1. Download the zip file

  1. Go to http://www.mongodb.org/downloads

  2. You will see a screen like this: The mongo download page I am using a windows 7 32 bit machine - that’s why I downloaded the package marked in red.

  3. Click download (It only takes a few seconds).
    Wow... I got that downloaded. It was a zipped file called mongodb-win32-i386-2.4.4.zip (The name of the folder will change according to the version you download, here I got version 2.4.4).

OK all set.


2. Extract

  1. Extract the zip
  2. Copy the files into a desired location in your machine.
    • I am going to copy the extracted files to my D drive, since I don’t have many files there.
    • Alright then where are you planning to paste the mongo files? In C: or in your Desktop itself?
    • Ok, no matter where you paste... In the snap shot below, you can see that I have navigated to the bin folder inside the Mongo folder. I count fifteen files inside bin. What about you?

The path to the bin folder

Finished! That’s all

What we have to do next?


3. Start the DB engine

Let’s go and start using our mongo db...

  1. Open up a command prompt, then navigate to bin in the mongo folder Navigating to mongo's bin folder

  2. Type mongo.exe (which is the command used to start mongo Db Power shell). Then see the below response.. Executing mongo.exe That was an awesome exception J LOL … What is that?

    Couldn’t connect to server.

    Why did the exception happen? I have no idea... Did I create a server in between?

    No.

    Right, then how come it connected to a server in between? Silly Machine …Jz.

    I got it! Like all other DBs - we have to start the DB engine before we use it.

    So, how can we start it?

  3. We have to start the mongo db by using the command mongod. Execute this from the bin folder of mongo.

    Let’s see what had happened.

    error message

    Again a wonderfully formatted exception J we got right? Did you notice what I have highlighted on top? Yeah it is the mongod command. The second one is the exception asking us to create a folder called data. And, inside the data folder, a folder called db.

    So we have to create these data\db folders.

    The next question is where to create these folders?

  4. We have to create the data\db folders in the C drive of our BOX in which we are installing mongo. Let’s go and create the folder structure in C drive.

    A question arises here: "Is it mandatory to create the data\db directories inside C?" Nooo, not really. Mongo looks in C by default for this folder, but you can create them wherever you want. However, if it's not in C, you have to tell mongo where it is.

    In other words, if you don't want the mongo databases to be on C:\, you have to set the db path for mongo.exe.

    Optional

    • Ok, I will create those folders in some other location besides C for better understanding of this option. I will create then in the D drive root, with the help of cmd.

      Why? Because it’s an opportunity for us to remember the old dos commands...

      md data

    • The next step is to set the Db path to mongo.exe.

      Navigate back to bin, and enter the command, mongod.exe --dbpath d:\data.

      I got the response below:

      --dbpath

      I Hope everything went well... Because I didn’t see any ERROR *** in the console J.

    Next, we can go and start the db using the command start mongo.exe

    start mongo.exe

    I didn't see any error or warning messages. But, we have to supply a command to make sure mongo is up and running, i.e. mongod will get a response:

    mongodb response

Hope everything went well.


4. Test the Mongo DB installation

Now we have to see our DB right? Yea very much, Otherwise how will we know it’s running?

For testing purpose MONGO has got a DB called test by default. Lets go query that.

But how without any management studios? Unlike SQL, we have to depend on the command prompt. Yes exactly the same command prompt… our good old command prompt… Heiiiii.. Don’t get afraid yes it’s our old command prompt only. Ok let’s go and see how we are going to use it…

Ohhh Nooo… don’t close the above Command prompt, leave it as it is…

  1. Open a new cmd window.

  2. Navigate to Bin as usual we do…

    I am sure you people may be remembering the old C programming which we have done on our college day’s right?

  3. In the command prompt, execute the command mongo or mongo.exe again and see what happens.

    You will get a screen as shown below:

    startup warning

  4. I mentioned before that Mongo has got a test db by default called test, try inserting a record into it.

    The next question here is "How will we insert?" Does mongo have SQL commands? No, mongo has got only commands to help with.

    The basic command to insert is
    db.test.save( { KodothTestField: ‘My name is Kodoth’ } )

    Where test is the DB and .save is the insert command. KodothTestField is the column or field name, and My name is Kodoth is the value.

  5. Before talking more let’s check whether it’s stored or not by performing another command: db.test.find()

    Mongo command to search for a document, similar to SELECT in SQL.

    Our Data got successfully inserted … Hurrayyyyyy..

    I know that you are thinking about the number which is displayed with every record right called ObjectId. It’s like a unique id field in SQL that auto-increments and all. Have a closer look you can see that the Object Id ends with 92, so it’s different for each and every record.

    At last we are successful in installing and verifying the MONGO right. Let’s have a party... So do you agree now MONGO is as Sweet as MANGO?

Also we have 3rd party tools to explore the MONGO. One is called MONGO VUE. Using this tool we can perform operations against the mongo DB like we use Management studio for SQL Server.

Can you just imagine an SQL server or Oracle Db with entirely different rows in same table? Is it possible in our relational DB table? This is how mongo works. I will show you how we can do that…


First I will show you how the data will look in a relational DB.

For example consider an Employee table and a Student table in relational way. The schemas would be entirely different right? Yes exactly…

results view

Let us now see how it will look in Mongo DB. The above two tables are combined into single Collection in Mongo…

MongoVUE

This is how Collections are stored in Mongo. I think now you can feel the difference really right? Every thing came under a single umbrella. This is not the right way but I just wanted to show you all how this happens that’s why I combined 2 entirely different tables in to one single Collection.

If you want to try out you can use below test scripts

*********************** 
TEST INSERT SCRIPT

*********EMPLOYEE****** 
db.test.save( { EmployeId: "1", EmployeFirstName: "Kodoth", EmployeLastName:"KodothLast", EmployeAge:"14" } )  
db.test.save( { EmployeId: "2", EmployeFirstName: "Kodoth 2", EmployeLastName:"Kodoth Last2", EmployeAge:"14" } )  
db.test.save( { EmployeId: "3", EmployeFirstName: "Kodoth 3", EmployeLastName:"Kodoth Last3", EmployeAge:"14" } ) 

******STUDENT****** 
db.test.save( { StudentId: "1", StudentName: "StudentName", StudentMark:"25" } )  
db.test.save( { StudentId: "2", StudentName: "StudentName 2", StudentMark:"26" } )  
db.test.save( {StudentId: "3", StudentName: "StudentName 3", StudentMark:"27"} )
************************

Thanks

How to close a web page on a button click, a hyperlink or a link button click?

To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

Explanation of "ClassCastException" in Java

Exception is not a subclass of RuntimeException -> ClassCastException

    final Object  exception = new Exception();
    final Exception data = (RuntimeException)exception ;
    System.out.println(data);

Get full query string in C# ASP.NET

Just use Request.QueryString.ToString() to get full query string, like this:

string URL = "http://www.example.com/rendernews.php?"+Request.Querystring.ToString();

What is the Ruby <=> (spaceship) operator?

I will explain with simple example

  1. [1,3,2] <=> [2,2,2]

    Ruby will start comparing each element of both array from left hand side. 1 for left array is smaller than 2 of right array. Hence left array is smaller than right array. Output will be -1.

  2. [2,3,2] <=> [2,2,2]

    As above it will first compare first element which are equal then it will compare second element, in this case second element of left array is greater hence output is 1.

Modifying the "Path to executable" of a windows service

You can't directly edit your path to execute of a service. For that you can use sc command,

SC CONFIG ServiceName binPath= "Path of your file"

Eg:

sc config MongoDB binPath="I:\Programming\MongoDB\MongoDB\bin\mongod.exe --config I:\Programming\MongoDB\MongoDB\bin\mongod.cfg --service"

Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

Simple dynamic breadcrumb

A better one using explode() function is as follows...

Don't forget to replace your URL variable in the hyperlink href.

<?php 
    if($url != ''){
        $b = '';
        $links = explode('/',rtrim($url,'/'));
        foreach($links as $l){
            $b .= $l;
            if($url == $b){
                echo $l;
            }else{
                echo "<a href='URL?url=".$b."'>".$l."/</a>";
            }
            $b .= '/';
         }
     }
?>

Android ImageView Fixing Image Size

You can also try this, suppose if you want to make a back image button and you have "500x500 png" and want it to fit in small button size.

Use dp to fix ImageView's size.

add this line of code to your Imageview.

android:scaleType="fitXY"

EXAMPLE:

<ImageView
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/imageView2"
        android:src="@drawable/Backicon"
        android:scaleType="fitXY"
        />

Cannot catch toolbar home button click event

I have handled back and Home button in Navigation Drawer like

public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private ActionBarDrawerToggle drawerToggle;
    private DrawerLayout drawerLayout;
    NavigationView navigationView;
    private Context context;

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

        setContentView(R.layout.activity_home);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        resetActionBar();

        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(this);

        //showing first fragment on Start
        getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).replace(R.id.content_fragment, new FirstFragment()).commit();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //listener for home
        if(id==android.R.id.home)
        {  
            if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                onBackPressed();
            else
                drawerLayout.openDrawer(navigationView);
            return  true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
       if (drawerLayout.isDrawerOpen(GravityCompat.START)) 
            drawerLayout.closeDrawer(GravityCompat.START);
       else 
            super.onBackPressed();
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Begin the transaction

        Fragment fragment = null;
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (id == R.id.nav_companies_list) {
            fragment = new FirstFragment();
            // Handle the action
        } 


        // Begin the transaction
        if(fragment!=null){

            if(item.isChecked()){
                if(getSupportFragmentManager().getBackStackEntryCount()==0){
                    drawer.closeDrawers();
            }else{
                    removeAllFragments();
                    getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
                    drawer.closeDrawer(GravityCompat.START);
                }

            }else{
                removeAllFragments();
                getSupportFragmentManager().beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE).replace(R.id.WikiCompany, fragment).commit();
                drawer.closeDrawer(GravityCompat.START);
            }
        }

        return true;
    }

    public void removeAllFragments(){
        getSupportFragmentManager().popBackStackImmediate(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }

    public void replaceFragment(final Fragment fragment) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
                .replace(R.id.WikiCompany, fragment).addToBackStack("")
                .commit();
    }


    public void updateDrawerIcon() {
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.i("", "BackStackCount: " + getSupportFragmentManager().getBackStackEntryCount());
                    if (getSupportFragmentManager().getBackStackEntryCount() > 0)
                        drawerToggle.setDrawerIndicatorEnabled(false);
                    else
                        drawerToggle.setDrawerIndicatorEnabled(true);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }, 50);
    }

    public void resetActionBar()
    {
        //display home
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    public void setActionBarTitle(String title) {
        getSupportActionBar().setTitle(title);
    }
}

and In each onViewCreated I call

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ((HomeActivity)getActivity()).updateDrawerIcon();
    ((HomeActivity) getActivity()).setActionBarTitle("List");
}

Python: json.loads returns items prefixing with 'u'

The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output.

For example, try this:

print mail_accounts[0]["i"]

You won't see a u.

How to set up gradle and android studio to do release build?

No need to update gradle for making release application in Android studio.If you were eclipse user then it will be so easy for you. If you are new then follow the steps

1: Go to the "Build" at the toolbar section. 2: Choose "Generate Signed APK..." option. enter image description here

3:fill opened form and go next 4 :if you already have .keystore or .jks then choose that file enter your password and alias name and respective password. 5: Or don't have .keystore or .jks file then click on Create new... button as shown on pic 1 then fill the form.enter image description here

Above process was to make build manually. If You want android studio to automatically Signing Your App

In Android Studio, you can configure your project to sign your release APK automatically during the build process:

On the project browser, right click on your app and select Open Module Settings. On the Project Structure window, select your app's module under Modules. Click on the Signing tab. Select your keystore file, enter a name for this signing configuration (as you may create more than one), and enter the required information. enter image description here Figure 4. Create a signing configuration in Android Studio.

Click on the Build Types tab. Select the release build. Under Signing Config, select the signing configuration you just created. enter image description here Figure 5. Select a signing configuration in Android Studio.

4:Most Important thing that make debuggable=false at gradle.

    buildTypes {
        release {
           minifyEnabled false
          proguardFiles getDefaultProguardFile('proguard-  android.txt'), 'proguard-rules.txt'
        debuggable false
        jniDebuggable false
        renderscriptDebuggable false
        zipAlignEnabled true
       }
     }

visit for more in info developer.android.com

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

Python Pandas: Get index of rows which column matches certain value

First you may check query when the target column is type bool (PS: about how to use it please check link )

df.query('BoolCol')
Out[123]: 
    BoolCol
10     True
40     True
50     True

After we filter the original df by the Boolean column we can pick the index .

df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')

Also pandas have nonzero, we just select the position of True row and using it slice the DataFrame or index

df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')

jQuery get the rendered height of an element?

Try one of:

var h = document.getElementById('someDiv').clientHeight;
var h = document.getElementById('someDiv').offsetHeight;
var h = document.getElementById('someDiv').scrollHeight;

clientHeight includes the height and vertical padding.

offsetHeight includes the height, vertical padding, and vertical borders.

scrollHeight includes the height of the contained document (would be greater than just height in case of scrolling), vertical padding, and vertical borders.

What is managed or unmanaged code in programming?

From Pro C# 5 and the .NET 4.5 Framework:

Managed vs. Unmanaged Code: Perhaps the most important point to understand about the C# language is that it can produce code that can execute only within the .NET runtime (you could never use C# to build a native COM server or an unmanaged C/C++ application). Officially speaking, the term used to describe the code targeting the .NET runtime is managed code. The binary unit that contains the managed code is termed an assembly (more details on assemblies in just a bit). Conversely, code that cannot be directly hosted by the .NET runtime is termed unmanaged code.

In Java, what is the best way to determine the size of an object?

My answer is based on the code supplied by Nick. That code measures total amount of bytes which are occupied by the serialized object. So this actually measures serialization stuff + plain object memory footprint (just serialize for example int and you will see that total amount of serialized bytes is not 4). So if you want to get raw byte number used exactly for your object - you need to modify that code a bit. Like so:

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectSizeCalculator {
    private Object getFirstObjectReference(Object o) {
        String objectType = o.getClass().getTypeName();

        if (objectType.substring(objectType.length()-2).equals("[]")) {
            try {
                if (objectType.equals("java.lang.Object[]"))
                    return ((Object[])o)[0];
                else if (objectType.equals("int[]"))
                    return ((int[])o)[0];
                else
                    throw new RuntimeException("Not Implemented !");
            } catch (IndexOutOfBoundsException e) {
                return null;
            }
        }

        return o;
    } 

    public int getObjectSizeInBytes(Object o) {
        final String STRING_JAVA_TYPE_NAME = "java.lang.String";

        if (o == null)
            return 0;

        String objectType = o.getClass().getTypeName();
        boolean isArray = objectType.substring(objectType.length()-2).equals("[]");

        Object objRef = getFirstObjectReference(o);
        if (objRef != null && !(objRef instanceof Serializable))
            throw new RuntimeException("Object must be serializable for measuring it's memory footprint using this method !");

        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(o);
            oos.close();
            byte[] bytes = baos.toByteArray();

            for (int i = bytes.length - 1, j = 0; i != 0; i--, j++) {
                if (objectType != STRING_JAVA_TYPE_NAME) {
                    if (bytes[i] == 112)
                        if (isArray)
                            return j - 4;
                        else
                            return j;
                } else {
                    if (bytes[i] == 0)
                        return j - 1;
                }
            }
        } catch (Exception e) {
            return -1;
        }

        return -1;
    }    

}

I've tested this solution with primitive types, String, and on some trivial classes. There may be not covered cases also.


UPDATE: Example modified to support memory footprint calculation of array objects.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

mysql -> insert into tbl (select from another table) and some default values

If you you want to copy a sub-set of the source table you can do:

INSERT INTO def (field_1, field_2, field3)

SELECT other_field_1, other_field_2, other_field_3 from `abc`

or to copy ALL fields from the source table to destination table you can do more simply:

INSERT INTO def 
SELECT * from `abc`

Get column from a two dimensional array

var data = [
    ["a1", "a2", "a3"],
    ["b1", "b2", "b3"],
    ["c1", "c2", "c3"]
];

var col0 = data.map(d => d[0]); // [ 'a1', 'b1', 'c1' ]

var col1 = data.map(d => d[1]); // [ 'a2', 'b2', 'c2' ]

INSTALL_FAILED_NO_MATCHING_ABIS when install apk

Basically if you tried Everything above and still you have the same error "Because i am facing this issue before too" then check which .jar or .aar or module you added may be the one library using ndk , and that one is not supporting 8.0 (Oreo)+ , likewise i am using Microsoft SignalR socket Library adding its .jar files and latterly i found out app not installing in Oreo then afterwards i remove that library because currently there is no solution on its git page and i go for another one.

So please check the library you are using and search about it if you eagerly needed that one.

How do I check if a string contains a specific word?

I'm a bit impressed that none of the answers here that used strpos, strstr and similar functions mentioned Multibyte String Functions yet (2015-05-08).

Basically, if you're having trouble finding words with characters specific to some languages, such as German, French, Portuguese, Spanish, etc. (e.g.: ä, é, ô, ç, º, ñ), you may want to precede the functions with mb_. Therefore, the accepted answer would use mb_strpos or mb_stripos (for case-insensitive matching) instead:

if (mb_strpos($a,'are') !== false) {
    echo 'true';
}

If you cannot guarantee that all your data is 100% in UTF-8, you may want to use the mb_ functions.

A good article to understand why is The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky.

How to add a single item to a Pandas Series

TLDR: do not append items to a series one by one, better extend with an ordered collection

I think the question in its current form is a bit tricky. And the accepted answer does answer the question. But the more I use pandas, the more I understand that it's a bad idea to append items to a Series one by one. I'll try to explain why for pandas beginners.

You might think that appending data to a given Series might allow you to reuse some resources, but in reality a Series is just a container that stores a relation between an index and a values array. Each is a numpy.array under the hood, and the index is immutable. When you add to Series an item with a label that is missing in the index, a new index with size n+1 is created, and a new values values array of the same size. That means that when you append items one by one, you create two more arrays of the n+1 size on each step.

By the way, you can not append a new item by position (you will get an IndexError) and the label in an index does not have to be unique, that is when you assign a value with a label, you assign the value to all existing items with the the label, and a new row is not appended in this case. This might lead to subtle bugs.

The moral of the story is that you should not append data one by one, you should better extend with an ordered collection. The problem is that you can not extend a Series inplace. That is why it is better to organize your code so that you don't need to update a specific instance of a Series by reference.

If you create labels yourself and they are increasing, the easiest way is to add new items to a dictionary, then create a new Series from the dictionary (it sorts the keys) and append the Series to an old one. If the keys are not increasing, then you will need to create two separate lists for the new labels and the new values.

Below are some code samples:

In [1]: import pandas as pd
In [2]: import numpy as np

In [3]: s = pd.Series(np.arange(4)**2, index=np.arange(4))

In [4]: s
Out[4]:
0    0
1    1
2    4
3    9
dtype: int64

In [6]: id(s.index), id(s.values)
Out[6]: (4470549648, 4470593296)

When we update an existing item, the index and the values array stay the same (if you do not change the type of the value)

In [7]: s[2] = 14  

In [8]: id(s.index), id(s.values)
Out[8]: (4470549648, 4470593296)

But when you add a new item, a new index and a new values array is generated:

In [9]: s[4] = 16

In [10]: s
Out[10]:
0     0
1     1
2    14
3     9
4    16
dtype: int64

In [11]: id(s.index), id(s.values)
Out[11]: (4470548560, 4470595056)

That is if you are going to append several items, collect them in a dictionary, create a Series, append it to the old one and save the result:

In [13]: new_items = {item: item**2 for item in range(5, 7)}

In [14]: s2 = pd.Series(new_items)

In [15]: s2  # keys are guaranteed to be sorted!
Out[15]:
5    25
6    36
dtype: int64

In [16]: s = s.append(s2); s
Out[16]:
0     0
1     1
2    14
3     9
4    16
5    25
6    36
dtype: int64

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

Returning JSON from a PHP Script

If you query a database and need the result set in JSON format it can be done like this:

<?php

$db = mysqli_connect("localhost","root","","mylogs");
//MSG
$query = "SELECT * FROM logs LIMIT 20";
$result = mysqli_query($db, $query);
//Add all records to an array
$rows = array();
while($row = $result->fetch_array()){
    $rows[] = $row;
}
//Return result to jTable
$qryResult = array();
$qryResult['logs'] = $rows;
echo json_encode($qryResult);

mysqli_close($db);

?>

For help in parsing the result using jQuery take a look at this tutorial.

How can I get an HTTP response body as a string?

Here's an example from another simple project I was working on using the httpclient library from Apache:

String response = new String();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j", request));
HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);

HttpPost httpPost = new HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
    response = EntityUtils.toString(responseEntity);
}

just use EntityUtils to grab the response body as a String. very simple.

A SQL Query to select a string between two known strings

Try this and replace '[' & ']' with your string

SELECT SUBSTRING(@TEXT,CHARINDEX('[',@TEXT)+1,(CHARINDEX(']',@TEXT)-CHARINDEX('[',@TEXT))-1)

How to move all HTML element children to another parent using JavaScript?

DEMO

Basically, you want to loop through each direct descendent of the old-parent node, and move it to the new parent. Any children of a direct descendent will get moved with it.

var newParent = document.getElementById('new-parent');
var oldParent = document.getElementById('old-parent');

while (oldParent.childNodes.length > 0) {
    newParent.appendChild(oldParent.childNodes[0]);
}

"unary operator expected" error in Bash if condition

If you know you're always going to use bash, it's much easier to always use the double bracket conditional compound command [[ ... ]], instead of the Posix-compatible single bracket version [ ... ]. Inside a [[ ... ]] compound, word-splitting and pathname expansion are not applied to words, so you can rely on

if [[ $aug1 == "and" ]];

to compare the value of $aug1 with the string and.

If you use [ ... ], you always need to remember to double quote variables like this:

if [ "$aug1" = "and" ];

If you don't quote the variable expansion and the variable is undefined or empty, it vanishes from the scene of the crime, leaving only

if [ = "and" ]; 

which is not a valid syntax. (It would also fail with a different error message if $aug1 included white space or shell metacharacters.)

The modern [[ operator has lots of other nice features, including regular expression matching.

How to get text box value in JavaScript

If you are using any user control and want to get any text box values then you can use the below code:

var result = document.getElementById('LE_OtherCostsDetails_txtHomeOwnerInsurance').value;

Here, LE_OtherCostsDetails, is the name of the user control and txtHomeOwnerInsurance is the id of the text box.

Is it possible to make a Tree View with Angular?

Yes it definitely possible. The question here probably assumes Angular 1.x, but for future reference I am including an Angular 2 example:

Conceptually all you have to do is create a recursive template:

<ul>
    <li *for="#dir of directories">

        <span><input type="checkbox" [checked]="dir.checked" (click)="dir.check()"    /></span> 
        <span (click)="dir.toggle()">{{ dir.name }}</span>

        <div *if="dir.expanded">
            <ul *for="#file of dir.files">
                {{file}}
            </ul>
            <tree-view [directories]="dir.directories"></tree-view>
        </div>
    </li>
</ul>

You then bind a tree object to the template and let Angular work its magic. This concept is obviously applicable to Angular 1.x as well.

Here is a complete example: http://www.syntaxsuccess.com/viewarticle/recursive-treeview-in-angular-2.0

How to change the Title of the window in Qt?

system("title WhateverYouWantToNameIt");

Convert char to int in C and C++

I was having problems converting a char array like "7c7c7d7d7d7d7c7c7c7d7d7d7d7c7c7c7c7c7c7d7d7c7c7c7c7d7c7d7d7d7c7c2e2e2e" into its actual integer value that would be able to be represented by `7C' as one hexadecimal value. So, after cruising for help I created this, and thought it would be cool to share.

This separates the char string into its right integers, and may be helpful to more people than just me ;)

unsigned int* char2int(char *a, int len)
{
    int i,u;
    unsigned int *val = malloc(len*sizeof(unsigned long));

    for(i=0,u=0;i<len;i++){
        if(i%2==0){
            if(a[i] <= 57)
                val[u] = (a[i]-50)<<4;
            else
                val[u] = (a[i]-55)<<4;
        }
        else{
            if(a[i] <= 57)
                val[u] += (a[i]-50);
            else
                val[u] += (a[i]-55);
            u++;
        }
    }
    return val;
}

Hope it helps!

Regex - how to match everything except a particular pattern

Match against the pattern and use the host language to invert the boolean result of the match. This will be much more legible and maintainable.

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

I'm using n (Node version management)

You can install it in two ways

brew install n

or

npm install -g n

You can switch between different version of node and io. Here's an example from my current env when I call n without params:

$ n

  io/3.3.1
  node/0.12.7
  node/4.0.0
  node/5.0.0
? node/5.10.1 

Passing properties by reference in C#

If you want to get and set the property both, you can use this in C#7:

GetString(
    inputString,
    (() => client.WorkPhone, x => client.WorkPhone = x))

void GetString(string inValue, (Func<string> get, Action<string> set) outValue)
{
    if (!string.IsNullOrEmpty(outValue))
    {
        outValue.set(inValue);
    }
}

What do .c and .h file extensions mean to C?

The .c is the source file and .h is the header file.

How to use Bootstrap in an Angular project?

  1. npm install --save bootstrap
  2. go to -> angular-cli.json file, find styles properties and just add next sting: "../node_modules/bootstrap/dist/css/bootstrap.min.css", It might be looks like this:

    "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
    ],
    

Cross-browser window resize event - JavaScript / jQuery

Using jQuery 1.9.1 I just found out that, although technically identical)*, this did not work in IE10 (but in Firefox):

// did not work in IE10
$(function() {
    $(window).resize(CmsContent.adjustSize);
});

while this worked in both browsers:

// did work in IE10
$(function() {
    $(window).bind('resize', function() {
        CmsContent.adjustSize();
    };
});

Edit:
)* Actually not technically identical, as noted and explained in the comments by WraithKenny and Henry Blyth.

Select rows with same id but different value in another column

$sql="SELECT * FROM TABLE_NAME WHERE item_id=".$item_id;

$query=mysql_query($sql);

while($myrow=mysql_fetch_array($query)) {

echo   print_r($myrow,1);


}

When use getOne and findOne methods Spring Data JPA

The basic difference is that getOne is lazy loaded and findOne is not.

Consider the following example:

public static String NON_EXISTING_ID = -1;
...
MyEntity getEnt = myEntityRepository.getOne(NON_EXISTING_ID);
MyEntity findEnt = myEntityRepository.findOne(NON_EXISTING_ID);

if(findEnt != null) {
     findEnt.getText(); // findEnt is null - this code is not executed
}

if(getEnt != null) {
     getEnt.getText(); // Throws exception - no data found, BUT getEnt is not null!!!
}

Manually type in a value in a "Select" / Drop-down HTML list?

Another common solution is adding "Other.." option to the drop down and when selected show text box that is otherwise hidden. Then when submitting the form, assign hidden field value with either the drop down or textbox value and in the server side code check the hidden value.

Example: http://jsfiddle.net/c258Q/

HTML code:

Please select: <form onsubmit="FormSubmit(this);">
<input type="hidden" name="fruit" />
<select name="fruit_ddl" onchange="DropDownChanged(this);">
    <option value="apple">Apple</option>
    <option value="orange">Apricot </option>
    <option value="melon">Peach</option>
    <option value="">Other..</option>
</select> <input type="text" name="fruit_txt" style="display: none;" />
<button type="submit">Submit</button>
</form>

JavaScript:

function DropDownChanged(oDDL) {
    var oTextbox = oDDL.form.elements["fruit_txt"];
    if (oTextbox) {
        oTextbox.style.display = (oDDL.value == "") ? "" : "none";
        if (oDDL.value == "")
            oTextbox.focus();
    }
}

function FormSubmit(oForm) {
    var oHidden = oForm.elements["fruit"];
    var oDDL = oForm.elements["fruit_ddl"];
    var oTextbox = oForm.elements["fruit_txt"];
    if (oHidden && oDDL && oTextbox)
        oHidden.value = (oDDL.value == "") ? oTextbox.value : oDDL.value;
}

And in the server side, read the value of "fruit" from the Request.

How to center a button within a div?

To center a <button type = "button"> both vertically and horizontally within a <div> which width is computed dynamically like in your case, this is what to do:

  1. Set text-align: center; to the wrapping <div>: this will center the button whenever you resize the <div> (or rather the window)
  2. For the vertical alignment, you will need to set margin: valuepx; for the button. This is the rule on how to calculate valuepx:

    valuepx = (wrappingDIVheight - buttonHeight)/2

Here is a JS Bin demo.

WinError 2 The system cannot find the file specified (Python)

I believe you need to .f file as a parameter, not as a command-single-string. same with the "--domain "+i, which i would split in two elements of the list. Assuming that:

  • you have the path set for FORTRAN executable,
  • the ~/ is indeed the correct way for the FORTRAN executable

I would change this line:

subprocess.Popen(["FORTRAN ~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain "+i])

to

subprocess.Popen(["FORTRAN", "~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f", "--domain", i])

If that doesn't work, you should do a os.path.exists() for the .f file, and check that you can launch the FORTRAN executable without any path, and set the path or system path variable accordingly

[EDIT 6-Mar-2017]

As the exception, detailed in the original post, is a python exception from subprocess; it is likely that the WinError 2 is because it cannot find FORTRAN

I highly suggest that you specify full path for your executable:

for i in input:
    exe = r'c:\somedir\fortrandir\fortran.exe'
    fortran_script = r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f'
    subprocess.Popen([exe, fortran_script, "--domain", i])

if you need to convert the forward-slashes to backward-slashes, as suggested in one of the comments, you can do this:

for i in input:
    exe = os.path.normcase(r'c:\somedir\fortrandir\fortran.exe')
    fortran_script = os.path.normcase(r'~/C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[EDIT 7-Mar-2017]

The following line is incorrect:

exe = os.path.normcase(r'~/C:/Program Files (x86)/Silverfrost/ftn95.exe'

I am not sure why you have ~/ as a prefix for every path, don't do that.

for i in input:
    exe = os.path.normcase(r'C:/Program Files (x86)/Silverfrost/ftn95.exe'
    fortran_script = os.path.normcase(r'C:/Users/Vishnu/Desktop/Fortran_Program_Rum/phase1.f')
    i = os.path.normcase(i)
    subprocess.Popen([exe, fortran_script, "--domain", i])

[2nd EDIT 7-Mar-2017]

I do not know this FORTRAN or ftn95.exe, does it need a shell to function properly?, in which case you need to launch as follows:

subprocess.Popen([exe, fortran_script, "--domain", i], shell = True)

You really need to try to launch the command manually from the working directory which your python script is operating from. Once you have the command which is actually working, then build up the subprocess command.

htaccess redirect to https://www

I try first answer and it doesnt work... This work:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Invert colors of an image in CSS or JavaScript

CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:

_x000D_
_x000D_
img {_x000D_
   -webkit-filter: invert(1);_x000D_
   filter: invert(1);_x000D_
   }
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
_x000D_
_x000D_

React Router with optional path parameter

For any React Router v4 users arriving here following a search, optional parameters in a <Route> are denoted with a ? suffix.

Here's the relevant documentation:

https://reacttraining.com/react-router/web/api/Route/path-string

path: string

Any valid URL path that path-to-regexp understands.

    <Route path="/users/:id" component={User}/>

https://www.npmjs.com/package/path-to-regexp#optional

Optional

Parameters can be suffixed with a question mark (?) to make the parameter optional. This will also make the prefix optional.

Simple example of a paginated section of a site that can be accessed with or without a page number.

    <Route path="/section/:page?" component={Section} />

Retrieve Button value with jQuery

You can also use the new HTML5 custom data- attributes.

<script type="text/javascript">
$(document).ready(function() {
    $('.my_button').click(function() {
        alert($(this).attr('data-value'));
    });
});
</script>

<button class="my_button" name="buttonName" data-value="buttonValue">Button Label</button>

EditText, clear focus on touch outside

The best way is use the default method clearFocus()

You know how to solve codes in onTouchListener right?

Just call EditText.clearFocus(). It will clear focus in last EditText.

CKEditor instance already exists

Its pretty simple. In my case, I ran the below jquery method that will destroy ckeditor instances during a page load. This did the trick and resolved the issue -

JQuery method -

function resetCkEditorsOnLoad(){

    for(var i in CKEDITOR.instances) {
        editor = CKEDITOR.instances[i];
            editor.destroy();
            editor = null;
    }
}

$(function() {

            $(".form-button").button();
    $(".button").button();

    resetCkEditorsOnLoad(); // CALLING THE METHOD DURING THE PAGE LOAD

            .... blah.. blah.. blah.... // REST OF YOUR BUSINESS LOGIC GOES HERE

       });

That's it. I hope it helps you.

Cheers, Sirish.

How to compare strings in sql ignoring case?

I don't recall the exact syntax, but you may set the table column to be case insensitive. But be careful because then you won't be able to match based on case anymore and if you WANT 'cool' to not match 'CoOl' it will no longer be possible.

C - freeing structs

Simple answer : free(testPerson) is enough .

Remember you can use free() only when you have allocated memory using malloc, calloc or realloc.

In your case you have only malloced memory for testPerson so freeing that is sufficient.

If you have used char * firstname , *last surName then in that case to store name you must have allocated the memory and that's why you had to free each member individually.

Here is also a point it should be in the reverse order; that means, the memory allocated for elements is done later so free() it first then free the pointer to object.

Freeing each element you can see the demo shown below:

typedef struct Person
{
char * firstname , *last surName;
}Person;
Person *ptrobj =malloc(sizeof(Person)); // memory allocation for struct
ptrobj->firstname = malloc(n); // memory allocation for firstname
ptrobj->surName = malloc(m); // memory allocation for surName

.
. // do whatever you want

free(ptrobj->surName);
free(ptrobj->firstname);
free(ptrobj);

The reason behind this is, if you free the ptrobj first, then there will be memory leaked which is the memory allocated by firstname and suName pointers.

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

What is the best way to iterate over a dictionary?

If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.

public new IEnumerator<T> GetEnumerator()
{
   return this.Values.GetEnumerator();
}

When to use single quotes, double quotes, and backticks in MySQL

In combination of PHP and MySQL, double quotes and single quotes make your query-writing time so much easier.

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

Now, suppose you are using a direct post variable into the MySQL query then, use it this way:

$query = "INSERT INTO `table` (`id`, `name`, `email`) VALUES (' ".$_POST['id']." ', ' ".$_POST['name']." ', ' ".$_POST['email']." ')";

This is the best practice for using PHP variables into MySQL.

How do I get the path of a process in Unix / Linux

You can find the exe easily by these ways, just try it yourself.

  • ll /proc/<PID>/exe
  • pwdx <PID>
  • lsof -p <PID> | grep cwd

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

Retrieve only the queried element in an object array in MongoDB collection

Thanks to JohnnyHK.

Here I just want to add some more complex usage.

// Document 
{ 
"_id" : 1
"shapes" : [
  {"shape" : "square",  "color" : "red"},
  {"shape" : "circle",  "color" : "green"}
  ] 
} 

{ 
"_id" : 2
"shapes" : [
  {"shape" : "square",  "color" : "red"},
  {"shape" : "circle",  "color" : "green"}
  ] 
} 


// The Query   
db.contents.find({
    "_id" : ObjectId(1),
    "shapes.color":"red"
},{
    "_id": 0,
    "shapes" :{
       "$elemMatch":{
           "color" : "red"
       } 
    }
}) 


//And the Result

{"shapes":[
    {
       "shape" : "square",
       "color" : "red"
    }
]}

Simple way to understand Encapsulation and Abstraction

Abstraction- Abstraction in simple words can be said as a way out in which the user is kept away from the complex details or detailed working of some system. You can also assume it as a simple way to solve any problem at the design and interface level.

You can say the only purpose of abstraction is to hide the details that can confuse a user. So for simplification purposes, we can use abstraction. Abstraction is also a concept of object-oriented programming. It hides the actual data and only shows the necessary information. For example, in an ATM machine, you are not aware that how it works internally. Only you are concerned to use the ATM interface. So that can be considered as a type of abstraction process.

Encapsulation- Encapsulation is also part of object-oriented programming. In this, all you have to do is to wrap up the data and code together so that they can work as a single unit. it works at the implementation level. it also improves the application Maintainance.

Encapsulation focuses on the process which will save information. Here you have to protect your data from external use.

.includes() not working in Internet Explorer

I had the same problem when working in Angular 5. In order to make it work directly without writing a polyfill yourself, just add the following line to polyfills.ts file:

import "core-js/es7/array"

Also, tsconfig.json lib section might be relevant:

"lib": [
  "es2017",
  "dom"
],

writing to serial port from linux command line

SCREEN:

NOTE: screen is actually not able to send hex, as far as I know. To do that, use echo or printf

I was using the suggestions in this post to write to a serial port, then using the info from another post to read from the port, with mixed results. I found that using screen is an "easier" solution, since it opens a terminal session directly with that port. (I put easier in quotes, because screen has a really weird interface, IMO, and takes some further reading to figure it out.)

You can issue this command to open a screen session, then anything you type will be sent to the port, plus the return values will be printed below it:

screen /dev/ttyS0 19200,cs8

(Change the above to fit your needs for speed, parity, stop bits, etc.) I realize screen isn't the "linux command line" as the post specifically asks for, but I think it's in the same spirit. Plus, you don't have to type echo and quotes every time.

ECHO:

Follow praetorian droid's answer. HOWEVER, this didn't work for me until I also used the cat command (cat < /dev/ttyS0) while I was sending the echo command.

PRINTF:

I found that one can also use printf's '%x' command:

c="\x"$(printf '%x' 0x12)
printf $c >> $SERIAL_COMM_PORT

Again, for printf, start cat < /dev/ttyS0 before sending the command.

Add multiple items to already initialized arraylist in java

If you have another list that contains all the items you would like to add you can do arList.addAll(otherList). Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll() method, with something like

Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
arList.addAll(Arrays.asList(otherList));

or, if you don't want to create that unnecessary array:

arList.addAll(Arrays.asList(1, 2, 3, 4, 5));

Otherwise you will have to have some sort of loop that adds the values to the list individually.

Android camera android.hardware.Camera deprecated

Faced with the same issue, supporting older devices via the deprecated camera API and needing the new Camera2 API for both current devices and moving into the future; I ran into the same issues -- and have not found a 3rd party library that bridges the 2 APIs, likely because they are very different, I turned to basic OOP principals.

The 2 APIs are markedly different making interchanging them problematic for client objects expecting the interfaces presented in the old API. The new API has different objects with different methods, built using a different architecture. Got love for Google, but ragnabbit! that's frustrating.

So I created an interface focussing on only the camera functionality my app needs, and created a simple wrapper for both APIs that implements that interface. That way my camera activity doesn't have to care about which platform its running on...

I also set up a Singleton to manage the API(s); instancing the older API's wrapper with my interface for older Android OS devices, and the new API's wrapper class for newer devices using the new API. The singleton has typical code to get the API level and then instances the correct object.

The same interface is used by both wrapper classes, so it doesn't matter if the App runs on Jellybean or Marshmallow--as long as the interface provides my app with what it needs from either Camera API, using the same method signatures; the camera runs in the App the same way for both newer and older versions of Android.

The Singleton can also do some related things not tied to the APIs--like detecting that there is indeed a camera on the device, and saving to the media library.

I hope the idea helps you out.

Where does Internet Explorer store saved passwords?

No guarantee, but I suspect IE uses the older Protected Storage API.

How to send email by using javascript or jquery

The short answer is that you can't do it using JavaScript alone. You'd need a server-side handler to connect with the SMTP server to actually send the mail. There are many simple mail scripts online, such as this one for PHP:

Simple PHP mail script

Using a script like that, you'd POST the contents of your web form to the script, using a function like this:

jQuery.post

And then the script would take those values, plus a username and password for the mail server, and connect to the server to send the mail.

How to parse the AndroidManifest.xml file inside an .apk package

In case it's useful, here's a C++ version of the Java snippet posted by Ribo:

struct decompressXML
{
    // decompressXML -- Parse the 'compressed' binary form of Android XML docs 
    // such as for AndroidManifest.xml in .apk files
    enum
    {
        endDocTag = 0x00100101,
        startTag =  0x00100102,
        endTag =    0x00100103
    };

    decompressXML(const BYTE* xml, int cb) {
    // Compressed XML file/bytes starts with 24x bytes of data,
    // 9 32 bit words in little endian order (LSB first):
    //   0th word is 03 00 08 00
    //   3rd word SEEMS TO BE:  Offset at then of StringTable
    //   4th word is: Number of strings in string table
    // WARNING: Sometime I indiscriminently display or refer to word in 
    //   little endian storage format, or in integer format (ie MSB first).
    int numbStrings = LEW(xml, cb, 4*4);

    // StringIndexTable starts at offset 24x, an array of 32 bit LE offsets
    // of the length/string data in the StringTable.
    int sitOff = 0x24;  // Offset of start of StringIndexTable

    // StringTable, each string is represented with a 16 bit little endian 
    // character count, followed by that number of 16 bit (LE) (Unicode) chars.
    int stOff = sitOff + numbStrings*4;  // StringTable follows StrIndexTable

    // XMLTags, The XML tag tree starts after some unknown content after the
    // StringTable.  There is some unknown data after the StringTable, scan
    // forward from this point to the flag for the start of an XML start tag.
    int xmlTagOff = LEW(xml, cb, 3*4);  // Start from the offset in the 3rd word.
    // Scan forward until we find the bytes: 0x02011000(x00100102 in normal int)
    for (int ii=xmlTagOff; ii<cb-4; ii+=4) {
      if (LEW(xml, cb, ii) == startTag) { 
        xmlTagOff = ii;  break;
      }
    } // end of hack, scanning for start of first start tag

    // XML tags and attributes:
    // Every XML start and end tag consists of 6 32 bit words:
    //   0th word: 02011000 for startTag and 03011000 for endTag 
    //   1st word: a flag?, like 38000000
    //   2nd word: Line of where this tag appeared in the original source file
    //   3rd word: FFFFFFFF ??
    //   4th word: StringIndex of NameSpace name, or FFFFFFFF for default NS
    //   5th word: StringIndex of Element Name
    //   (Note: 01011000 in 0th word means end of XML document, endDocTag)

    // Start tags (not end tags) contain 3 more words:
    //   6th word: 14001400 meaning?? 
    //   7th word: Number of Attributes that follow this tag(follow word 8th)
    //   8th word: 00000000 meaning??

    // Attributes consist of 5 words: 
    //   0th word: StringIndex of Attribute Name's Namespace, or FFFFFFFF
    //   1st word: StringIndex of Attribute Name
    //   2nd word: StringIndex of Attribute Value, or FFFFFFF if ResourceId used
    //   3rd word: Flags?
    //   4th word: str ind of attr value again, or ResourceId of value

    // TMP, dump string table to tr for debugging
    //tr.addSelect("strings", null);
    //for (int ii=0; ii<numbStrings; ii++) {
    //  // Length of string starts at StringTable plus offset in StrIndTable
    //  String str = compXmlString(xml, sitOff, stOff, ii);
    //  tr.add(String.valueOf(ii), str);
    //}
    //tr.parent();

    // Step through the XML tree element tags and attributes
    int off = xmlTagOff;
    int indent = 0;
    int startTagLineNo = -2;
    while (off < cb) {
      int tag0 = LEW(xml, cb, off);
      //int tag1 = LEW(xml, off+1*4);
      int lineNo = LEW(xml, cb, off+2*4);
      //int tag3 = LEW(xml, off+3*4);
      int nameNsSi = LEW(xml, cb, off+4*4);
      int nameSi = LEW(xml, cb, off+5*4);

      if (tag0 == startTag) { // XML START TAG
        int tag6 = LEW(xml, cb, off+6*4);  // Expected to be 14001400
        int numbAttrs = LEW(xml, cb, off+7*4);  // Number of Attributes to follow
        //int tag8 = LEW(xml, off+8*4);  // Expected to be 00000000
        off += 9*4;  // Skip over 6+3 words of startTag data
        std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
        //tr.addSelect(name, null);
        startTagLineNo = lineNo;

        // Look for the Attributes
        std::string sb;
        for (int ii=0; ii<numbAttrs; ii++) {
          int attrNameNsSi = LEW(xml, cb, off);  // AttrName Namespace Str Ind, or FFFFFFFF
          int attrNameSi = LEW(xml, cb, off+1*4);  // AttrName String Index
          int attrValueSi = LEW(xml, cb, off+2*4); // AttrValue Str Ind, or FFFFFFFF
          int attrFlags = LEW(xml, cb, off+3*4);  
          int attrResId = LEW(xml, cb, off+4*4);  // AttrValue ResourceId or dup AttrValue StrInd
          off += 5*4;  // Skip over the 5 words of an attribute

          std::string attrName = compXmlString(xml, cb, sitOff, stOff, attrNameSi);
          std::string attrValue = attrValueSi!=-1
            ? compXmlString(xml, cb, sitOff, stOff, attrValueSi)
            : "resourceID 0x"+toHexString(attrResId);
          sb.append(" "+attrName+"=\""+attrValue+"\"");
          //tr.add(attrName, attrValue);
        }
        prtIndent(indent, "<"+name+sb+">");
        indent++;

      } else if (tag0 == endTag) { // XML END TAG
        indent--;
        off += 6*4;  // Skip over 6 words of endTag data
        std::string name = compXmlString(xml, cb, sitOff, stOff, nameSi);
        prtIndent(indent, "</"+name+">  (line "+toIntString(startTagLineNo)+"-"+toIntString(lineNo)+")");
        //tr.parent();  // Step back up the NobTree

      } else if (tag0 == endDocTag) {  // END OF XML DOC TAG
        break;

      } else {
        prt("  Unrecognized tag code '"+toHexString(tag0)
          +"' at offset "+toIntString(off));
        break;
      }
    } // end of while loop scanning tags and attributes of XML tree
    prt("    end at offset "+off);
    } // end of decompressXML


    std::string compXmlString(const BYTE* xml, int cb, int sitOff, int stOff, int strInd) {
      if (strInd < 0) return std::string("");
      int strOff = stOff + LEW(xml, cb, sitOff+strInd*4);
      return compXmlStringAt(xml, cb, strOff);
    }

    void prt(std::string str)
    {
        printf("%s", str.c_str());
    }
    void prtIndent(int indent, std::string str) {
        char spaces[46];
        memset(spaces, ' ', sizeof(spaces));
        spaces[min(indent*2,  sizeof(spaces) - 1)] = 0;
        prt(spaces);
        prt(str);
        prt("\n");
    }


    // compXmlStringAt -- Return the string stored in StringTable format at
    // offset strOff.  This offset points to the 16 bit string length, which 
    // is followed by that number of 16 bit (Unicode) chars.
    std::string compXmlStringAt(const BYTE* arr, int cb, int strOff) {
        if (cb < strOff + 2) return std::string("");
      int strLen = arr[strOff+1]<<8&0xff00 | arr[strOff]&0xff;
      char* chars = new char[strLen + 1];
      chars[strLen] = 0;
      for (int ii=0; ii<strLen; ii++) {
          if (cb < strOff + 2 + ii * 2)
          {
              chars[ii] = 0;
              break;
          }
        chars[ii] = arr[strOff+2+ii*2];
      }
      std::string str(chars);
      free(chars);
      return str;
    } // end of compXmlStringAt


    // LEW -- Return value of a Little Endian 32 bit word from the byte array
    //   at offset off.
    int LEW(const BYTE* arr, int cb, int off) {
      return (cb > off + 3) ? ( arr[off+3]<<24&0xff000000 | arr[off+2]<<16&0xff0000
          | arr[off+1]<<8&0xff00 | arr[off]&0xFF ) : 0;
    } // end of LEW

    std::string toHexString(DWORD attrResId)
    {
        char ch[20];
        sprintf_s(ch, 20, "%lx", attrResId);
        return std::string(ch);
    }
    std::string toIntString(int i)
    {
        char ch[20];
        sprintf_s(ch, 20, "%ld", i);
        return std::string(ch);
    }
};

height style property doesn't work in div elements

Set positioning to absolute. That will solve the problem immediately, but might cause some problems in layout later. You can always figure out a way around them ;)

Example:

position:absolute;

Run PHP Task Asynchronously

PHP is a single-threaded language, so there is no official way to start an asynchronous process with it other than using exec or popen. There is a blog post about that here. Your idea for a queue in MySQL is a good idea as well.

Your specific requirement here is for sending an email to the user. I'm curious as to why you are trying to do that asynchronously since sending an email is a pretty trivial and quick task to perform. I suppose if you are sending tons of email and your ISP is blocking you on suspicion of spamming, that might be one reason to queue, but other than that I can't think of any reason to do it this way.

PHP split alternative?

split is deprecated since it is part of the family of functions which make use of POSIX regular expressions; that entire family is deprecated in favour of the PCRE (preg_*) functions.

If you do not need the regular expression functionality, then explode is a very good choice (and would have been recommended over split even if that were not deprecated), if on the other hand you do need to use regular expressions then the PCRE alternate is simply preg_split.

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

The moral of this strangeness is:

  • Use dates and times in UTC wherever possible.
  • If you can not display a date or time in UTC, always indicate the time-zone.
  • If you can not require an input date/time in UTC, require an explicitly indicated time-zone.

Delete all data in SQL Server database

Yes, it is possible to delete with a single line of code

SELECT 'TRUNCATE TABLE ' + d.NAME + ';' 
FROM   sys.tables d 
WHERE  type = 'U' 

How to access the content of an iframe with jQuery?

You have to use the contents() method:

$("#myiframe").contents().find("#myContent")

Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/

API Doc: https://api.jquery.com/contents/

Using Tkinter in python to edit the title bar

Example of python GUI


Here is an example:

from tkinter import *;
screen = Tk();
screen.geometry("370x420"); //size of screen

Change the name of window

  screen.title('Title Name')

Run it:

screen.mainloop();

MySQL limit from descending order

This way is comparatively more easy

SELECT doc_id,serial_number,status FROM date_time ORDER BY  date_time DESC LIMIT 0,1;

Navigation Controller Push View Controller

Let's Say If you want to go from ViewController A --> B then

  1. Make sure your ViewControllerA is embedded in Navigation Controller

  2. In ViewControllerA's Button click you should have code like this.

@IBAction func goToViewController(_ sender: Any) {

    if let viewControllerB = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ViewControllerB") as? ViewControllerB {

        if let navigator = navigationController {
            navigator.pushViewController(viewControllerB, animated: true)
        }
    }
}
  1. Please double check your storyboard name, and ViewControllerB's Identifier mentioned in storyboard for ViewControllerB's View

Look at StoryboardID = ViewControllerB

enter image description here

Is there a Google Voice API?

There is a C# Google Voice API... there is limited documentation, however the download has an application that 'works' using the API that is included:

https://sourceforge.net/projects/gvoicedotnet/

Difference between a Seq and a List in Scala

A Seq is an Iterable that has a defined order of elements. Sequences provide a method apply() for indexing, ranging from 0 up to the length of the sequence. Seq has many subclasses including Queue, Range, List, Stack, and LinkedList.

A List is a Seq that is implemented as an immutable linked list. It's best used in cases with last-in first-out (LIFO) access patterns.

Here is the complete collection class hierarchy from the Scala FAQ:

enter image description here

How can I de-install a Perl module installed via `cpan`?

  1. Install App::cpanminus from CPAN (use: cpan App::cpanminus for this).
  2. Type cpanm --uninstall Module::Name (note the "m") to uninstall the module with cpanminus.

This should work.

Removing X-Powered-By

This solution worked for me :)

Please add below line in the script and check.

Ngnix / Apache etc level settings might not be required.

header("Server:");

Declare multiple module.exports in Node.js

There are multiple ways to do this, one way is mentioned below. Just assume you have .js file like this.

let add = function (a, b) {
   console.log(a + b);
};

let sub = function (a, b) {
   console.log(a - b);
};

You can export these functions using the following code snippet,

 module.exports.add = add;
 module.exports.sub = sub;

And you can use the exported functions using this code snippet,

var add = require('./counter').add;
var sub = require('./counter').sub;

add(1,2);
sub(1,2);

I know this is a late reply, but hope this helps!

Basic authentication for REST API using spring restTemplate

Instead of instantiating as follows:

TestRestTemplate restTemplate = new TestRestTemplate();

Just do it like this:

TestRestTemplate restTemplate = new TestRestTemplate(user, password);

It works for me, I hope it helps!

Django set field value after a form is initialized

Since you're not passing in POST data, I'll assume that what you are trying to do is set an initial value that will be displayed in the form. The way you do this is with the initial keyword.

form = CustomForm(initial={'Email': GetEmailString()})

See the Django Form docs for more explanation.

If you are trying to change a value after the form was submitted, you can use something like:

if form.is_valid():
    form.cleaned_data['Email'] = GetEmailString()

Check the referenced docs above for more on using cleaned_data

How to export table as CSV with headings on Postgresql?

I am posting this answer because none of the other answers given here actually worked for me. I could not use COPY from within Postgres, because I did not have the correct permissions. So I chose "Export grid rows" and saved the output as UTF-8.

The psql version given by @Brian also did not work for me, for a different reason. The reason it did not work is that apparently the Windows command prompt (I was using Windows) was meddling around with the encoding on its own. I kept getting this error:

ERROR: character with byte sequence 0x81 in encoding "WIN1252" has no equivalent in encoding "UTF8"

The solution I ended up using was to write a short JDBC script (Java) which read the CSV file and issued insert statements directly into my Postgres table. This worked, but the command prompt also would have worked had it not been altering the encoding.

Stop absolutely positioned div from overlapping text

Put a z-indez of -1 on your absolute (or relative) positioned element.

This will pull it out of the stacking context. (I think.) Read more wonderful things about "stacking contexts" here: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

What is the time complexity of indexing, inserting and removing from common data structures?

Amortized Big-O for hashtables:

  • Insert - O(1)
  • Retrieve - O(1)
  • Delete - O(1)

Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.

What is fastest children() or find() in jQuery?

Here is a link that has a performance test you can run. find() is actually about 2 times faster than children().

Chrome on OSX10.7.6

Where am I? - Get country

This will get the country code set for the phone (phones language, NOT user location):

 String locale = context.getResources().getConfiguration().locale.getCountry(); 

can also replace getCountry() with getISO3Country() to get a 3 letter ISO code for the country. This will get the country name:

 String locale = context.getResources().getConfiguration().locale.getDisplayCountry();

This seems easier than the other methods and rely upon the localisation settings on the phone, so if a US user is abroad they probably still want Fahrenheit and this will work :)

Editors note: This solution has nothing to do with the location of the phone. It is constant. When you travel to Germany locale will NOT change. In short: locale != location.

How to find the unclosed div tag

Taking Milad's suggestion a bit further, you can break your document source down and then do another find, continuing until you find the unmatched culprit.

When you are working with many modules (using a CMS), or don't have access to the W3C tool (because you are working locally), this approach is really helpful.

How to check if the user can go back in browser history or not

I came up with the following approach. It utilizes the onbeforeunload event to detect whether the browser starts leaving the page or not. If it does not in a certain timespan it'll just redirect to the fallback.

var goBack = function goBack(fallback){
    var useFallback = true;

    window.addEventListener("beforeunload", function(){
      useFallback = false;
    });

    window.history.back();

    setTimeout(function(){
        if (useFallback){ window.location.href = fallback; }
    }, 100); 
}

You can call this function using goBack("fallback.example.org").

Show/Hide Multiple Divs with Jquery

If they fall into logical groups, I would probably go with the class approach already listed here.

Many people seem to forget that you can actually select several items by id in the same jQuery selector, as well:

$("#div1, #div2, #div3").show();

Where 'div1', 'div2', and 'div3' are all id attributes on various divs you want to show at once.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Look no more for IP addresses not being set in the expected header. Just do the following to inspect the whole server variables and figure out which one is suitable for your case:

print_r($_SERVER);

How to access command line arguments of the caller inside a function?

My reading of the Bash Reference Manual says this stuff is captured in BASH_ARGV, although it talks about "the stack" a lot.

#!/bin/bash

function argv {
    for a in ${BASH_ARGV[*]} ; do
      echo -n "$a "
    done
    echo
}

function f {
    echo f $1 $2 $3
    echo -n f ; argv
}

function g {
    echo g $1 $2 $3
    echo -n g; argv
    f
}

f boo bar baz
g goo gar gaz

Save in f.sh

$ ./f.sh arg0 arg1 arg2
f boo bar baz
farg2 arg1 arg0 
g goo gar gaz
garg2 arg1 arg0 
f
farg2 arg1 arg0 

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

You will have to include driver jar for MySQL MySQL Connector Jar in your classpath.

If you are using Eclipse: How to add dependent libraries in Eclipse

If you are using command line include the path to the driver jar using the -cp parameter of java.

java -cp C:\lib\* Main

Python: How to get stdout after running os.system?

These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out = p.stdout.read()
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)
    return p.stdout.read()

Copying data from one SQLite database to another

If you use DB Browser for SQLite, you can copy the table from one db to another in following steps:

  1. Open two instances of the app and load the source db and target db side by side.
  2. If the target db does not have the table, "Copy Create Statement" from the source db and then paste the sql statement in "Execute SQL" tab and run the sql to create the table.
  3. In the source db, export the table as a CSV file.
  4. In the target db, import the CSV file to the table with the same table name. The app will ask you do you want to import the data to the existing table, click yes. Done.

.NET String.Format() to add commas in thousands place for a number

If you want to show it in DataGridview , you should change its type , because default is String and since you change it to decimal it considers as Number with floating point

Dim dt As DataTable = New DataTable
dt.Columns.Add("col1", GetType(Decimal))
dt.Rows.Add(1)
dt.Rows.Add(10)
dt.Rows.Add(2)

DataGridView1.DataSource = dt

Dynamic creation of table with DOM

You can create a dynamic table rows as below:

var tbl = document.createElement('table');
tbl.style.width = '100%';

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

        tr = document.createElement('tr');

        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');

        ::::: // As many <td> you want

        td1.appendChild(document.createTextNode());
        td2.appendChild(document.createTextNode());
        td3.appendChild(document.createTextNode();

        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);

        tbl.appendChild(tr);
}

Making a Windows shortcut start relative to where the folder is?

The method that proposed by 'leoj' does not allow passing parameters with spaces. Us it:

    cmd.exe /v /c %CD:~0,2%"%CD:~2%\bat\bat\run.bat" "Par1-1 Par1-2" Par2

Which will be similar double quote written as in path

    C:"\Program Files\anyProgram.exe" "Par1-1 Par1-2" Par2

Cannot connect to repo with TortoiseSVN

I faced similar issue while doing svn update.

The approach which worked for me is to rename C:\Users\user\AppData\Roaming\TortoiseSVN folder to TortoiseSVN_bkp folder and then tried svn update again. This time I was able to connect to repository and it got updated.

How can I set NODE_ENV=production on Windows?

Here is the non-command line method:

In Windows 7 or 10, type environment into the start menu search box, and select Edit the system environment variables.

Alternatively, navigate to Control Panel\System and Security\System, and click Advanced system settings

This should open up the System properties dialog box with the Advanced tab selected. At the bottom, you will see an Environment Variables... button. Click this.

System Dialog Box

The Environment Variables Dialog Box will open.

Environment Variable Dialog Box

At the bottom, under System variables, select New...This will open the New System Variable dialog box.

enter image description here

Enter the variable name and value, and click OK.

You will need to close all cmd prompts and restart your server for the new variable to be available to process.env. If it still doesn't show up, restart your machine.

javascript: Disable Text Select

Just use this css method:

body{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

You can find the same answer here: How to disable text selection highlighting using CSS?

Transactions in .net

if you just need it for db-related stuff, some OR Mappers (e.g. NHibernate) support transactinos out of the box per default.

C# looping through an array

Just increment i by 3 in each step:

  Debug.Assert((theData.Length % 3) == 0);  // 'theData' will always be divisible by 3

  for (int i = 0; i < theData.Length; i += 3)
  {
       //grab 3 items at a time and do db insert, 
       // continue until all items are gone..
       string item1 = theData[i+0];
       string item2 = theData[i+1];
       string item3 = theData[i+2];
       // use the items
  }

To answer some comments, it is a given that theData.Length is a multiple of 3 so there is no need to check for theData.Length-2 as an upperbound. That would only mask errors in the preconditions.

Check if image exists on server using JavaScript?

If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Sophia Alpert of the React team here

getInitialState: function(event) {
    return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
    this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
    return (
        <img onError={this.handleError} src={src} />;
    );
}

jQuery SVG vs. Raphael

You should also take a look at svgweb. It uses flash to render svg in IE, and optionally on other browsers (in the cases where it supports more than the browser itself does).

http://code.google.com/p/svgweb/

How stable is the git plugin for eclipse?

I'm using if for day-to-day work and I find it stable. Lately the plugin has made good progress and has added:

  • merge support, including a in-Eclipse merge tool;
  • a basic synchronise view;
  • reading of .git/info/exclude and .gitignore files.
  • rebasing;
  • streamlined commands for pushing and pulling;
  • cherry-picking.

Git repositories view

Be sure to skim the EGit User Guide for a good overview of the current functionality.

I find that I only need to drop to the comand line for interactive rebases.

As an official Eclipse project I am confident that EGit will receive all the main features of the command-line client.

Loop through all the resources in a .resx file

Using LINQ to SQL:

XDocument
        .Load(resxFileName)
        .Descendants()
        .Where(_ => _.Name == "data")
        .Select(_ => $"{ _.Attributes().First(a => a.Name == "name").Value} - {_.Value}");

How to force NSLocalizedString to use a specific language

I usually do this in this way, but you MUST have all localization files in your project.

@implementation Language

static NSBundle *bundle = nil;

+(void)initialize 
{
    NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
    NSArray* languages = [defs objectForKey:@"AppleLanguages"];
    NSString *current = [[languages objectAtIndex:0] retain];
    [self setLanguage:current];
}

/*
  example calls:
    [Language setLanguage:@"it"];
    [Language setLanguage:@"de"];
*/
+(void)setLanguage:(NSString *)l
{
    NSLog(@"preferredLang: %@", l);
    NSString *path = [[ NSBundle mainBundle ] pathForResource:l ofType:@"lproj" ];
    bundle = [[NSBundle bundleWithPath:path] retain];
}

+(NSString *)get:(NSString *)key alter:(NSString *)alternate 
{
    return [bundle localizedStringForKey:key value:alternate table:nil];
}

@end

How can I get color-int from color resource?

Based on the new Android Support Library (and this update), now you should call:

ContextCompat.getColor(context, R.color.name.color);

According to the documentation:

public int getColor (int id)

This method was deprecated in API level 23. Use getColor(int, Theme) instead

It is the same solution for getResources().getColorStateList(id):

You have to change it like this:

ContextCompat.getColorStateList(getContext(),id);

EDIT 2019

Regarding ThemeOverlay use the context of the closest view:

val color = ContextCompat.getColor(
  closestView.context,
  R.color.name.color
)

So this way you get the right color based on your ThemeOverlay.

Specially needed when in same activity you use different themes, like dark/light theme. If you would like to understand more about Themes and Styles this talk is suggested: Developing Themes with Style

Nick Butcher - Droidcon Berlin - Developing Themes with Style

What's the difference between map() and flatMap() methods in Java 8?

Oracle's article on Optional highlights this difference between map and flatmap:

String version = computer.map(Computer::getSoundcard)
                  .map(Soundcard::getUSB)
                  .map(USB::getVersion)
                  .orElse("UNKNOWN");

Unfortunately, this code doesn't compile. Why? The variable computer is of type Optional<Computer>, so it is perfectly correct to call the map method. However, getSoundcard() returns an object of type Optional. This means the result of the map operation is an object of type Optional<Optional<Soundcard>>. As a result, the call to getUSB() is invalid because the outermost Optional contains as its value another Optional, which of course doesn't support the getUSB() method.

With streams, the flatMap method takes a function as an argument, which returns another stream. This function is applied to each element of a stream, which would result in a stream of streams. However, flatMap has the effect of replacing each generated stream by the contents of that stream. In other words, all the separate streams that are generated by the function get amalgamated or "flattened" into one single stream. What we want here is something similar, but we want to "flatten" a two-level Optional into one.

Optional also supports a flatMap method. Its purpose is to apply the transformation function on the value of an Optional (just like the map operation does) and then flatten the resulting two-level Optional into a single one.

So, to make our code correct, we need to rewrite it as follows using flatMap:

String version = computer.flatMap(Computer::getSoundcard)
                   .flatMap(Soundcard::getUSB)
                   .map(USB::getVersion)
                   .orElse("UNKNOWN");

The first flatMap ensures that an Optional<Soundcard> is returned instead of an Optional<Optional<Soundcard>>, and the second flatMap achieves the same purpose to return an Optional<USB>. Note that the third call just needs to be a map() because getVersion() returns a String rather than an Optional object.

http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html

How to add element into ArrayList in HashMap

HashMap<String, ArrayList<Item>> items = new HashMap<String, ArrayList<Item>>();

public synchronized void addToList(String mapKey, Item myItem) {
    List<Item> itemsList = items.get(mapKey);

    // if list does not exist create it
    if(itemsList == null) {
         itemsList = new ArrayList<Item>();
         itemsList.add(myItem);
         items.put(mapKey, itemsList);
    } else {
        // add if item is not already in list
        if(!itemsList.contains(myItem)) itemsList.add(myItem);
    }
}

Subtract two variables in Bash

Alternatively to the suggested 3 methods you can try let which carries out arithmetic operations on variables as follows:

let COUNT=$FIRSTV-$SECONDV

or

let COUNT=FIRSTV-SECONDV

How do I run a shell script without using "sh" or "bash" commands?

Here is my backup script that will give you the idea and the automation:

Server: Ubuntu 16.04 PHP: 7.0 Apache2, Mysql etc...

# Make Shell Backup Script - Bash Backup Script
    nano /home/user/bash/backupscript.sh
        #!/bin/bash
        # Backup All Start
        mkdir /home/user/backup/$(date +"%Y-%m-%d")
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_rest.zip /etc -x "*apache2*" -x "*php*" -x "*mysql*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_apache2.zip /etc/apache2
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_php.zip /etc/php
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/etc_mysql.zip /etc/mysql
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_rest.zip /var/www -x "*html*"
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/var_www_html.zip /var/www/html
        sudo zip -ry /home/user/backup/$(date +"%Y-%m-%d")/home_user.zip /home/user -x "*backup*"
        # Backup All End
        echo "Backup Completed Successfully!"
        echo "Location: /home/user/backup/$(date +"%Y-%m-%d")"

    chmod +x /home/user/bash/backupscript.sh
    sudo ln -s /home/user/bash/backupscript.sh /usr/bin/backupscript

change /home/user to your user directory and type: backupscript anywhere on terminal to run the script! (assuming that /usr/bin is in your path)

How to run .sh on Windows Command Prompt?

On Windows 10 Anniversary Update, it's even easier to run shell commands in/with bash on ubuntu on windows

I was trying to set my region for my x-wrt r7000 netgear router, I found the following worked for me, using bash on ubuntu on windows, you do have to enable subsystem found in windows features, and dev mode on

ssh [email protected] < /mnt/c/ccode-eu.sh

Sending credentials with cross-domain posts?

You can use the beforeSend callback to set additional parameters (The XMLHTTPRequest object is passed to it as its only parameter).

Just so you know, this type of cross-domain request will not work in a normal site scenario and not with any other browser. I don't even know what security limitations FF 3.5 imposes as well, just so you don't beat your head against the wall for nothing:

$.ajax({
    url: 'http://bar.other',
    data: { whatever:'cool' },
    type: 'GET',
    beforeSend: function(xhr){
       xhr.withCredentials = true;
    }
});

One more thing to beware of, is that jQuery is setup to normalize browser differences. You may find that further limitations are imposed by the jQuery library that prohibit this type of functionality.

How do I install an R package from source?

A supplementarily handy (but trivial) tip for installing older version of packages from source.

First, if you call "install.packages", it always installs the latest package from repo. If you want to install the older version of packages, say for compatibility, you can call install.packages("url_to_source", repo=NULL, type="source"). For example:

install.packages("http://cran.r-project.org/src/contrib/Archive/RNetLogo/RNetLogo_0.9-6.tar.gz", repo=NULL, type="source")

Without manually downloading packages to the local disk and switching to the command line or installing from local disk, I found it is very convenient and simplify the call (one-step).

Plus: you can use this trick with devtools library's dev_mode, in order to manage different versions of packages:

Reference: doc devtools

Difference between "or" and || in Ruby?

The way I use these operators:

||, && are for boolean logic. or, and are for control flow. E.g.

do_smth if may_be || may_be -- we evaluate the condition here

do_smth or do_smth_else -- we define the workflow, which is equivalent to do_smth_else unless do_smth

to give a simple example:

> puts "a" && "b"
b

> puts 'a' and 'b'
a

A well-known idiom in Rails is render and return. It's a shortcut for saying return if render, while render && return won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.

How can I undo git reset --hard HEAD~1?

I know this is an old thread... but as many people are searching for ways to undo stuff in Git, I still think it may be a good idea to continue giving tips here.

When you do a "git add" or move anything from the top left to the bottom left in git gui the content of the file is stored in a blob and the file content is possible to recover from that blob.

So it is possible to recover a file even if it was not committed but it has to have been added.

git init  
echo hello >> test.txt  
git add test.txt  

Now the blob is created but it is referenced by the index so it will no be listed with git fsck until we reset. So we reset...

git reset --hard  
git fsck  

you will get a dangling blob ce013625030ba8dba906f756967f9e9ca394464a

git show ce01362  

will give you the file content "hello" back

To find unreferenced commits I found a tip somewhere suggesting this.

gitk --all $(git log -g --pretty=format:%h)  

I have it as a tool in git gui and it is very handy.

"unable to locate adb" using Android Studio

if using avast go for virus chest,will find adb,restore it by clicking right button..thats all,perfectly works

How to redirect docker container logs to a single file?

If you work on Windows and use PowerShell (like me), you could use the following line to capture the stdout and stderr:

 docker logs <containerId> | Out-File 'C:/dev/mylog.txt'

I hope it helps someone!

How to make a promise from setTimeout

const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

We can pass custom 'cb fxn' like this one

commands not found on zsh

I fixed the issue by opening the terminal preference general tab and changing the Command (complete path) to /bin/bash to default and then editing the ~/.zshrc file.

enter image description here

export PATH="all your path inside the quotes"

...without any whitespace between the PATH=" and save the file.

enter image description here

After saving the file, change the /bin/zsh in your command or select default enter image description here

...and restart terminal and you should have your zsh shell working again!

How does one capture a Mac's command key via JavaScript?

if you use Vuejs, just make it by vue-shortkey plugin, everything will be simple

https://www.npmjs.com/package/vue-shortkey

v-shortkey="['meta', 'enter']"·
@shortkey="metaEnterTrigged"

Waiting for HOME ('android.process.acore') to be launched

This problem occurs because while creating the AVD manager in the "Create new Android virtual device(AVD)" dialog window ,"Snapshot" was marked as "Enabled" by me.

Solution:

Create a new AVD manager with the "Enabled" checkbox not checked and then try running the project with the newly created AVD manager as "Target" , the problem will not occur anymore

How do I create an array of strings in C?

Ack! Constant strings:

const char *strings[] = {"one","two","three"};

If I remember correctly.

Oh, and you want to use strcpy for assignment, not the = operator. strcpy_s is safer, but it's neither in C89 nor in C99 standards.

char arr[MAX_NUMBER_STRINGS][MAX_STRING_SIZE]; 
strcpy(arr[0], "blah");

Update: Thomas says strlcpy is the way to go.

Difference between Interceptor and Filter in Spring MVC

A HandlerInterceptor gives you more fine-grained control than a filter, because you have access to the actual target "handler" - this means that whatever action you perform can vary depending on what the request is actually doing (whereas the servlet filter is generically applied to all requests - only able to take into account the parameters of each request). The handlerInterceptor also provides 3 different methods, so that you can apply behavior prior to calling a handler, after the handler has completed but prior to view rendering (where you may even bypass view rendering altogether), or after the view itself has been rendered. Also, you can set up different interceptors for different groups of handlers - the interceptors are configured on the handlerMapping, and there may be multiple handlerMappings.

Therefore, if you have a need to do something completely generic (e.g. log all requests), then a filter is sufficient - but if the behavior depends on the target handler or you want to do something between the request handling and view rendering, then the HandlerInterceptor provides that flexibility.

Reference: http://static.springframework.org/sp...ng-interceptor

Use a LIKE statement on SQL Server XML Datatype

This is what I am going to use based on marc_s answer:

SELECT 
SUBSTRING(DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)'),PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')) - 20,999)

FROM WEBPAGECONTENT 
WHERE COALESCE(PATINDEX('%NORTH%',DATA.value('(/PAGECONTENT/TEXT)[1]', 'VARCHAR(100)')),0) > 0

Return a substring on the search where the search criteria exists

Java - How to convert type collection into ArrayList?

public <E> List<E> collectionToList(Collection<E> collection)
{
    return (collection instanceof List) ? (List<E>) collection : new ArrayList<E>(collection);
}

Use the above method for converting the collection to list

Import data into Google Colaboratory

The Best and easy way to upload data / import data into Google colab GUI way is click on left most 3rd option File menu icon and there you will get upload browser files as you get in windows OS .Check below the images for better easy understanding.After clicking on below two options you will get upload window box easy. work done. enter image description here

from google.colab import files
files=files.upload()

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

Command copy exited with code 4 when building - Visual Studio restart solves it

Run VS in Administrator mode and it should work fine.

Selecting a Record With MAX Value

Here's an option if you have multiple records for each Customer and are looking for the latest balance for each (say they are dated records):

SELECT ID, BALANCE FROM (
    SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY DateModified DESC) as RowNum, ID, BALANCE
    FROM CUSTOMERS
) C
WHERE RowNum = 1

Automatically enter SSH password with script

This is how I login to my servers.

ssp <server_ip>
  • alias ssp='/home/myuser/Documents/ssh_script.sh'
  • cat /home/myuser/Documents/ssh_script.sh

#!/bin/bash

sshpass -p mypassword ssh root@$1

And therefore...

ssp server_ip

iPhone and WireShark

The easiest way of doing this will be to use wifi of course. You will need to determine if your wifi base acts as a hub or a switch. If it acts as a hub then just connect your windows pc to it and wireshark should be able to see all the traffic from the iPhone. If it is a switch then your easiest bet will be to buy a cheap hub and connect the wan side of your wifi base to the hub and then connect your windows pc running wireshark to the hub as well. At that point wireshark will be able to see all the traffic as it passes over the hub.

How can I find the first occurrence of a sub-string in a python string?

verse = "If you can keep your head when all about you\n Are losing theirs and blaming it on you,\nIf you can trust yourself when all men doubt you,\n But make allowance for their doubting too;\nIf you can wait and not be tired by waiting,\n Or being lied about, don’t deal in lies,\nOr being hated, don’t give way to hating,\n And yet don’t look too good, nor talk too wise:"

enter code here

print(verse)
#1. What is the length of the string variable verse?
verse_length = len(verse)
print("The length of verse is: {}".format(verse_length))
#2. What is the index of the first occurrence of the word 'and' in verse?
index = verse.find("and")
print("The index of the word 'and' in verse is {}".format(index))

How to shutdown a Spring Boot Application in a correct way?

If you are in a linux environment all you have to do is to create a symlink to your .jar file from inside /etc/init.d/

sudo ln -s /path/to/your/myboot-app.jar /etc/init.d/myboot-app

Then you can start the application like any other service

sudo /etc/init.d/myboot-app start

To close the application

sudo /etc/init.d/myboot-app stop

This way, application will not terminate when you exit the terminal. And application will shutdown gracefully with stop command.

Gradle proxy configuration

This is my gradle.properties, please note those HTTPS portion

systemProp.http.proxyHost=127.0.0.1
systemProp.http.proxyPort=8118
systemProp.https.proxyHost=127.0.0.1
systemProp.https.proxyPort=8118

eclipse stuck when building workspace

I faced the same problem when I tried to install Angular.js with bower in my project. I seems bower has lots of javascript files it downloaded automatically which caused my IDE to stuck in validation process for a long time. So, I solved this problem this way,

  • I first installed tern.js 0.9.0.
  • Then I went to the project properties, selected tern script path included only the path I needed for validation, My project's javascript folder. I excluded other path like placeholders, Angular.js files, Jquery files.
  • I selected the Javascript from the properties again and did the same things in include path's source.

My IDE currently working without freezing. I took help from there. Tern I guess it can be helpful, where any IDE stuck due to lots of Javascript file.

Convert string to JSON Object

Quick answer, this eval work:

eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')

How to get distinct results in hibernate with joins and row-based limiting (paging)?

The solution:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

works very well.

Change x axes scale in matplotlib

Try using matplotlib.pyplot.ticklabel_format:

import matplotlib.pyplot as plt
...
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

This applies scientific notation (i.e. a x 10^b) to your x-axis tickmarks

Global npm install location on windows?

Just press windows button and type %APPDATA% and type enter.

Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.