Programs & Examples On #Spatialite

Spatialite is a library extending the basic SQLite core in order to get a full fledged Spatial DBMS.

How to open .SQLite files

I would suggest using R and the package RSQLite

#install.packages("RSQLite") #perhaps needed
library("RSQLite")

# connect to the sqlite file
sqlite    <- dbDriver("SQLite")
exampledb <- dbConnect(sqlite,"database.sqlite")

dbListTables(exampledb)

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

How to see full absolute path of a symlink

Another way to see information is stat command that will show more information. Command stat ~/.ssh on my machine display

File: ‘/home/sumon/.ssh’ -> ‘/home/sumon/ssh-keys/.ssh.personal’
  Size: 34          Blocks: 0          IO Block: 4096   symbolic link
Device: 801h/2049d  Inode: 25297409    Links: 1
Access: (0777/lrwxrwxrwx)  Uid: ( 1000/   sumon)   Gid: ( 1000/   sumon)
Access: 2017-09-26 16:41:18.985423932 +0600
Modify: 2017-09-25 15:48:07.880104043 +0600
Change: 2017-09-25 15:48:07.880104043 +0600
 Birth: -

Hope this may help someone.

Breaking a list into multiple columns in Latex

Using the multicol package and embedding your list in a multicols environment does what you want:

\documentclass{article}
\usepackage{multicol}

\begin{document}
\begin{multicols}{2}
\begin{enumerate}
    \item a
    \item b
    \item c
    \item d
    \item e
    \item f
\end{enumerate}
\end{multicols}
\end{document}

how to set radio option checked onload with jQuery

Say you had radio buttons like these, for example:

<input type='radio' name='gender' value='Male'>
<input type='radio' name='gender' value='Female'>

And you wanted to check the one with a value of "Male" onload if no radio is checked:

$(function() {
    var $radios = $('input:radio[name=gender]');
    if($radios.is(':checked') === false) {
        $radios.filter('[value=Male]').prop('checked', true);
    }
});

Extending the User model with custom fields in Django

There is an official recommendation on storing additional information about users. The Django Book also discusses this problem in section Profiles.

Select records from NOW() -1 Day

You're almost there: it's NOW() - INTERVAL 1 DAY

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

The extglob shell option gives you more powerful pattern matching in the command line.

You turn it on with shopt -s extglob, and turn it off with shopt -u extglob.

In your example, you would initially do:

$ shopt -s extglob
$ cp !(*Music*) /target_directory

The full available extended globbing operators are (excerpt from man bash):

If the extglob shell option is enabled using the shopt builtin, several extended pattern matching operators are recognized.A pattern-list is a list of one or more patterns separated by a |. Composite patterns may be formed using one or more of the following sub-patterns:

  • ?(pattern-list)
    Matches zero or one occurrence of the given patterns
  • *(pattern-list)
    Matches zero or more occurrences of the given patterns
  • +(pattern-list)
    Matches one or more occurrences of the given patterns
  • @(pattern-list)
    Matches one of the given patterns
  • !(pattern-list)
    Matches anything except one of the given patterns

So, for example, if you wanted to list all the files in the current directory that are not .c or .h files, you would do:

$ ls -d !(*@(.c|.h))

Of course, normal shell globing works, so the last example could also be written as:

$ ls -d !(*.[ch])

Switch case on type c#

Here's an option that stays as true I could make it to the OP's requirement to be able to switch on type. If you squint hard enough it almost looks like a real switch statement.

The calling code looks like this:

var @switch = this.Switch(new []
{
    this.Case<WebControl>(x => { /* WebControl code here */ }),
    this.Case<TextBox>(x => { /* TextBox code here */ }),
    this.Case<ComboBox>(x => { /* ComboBox code here */ }),
});

@switch(obj);

The x in each lambda above is strongly-typed. No casting required.

And to make this magic work you need these two methods:

private Action<object> Switch(params Func<object, Action>[] tests)
{
    return o =>
    {
        var @case = tests
            .Select(f => f(o))
            .FirstOrDefault(a => a != null);

        if (@case != null)
        {
            @case();
        }
    };
}

private Func<object, Action> Case<T>(Action<T> action)
{
    return o => o is T ? (Action)(() => action((T)o)) : (Action)null;
}

Almost brings tears to your eyes, right?

Nonetheless, it works. Enjoy.

mongodb how to get max value from collections

Folks you can see what the optimizer is doing by running a plan. The generic format of looking into a plan is from the MongoDB documentation . i.e. Cursor.plan(). If you really want to dig deeper you can do a cursor.plan(true) for more details.

Having said that if you have an index, your db.col.find().sort({"field":-1}).limit(1) will read one index entry - even if the index is default ascending and you wanted the max entry and one value from the collection.

In other words the suggestions from @yogesh is correct.

Thanks - Sumit

Tkinter: "Python may not be configured for Tk"

You need to install tkinter for python3.

On Fedora pip3 install tkinter --user returns Could not find a version that satisfies the requirement... so I have to command: dnf install python3-tkinter. This have solved my problem

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

PHP: How to use array_filter() to filter array keys?

PHP 5.6 introduced a third parameter to array_filter(), flag, that you can set to ARRAY_FILTER_USE_KEY to filter by key instead of value:

$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed  = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);

Clearly this isn't as elegant as array_intersect_key($my_array, array_flip($allowed)), but it does offer the additional flexibility of performing an arbitrary test against the key, e.g. $allowed could contain regex patterns instead of plain strings.

You can also use ARRAY_FILTER_USE_BOTH to have both the value and the key passed to your filter function. Here's a contrived example based upon the first, but note that I'd not recommend encoding filtering rules using $allowed this way:

$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed  = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
    $my_array,
    function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
        return isset($allowed[$key]) && (
            $allowed[$key] === true || $allowed[$key] === $val
        );
    },
    ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']

Convert JSONObject to Map

org.json.JSONObject#toMap() will do to work

Where is NuGet.Config file located in Visual Studio project?

There are multiple nuget packages read in the following order:

  1. First the NuGetDefaults.Config file. You will find this in %ProgramFiles(x86)%\NuGet\Config.
  2. The computer-level file.
  3. The user-level file. You will find this in %APPDATA%\NuGet\nuget.config.
  4. Any file named nuget.config beginning from the root of your drive up to the directory where nuget.exe is called.
  5. The config file you specify in the -configfile option when calling nuget.exe

You can find more information here.

How can I align the columns of tables in Bash?

function printTable()
{
    local -r delimiter="${1}"
    local -r data="$(removeEmptyLines "${2}")"

    if [[ "${delimiter}" != '' && "$(isEmptyString "${data}")" = 'false' ]]
    then
        local -r numberOfLines="$(wc -l <<< "${data}")"

        if [[ "${numberOfLines}" -gt '0' ]]
        then
            local table=''
            local i=1

            for ((i = 1; i <= "${numberOfLines}"; i = i + 1))
            do
                local line=''
                line="$(sed "${i}q;d" <<< "${data}")"

                local numberOfColumns='0'
                numberOfColumns="$(awk -F "${delimiter}" '{print NF}' <<< "${line}")"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi

                # Add Header Or Body

                table="${table}\n"

                local j=1

                for ((j = 1; j <= "${numberOfColumns}"; j = j + 1))
                do
                    table="${table}$(printf '#| %s' "$(cut -d "${delimiter}" -f "${j}" <<< "${line}")")"
                done

                table="${table}#|\n"

                # Add Line Delimiter

                if [[ "${i}" -eq '1' ]] || [[ "${numberOfLines}" -gt '1' && "${i}" -eq "${numberOfLines}" ]]
                then
                    table="${table}$(printf '%s#+' "$(repeatString '#+' "${numberOfColumns}")")"
                fi
            done

            if [[ "$(isEmptyString "${table}")" = 'false' ]]
            then
                echo -e "${table}" | column -s '#' -t | awk '/^\+/{gsub(" ", "-", $0)}1'
            fi
        fi
    fi
}

function removeEmptyLines()
{
    local -r content="${1}"

    echo -e "${content}" | sed '/^\s*$/d'
}

function repeatString()
{
    local -r string="${1}"
    local -r numberToRepeat="${2}"

    if [[ "${string}" != '' && "${numberToRepeat}" =~ ^[1-9][0-9]*$ ]]
    then
        local -r result="$(printf "%${numberToRepeat}s")"
        echo -e "${result// /${string}}"
    fi
}

function isEmptyString()
{
    local -r string="${1}"

    if [[ "$(trimString "${string}")" = '' ]]
    then
        echo 'true' && return 0
    fi

    echo 'false' && return 1
}

function trimString()
{
    local -r string="${1}"

    sed 's,^[[:blank:]]*,,' <<< "${string}" | sed 's,[[:blank:]]*$,,'
}

SAMPLE RUNS

$ cat data-1.txt
HEADER 1,HEADER 2,HEADER 3

$ printTable ',' "$(cat data-1.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+

$ cat data-2.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3

$ printTable ',' "$(cat data-2.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
+-----------+-----------+-----------+

$ cat data-3.txt
HEADER 1,HEADER 2,HEADER 3
data 1,data 2,data 3
data 4,data 5,data 6

$ printTable ',' "$(cat data-3.txt)"
+-----------+-----------+-----------+
| HEADER 1  | HEADER 2  | HEADER 3  |
+-----------+-----------+-----------+
| data 1    | data 2    | data 3    |
| data 4    | data 5    | data 6    |
+-----------+-----------+-----------+

$ cat data-4.txt
HEADER
data

$ printTable ',' "$(cat data-4.txt)"
+---------+
| HEADER  |
+---------+
| data    |
+---------+

$ cat data-5.txt
HEADER

data 1

data 2

$ printTable ',' "$(cat data-5.txt)"
+---------+
| HEADER  |
+---------+
| data 1  |
| data 2  |
+---------+

REF LIB at: https://github.com/gdbtek/linux-cookbooks/blob/master/libraries/util.bash

Java 8 lambda get and remove element from list

Although the thread is quite old, still thought to provide solution - using Java8.

Make the use of removeIf function. Time complexity is O(n)

producersProcedureActive.removeIf(producer -> producer.getPod().equals(pod));

API reference: removeIf docs

Assumption: producersProcedureActive is a List

NOTE: With this approach you won't be able to get the hold of the deleted item.

Converting a vector<int> to string

I usually do it this way...

#include <string>
#include <vector>

int main( int argc, char* argv[] )
{
    std::vector<char> vec;
    //... do something with vec
    std::string str(vec.begin(), vec.end());
    //... do something with str
    return 0;
}

ARM compilation error, VFP registers used by executable, not object file

This is guesswork, but you may need to supply some or all of the floating point related switches for the link stage as well.

Fast check for NaN in NumPy

Related to this is the question of how to find the first occurrence of NaN. This is the fastest way to handle that that I know of:

index = next((i for (i,n) in enumerate(iterable) if n!=n), None)

Swift Bridging Header import issue

I've also experienced this problem and sadly it is just a bug in the SDK + Xcode. I talked to an engineer at WWDC, about this and a few other problems I was having with CloudKit. These bugs will be addressed in the next seed of Xcode.

It's the fun part about using beta software.

Display A Popup Only Once Per User

The code to show only one time the popup (Bootstrap Modal in the case) :

modal.js

 $(document).ready(function() {
     if (Cookies('pop') == null) {
         $('#ModalIdName').modal('show');
         Cookies('pop', '365');
     }
 });

Here is the full code snipet for Rails :

Add the script above to your js repo (in Rails : app/javascript/packs)

In Rails we have a specific packing way for script, so :

  1. Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')

    /*!
     * JavaScript Cookie v2.2.0
     * https://github.com/js-cookie/js-cookie
     *
     * Copyright 2006, 2015 Klaus Hartl & Fagner Brack
     * Released under the MIT license
     */
    ;(function (factory) {
      var registeredInModuleLoader = false;
      if (typeof define === 'function' && define.amd) {
        define(factory);
        registeredInModul
     ...
    
  2. Add //= require js.cookie to application.js

It will works perfectly for 365 days!

Installing PIL with pip

These days, everyone uses Pillow, a friendly PIL fork, over PIL.

Instead of: sudo pip install pil

Do: sudo pip install pillow

$ sudo apt-get install python-imaging
$ sudo -H pip install pillow

Get key by value in dictionary

Heres a truly "Reversible Dictionary", Based upon Adam Acosta's solution, but enforcing val-to-key calls to be unique and easily return key from value:

from collections import UserDict


class ReversibleDict(UserDict):
    def __init__(self, enforce_unique=True, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.val_to_keys = {}
        self.check_val = self.check_unique if enforce_unique else lambda x: x

    def __setitem__(self, key, value):
        self.check_val(value)
        super().__setitem__(key, value)
        self.val_to_keys[value] = key

    def __call__(self, value):
        return self.val_to_keys[value]

    def check_unique(self, value):
        assert value not in self.val_to_keys, f"Non unique value '{value}'"
        return value

If you want to enforce uniqueness on dictionary values ensure to set enforce_unique=True. to get keys from values just do rev_dict(value), to call values from keys just do as usual dict['key'], here's an example of usage:

rev_dict = ReversibleDict(enforce_unique=True)
rev_dict["a"] = 1
rev_dict["b"] = 2
rev_dict["c"] = 3
print("full dictinoary is: ", rev_dict)
print("value for key 'b' is: ", rev_dict["b"])
print("key for value '2' is: ", rev_dict(2))
print("tring to set another key with the same value results in error: ")
rev_dict["d"] = 1

Playing MP4 files in Firefox using HTML5 video

I can confirm that mp4 just will not work in the video tag. No matter how much you try to mess with the type tag and the codec and the mime types from the server.

Crazy, because for the same exact video, on the same test page, the old embed tag for an mp4 works just fine in firefox. I spent all yesterday messing with this. Firefox is like IE all of a sudden, hours and hours of time, not billable. Yay.

Speaking of IE, it fails FAR MORE gracefully on this. When it can't match up the format it falls to the content between the tags, so it is possible to just put video around object around embed and everything works great. Firefox, nope, despite failing, it puts up the poster image (greyed out so that isn't even useful as a fallback) with an error message smack in the middle. So now the options are put in browser recognition code (meaning we've gained nothing on embedding videos in the last ten years) or ditch html5.

Setting timezone to UTC (0) in PHP

Is 'UTC' a valid timezone identifier on your system?

<?php
if (date_default_timezone_set('UTC')){
    echo "UTC is a valid time zone";
}else{
    echo "The system doesn't know WTFUTC.  Maybe try updating tzinfo with your package manager?";
}

Difference between File.separator and slash in paths

You use File.separator because someday your program might run on a platform developed in a far-off land, a land of strange things and stranger people, where horses cry and cows operate all the elevators. In this land, people have traditionally used the ":" character as a file separator, and so dutifully the JVM obeys their wishes.

Copy array by value

Here's a variant:

var arr1=['a', 'b', 'c'];
var arr2=eval(arr1.toSource());
arr2.push('d');
console.log('arr1: '+arr1+'\narr2: '+arr2);
/*
 *  arr1: a,b,c
 *  arr2: a,b,c,d
 */

How to export a Hive table into a CSV file?

You can not have a delimiter for query output,after generating the report (as you did).

you can change the delimiter to comma.

It comes with default delimiter \001 (inivisible character).

hadoop fs -cat /user/data/output/test/* |tr "\01" "," >>outputwithcomma.csv

check this also

How should the ViewModel close the form?

This is a simple and clean solution - You add an event to the ViewModel and instruct the Window to close itself when that event is fired.

For more details see my blog post, Close window from ViewModel.

XAML:

<Window
  x:Name="this"
  xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"  
  xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions">
  <i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding}" EventName="Closed">
      <ei:CallMethodAction
        TargetObject="{Binding ElementName=this}"
        MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
<Window>

ViewModel:

private ICommand _SaveAndCloseCommand;
public ICommand SaveAndCloseCommand
{
  get
  {
    return _SaveAndCloseCommand ??
      (_SaveAndCloseCommand = new DelegateCommand(SaveAndClose));
  }
}
private void SaveAndClose()
{
  Save();
  Close();
}

public event EventHandler Closed;
private void Close()
{
  if (Closed != null) Closed(this, EventArgs.Empty);
}

Note: The example uses Prism's DelegateCommand (see Prism: Commanding), but any ICommand implementation can be used for that matter.

You can use behaviors from this official package.

php $_POST array empty upon form submission

Make sure you use name="your_variable_name" in input tag.

I mistakenly use id="your_variable_name".

I spent much time to catch the bug.

How to view kafka message

Use the Kafka consumer provided by Kafka :

bin/kafka-console-consumer.sh --bootstrap-server BROKERS --topic TOPIC_NAME

It will display the messages as it will receive it. Add --from-beginning if you want to start from the beginning.

Python: convert string from UTF-8 to Latin-1

Instead of .encode('utf-8'), use .encode('latin-1').

Compiling with g++ using multiple cores

I'm not sure about g++, but if you're using GNU Make then "make -j N" (where N is the number of threads make can create) will allow make to run multple g++ jobs at the same time (so long as the files do not depend on each other).

How to detect when an Android app goes to the background and come back to the foreground

ProcessLifecycleOwner seems to be a promising solution also.

ProcessLifecycleOwner will dispatch ON_START, ON_RESUME events, as a first activity moves through these events. ON_PAUSE, ON_STOP, events will be dispatched with a delay after a last activity passed through them. This delay is long enough to guarantee that ProcessLifecycleOwner won't send any events if activities are destroyed and recreated due to a configuration change.

An implementation can be as simple as

class AppLifecycleListener : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    fun onMoveToForeground() { // app moved to foreground
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    fun onMoveToBackground() { // app moved to background
    }
}

// register observer
ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleListener())

According to source code, current delay value is 700ms.

Also using this feature requires the dependencies:

implementation "androidx.lifecycle:lifecycle-extensions:$lifecycleVersion"

Using 24 hour time in bootstrap timepicker

This works for me:

$(function () {
    $('#datetimepicker5').datetimepicker({
        use24hours: true,
        format: 'HH:mm'
    });
});

Important: It only worked at the point I used uppercase "H" as time format.

jQuery - checkbox enable/disable

Here's another sample using JQuery 1.10.2

$(".chkcc9").on('click', function() {
            $(this)
            .parents('table')
            .find('.group1') 
            .prop('checked', $(this).is(':checked')); 
});

HTML CSS Button Positioning

try changing that line-height change to a margin-top or padding-top change instead

#btnhome:active{
margin-top : 25px;
}

Edit: You could also try adding a span inside the button

<div id="header">           
    <button id="btnhome"><span>Home</span></button>          
    <button id="btnabout">About</button>
    <button id="btncontact">Contact</button>
    <button id="btnsup">Help Us</button>           
</div>

Then style that

#btnhome span:active { padding-top:25px;}

Passing an integer by reference in Python

Most cases where you would need to pass by reference are where you need to return more than one value back to the caller. A "best practice" is to use multiple return values, which is much easier to do in Python than in languages like Java.

Here's a simple example:

def RectToPolar(x, y):
    r = (x ** 2 + y ** 2) ** 0.5
    theta = math.atan2(y, x)
    return r, theta # return 2 things at once

r, theta = RectToPolar(3, 4) # assign 2 things at once

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

Javascript event handler with parameters

let obj = MyObject();

elem.someEvent( function(){ obj.func(param) } );

//calls the MyObject.func, passing the param.

How can I make a menubar fixed on the top while scrolling

to set a div at position fixed you can use

position:fixed
top:0;
left:0;
width:100%;
height:50px; /* change me */

How to position a CSS triangle using ::after?

Just add position:relative to the parent element .sidebar-resources-categories

http://jsfiddle.net/matthewabrman/5msuY/

explanation: the ::after elements position is based off of it's parent, in your example you probably had a parent element of the .sidebar-res... which had a set height, therefore it rendered just below it. Adding position relative to the .sidebar-res... makes the after elements move to 100% of it's parent which now becomes the .sidebar-res... because it's position is set to relative. I'm not sure how to explain it but it's expected behaviour.

read more on the subject: http://css-tricks.com/absolute-positioning-inside-relative-positioning/

VB.NET - If string contains "value1" or "value2"

You need this

If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
    'Code
End if

How can I verify if one list is a subset of another?

Pardon me if I am late to the party. ;)

To check if one set A is subset of set B, Python has A.issubset(B) and A <= B. It works on set only and works great BUT the complexity of internal implementation is unknown. Reference: https://docs.python.org/2/library/sets.html#set-objects

I came up with an algorithm to check if list A is a subset of list B with following remarks.

  • To reduce complexity of finding subset, I find it appropriate to sort both lists first before comparing elements to qualify for subset.
  • It helped me to break the loop when value of element of second list B[j] is greater than value of element of first list A[i].
  • last_index_j is used to start loop over list B where it last left off. It helps avoid starting comparisons from the start of list B (which is, as you might guess unnecessary, to start list B from index 0 in subsequent iterations.)
  • Complexity will be O(n ln n) each for sorting both lists and O(n) for checking for subset.
    O(n ln n) + O(n ln n) + O(n) = O(n ln n).

  • Code has lots of print statements to see what's going on at each iteration of the loop. These are meant for understanding only.

Check if one list is subset of another list

is_subset = True;

A = [9, 3, 11, 1, 7, 2];
B = [11, 4, 6, 2, 15, 1, 9, 8, 5, 3];

print(A, B);

# skip checking if list A has elements more than list B
if len(A) > len(B):
    is_subset = False;
else:
    # complexity of sorting using quicksort or merge sort: O(n ln n)
    # use best sorting algorithm available to minimize complexity
    A.sort();
    B.sort();

    print(A, B);

    # complexity: O(n^2)
    # for a in A:
    #   if a not in B:
    #       is_subset = False;
    #       break;

    # complexity: O(n)
    is_found = False;
    last_index_j = 0;

    for i in range(len(A)):
        for j in range(last_index_j, len(B)):
            is_found = False;

            print("i=" + str(i) + ", j=" + str(j) + ", " + str(A[i]) + "==" + str(B[j]) + "?");

            if B[j] <= A[i]:
                if A[i] == B[j]:
                    is_found = True;
                last_index_j = j;
            else:
                is_found = False;
                break;

            if is_found:
                print("Found: " + str(A[i]));
                last_index_j = last_index_j + 1;
                break;
            else:
                print("Not found: " + str(A[i]));

        if is_found == False:
            is_subset = False;
            break;

print("subset") if is_subset else print("not subset");

Output

[9, 3, 11, 1, 7, 2] [11, 4, 6, 2, 15, 1, 9, 8, 5, 3]
[1, 2, 3, 7, 9, 11] [1, 2, 3, 4, 5, 6, 8, 9, 11, 15]
i=0, j=0, 1==1?
Found: 1
i=1, j=1, 2==1?
Not found: 2
i=1, j=2, 2==2?
Found: 2
i=2, j=3, 3==3?
Found: 3
i=3, j=4, 7==4?
Not found: 7
i=3, j=5, 7==5?
Not found: 7
i=3, j=6, 7==6?
Not found: 7
i=3, j=7, 7==8?
not subset

Ansible Ignore errors in tasks and fail at end of the playbook if any tasks had errors

Use Fail module.

  1. Use ignore_errors with every task that you need to ignore in case of errors.
  2. Set a flag (say, result = false) whenever there is a failure in any task execution
  3. At the end of the playbook, check if flag is set, and depending on that, fail the execution
- fail: msg="The execution has failed because of errors."
  when: flag == "failed"

Update:

Use register to store the result of a task like you have shown in your example. Then, use a task like this:

- name: Set flag
  set_fact: flag = failed
  when: "'FAILED' in command_result.stderr"

Get a Windows Forms control by name in C#

this.Controls.Find(name, searchAllChildren) doesn't find ToolStripItem because ToolStripItem is not a Control

  using SWF = System.Windows.Forms;
  using NUF = NUnit.Framework;
  namespace workshop.findControlTest {
     [NUF.TestFixture]
     public class FormTest {
        [NUF.Test]public void Find_menu() {
           // == prepare ==
           var fileTool = new SWF.ToolStripMenuItem();
           fileTool.Name = "fileTool";
           fileTool.Text = "File";

           var menuStrip = new SWF.MenuStrip();
           menuStrip.Items.Add(fileTool);

           var form = new SWF.Form();
           form.Controls.Add(menuStrip);

           // == execute ==
           var ctrl = form.Controls.Find("fileTool", true);

           // == not found! ==
           NUF.Assert.That(ctrl.Length, NUF.Is.EqualTo(0)); 
        }
     }
  }

The program can't start because libgcc_s_dw2-1.dll is missing

Code::Blocks: add '-static' in settings->compiler->Linker settings->Other linker options.

How to use zIndex in react-native

Use elevation instead of zIndex for android devices

elevatedElement: {
  zIndex: 3, // works on ios
  elevation: 3, // works on android
}

This worked fine for me!

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

How to revert a merge commit that's already pushed to remote branch?

I found creating a reverse patch between two know end-points and applying that patch would work. This presumes that you have created snapshots (tags) off of your master branch or even a back up of your master branch say master_bk_01012017.

Say the code branch you merged into master was mycodebranch.

  1. Checkout master.
  2. Create a full binary reverse patch between master and your backup. git diff --binary master..master_bk_01012017 > ~/myrevert.patch
  3. Check your patch git apply --check myrevert.patch
  4. Apply patch with sign-off git am --signoff < myrevert.patch
  5. If you will need to bring in this code again once it is fixed, you will need to branch off the reverted master and checkout the fix branch git branch mycodebranch_fix git checkout mycodebranch_fix
  6. Here you need to find the SHA key for the revert and revert the revert git revert [SHA]
  7. Now you can use your mycodebranch_fix to fix the issues, commit and re-merge into master once done.

Returning value from called function in a shell script

You are working way too hard. Your entire script should be:

if mkdir "$lockdir" 2> /dev/null; then 
  echo lock acquired
else
  echo could not acquire lock >&2
fi

but even that is probably too verbose. I would code it:

mkdir "$lockdir" || exit 1

but the resulting error message is a bit obscure.

How to bind inverse boolean properties in WPF?

Following @Paul's answer, I wrote the following in the ViewModel:

public bool ShowAtView { get; set; }
public bool InvShowAtView { get { return !ShowAtView; } }

I hope having a snippet here will help someone, probably newbie as I am.
And if there's a mistake, please let me know!

BTW, I also agree with @heltonbiker comment - it's definitely the correct approach only if you don't have to use it more than 3 times...

Split string into list in jinja?

You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.

For your purpose, it would make most sense to define a custom filter, so you could for example do the following:

The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{  splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{  splitpart(1) }}

The filter function could then look like this:

def splitpart (value, index, char = ','):
    return value.split(char)[index]

An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.

Remove all line breaks from a long string of text

The problem with rstrip is that it does not work in all cases (as I myself have seen few). Instead you can use - text= text.replace("\n"," ") this will remove all new line \n with a space.

Thanks in advance guys for your upvotes.

How to convert an IPv4 address into a integer in C#?

I have encountered some problems with the described solutions, when facing IP Adresses with a very large value. The result would be, that the byte[0] * 16777216 thingy would overflow and become a negative int value. what fixed it for me, is the a simple type casting operation.

public static long ConvertIPToLong(string ipAddress)
{
    System.Net.IPAddress ip;

    if (System.Net.IPAddress.TryParse(ipAddress, out ip))
    {
        byte[] bytes = ip.GetAddressBytes();

        return
            16777216L * bytes[0] +
            65536 * bytes[1] +
            256 * bytes[2] +
            bytes[3]
            ;
    }
    else
        return 0;
}

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

Recently I had this same problem on windows 10 - after installing Hyper-V & other windows features like:

Windows Projected File System, Windows Sandbox, Windows Subsystem for Linux, Work Folders Client,

And it stopped working for me;(

  1. Step uninstall Hyper-V -check if ti stared to work for you - no in my case
  2. Step uninstall other windows features mentioned above! - I worked for me;) enter image description here

Extracting an attribute value with beautifulsoup

you can also use this :

import requests
from bs4 import BeautifulSoup
import csv

url = "http://58.68.130.147/"
r = requests.get(url)
data = r.text

soup = BeautifulSoup(data, "html.parser")
get_details = soup.find_all("input", attrs={"name":"stainfo"})

for val in get_details:
    get_val = val["value"]
    print(get_val)

Using Pairs or 2-tuples in Java

If you are looking for a built-in Java two-element tuple, try AbstractMap.SimpleEntry.

How to calculate Date difference in Hive

I would try this first

select * from employee where month(current_date)-3 = month(joining_date)

Error when trying to access XAMPP from a network

This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185

Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin"> to have the following code:

<Directory "/opt/lampp/phpmyadmin">
  AllowOverride AuthConfig Limit
  Order allow,deny
  Allow from all
  Require all granted
</Directory>

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

Bootstrap Datepicker - Months and Years Only

To view the months of the current year, and only the months, use this format - it only takes the months of that year. It can also be restricted so that a certain number of months is displayed.

<input class="form-control" id="txtDateMMyyyy"  autocomplete="off" required readonly/>

<script>
('#txtDateMMyyyy').datetimepicker({
    format: "mm/yyyy",
    startView: "year",
    minView: "year"
}).datetimepicker("setDate", new Date());
</script>

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

Select every Nth element in CSS

As the name implies, :nth-child() allows you to construct an arithmetic expression using the n variable in addition to constant numbers. You can perform addition (+), subtraction (-) and coefficient multiplication (an where a is an integer, including positive numbers, negative numbers and zero).

Here's how you would rewrite the above selector list:

div:nth-child(4n)

For an explanation on how these arithmetic expressions work, see my answer to this question, as well as the spec.

Note that this answer assumes that all of the child elements within the same parent element are of the same element type, div. If you have any other elements of different types such as h1 or p, you will need to use :nth-of-type() instead of :nth-child() to ensure you only count div elements:

<body>
  <h1></h1>
  <div>1</div>  <div>2</div>
  <div>3</div>  <div>4</div>
  <h2></h2>
  <div>5</div>  <div>6</div>
  <div>7</div>  <div>8</div>
  <h2></h2>
  <div>9</div>  <div>10</div>
  <div>11</div> <div>12</div>
  <h2></h2>
  <div>13</div> <div>14</div>
  <div>15</div> <div>16</div>
</body>

For everything else (classes, attributes, or any combination of these), where you're looking for the nth child that matches an arbitrary selector, you will not be able to do this with a pure CSS selector. See my answer to this question.


By the way, there's not much of a difference between 4n and 4n + 4 with regards to :nth-child(). If you use the n variable, it starts counting at 0. This is what each selector would match:

:nth-child(4n)

4(0) = 0
4(1) = 4
4(2) = 8
4(3) = 12
4(4) = 16
...

:nth-child(4n+4)

4(0) + 4 = 0  + 4 = 4
4(1) + 4 = 4  + 4 = 8
4(2) + 4 = 8  + 4 = 12
4(3) + 4 = 12 + 4 = 16
4(4) + 4 = 16 + 4 = 20
...

As you can see, both selectors will match the same elements as above. In this case, there is no difference.

python dataframe pandas drop column using int

If there are multiple columns with identical names, the solutions given here so far will remove all of the columns, which may not be what one is looking for. This may be the case if one is trying to remove duplicate columns except one instance. The example below clarifies this situation:

# make a df with duplicate columns 'x'
df = pd.DataFrame({'x': range(5) , 'x':range(5), 'y':range(6, 11)}, columns = ['x', 'x', 'y']) 


df
Out[495]: 
   x  x   y
0  0  0   6
1  1  1   7
2  2  2   8
3  3  3   9
4  4  4  10

# attempting to drop the first column according to the solution offered so far     
df.drop(df.columns[0], axis = 1) 
   y
0  6
1  7
2  8
3  9
4  10

As you can see, both Xs columns were dropped. Alternative solution:

column_numbers = [x for x in range(df.shape[1])]  # list of columns' integer indices

column_numbers .remove(0) #removing column integer index 0
df.iloc[:, column_numbers] #return all columns except the 0th column

   x  y
0  0  6
1  1  7
2  2  8
3  3  9
4  4  10

As you can see, this truly removed only the 0th column (first 'x').

How do I loop through a list by twos?

If you're using Python 2.6 or newer you can use the grouper recipe from the itertools module:

from itertools import izip_longest

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Call like this:

for item1, item2 in grouper(2, l):
    # Do something with item1 and item2

Note that in Python 3.x you should use zip_longest instead of izip_longest.

Closing Application with Exit button

this.close_Button = (Button)this.findViewById(R.id.close);
   this.close_Button.setOnClickListener(new OnClickListener() {
     @Override
     public void onClick(View v) {
        finish();
     }
  });

finish() - Call this when your activity is done and should be closed. The ActivityResult is propagated back to whoever launched you via onActivityResult().

MySQL select 10 random rows from 600K rows fast

If you have just one Read-Request

Combine the answer of @redsio with a temp-table (600K is not that much):

DROP TEMPORARY TABLE IF EXISTS tmp_randorder;
CREATE TABLE tmp_randorder (id int(11) not null auto_increment primary key, data_id int(11));
INSERT INTO tmp_randorder (data_id) select id from datatable;

And then take a version of @redsios Answer:

SELECT dt.*
FROM
       (SELECT (RAND() *
                     (SELECT MAX(id)
                        FROM tmp_randorder)) AS id)
        AS rnd
 INNER JOIN tmp_randorder rndo on rndo.id between rnd.id - 10 and rnd.id + 10
 INNER JOIN datatable AS dt on dt.id = rndo.data_id
 ORDER BY abs(rndo.id - rnd.id)
 LIMIT 1;

If the table is big, you can sieve on the first part:

INSERT INTO tmp_randorder (data_id) select id from datatable where rand() < 0.01;

If you have many read-requests

  1. Version: You could keep the table tmp_randorder persistent, call it datatable_idlist. Recreate that table in certain intervals (day, hour), since it also will get holes. If your table gets really big, you could also refill holes

    select l.data_id as whole from datatable_idlist l left join datatable dt on dt.id = l.data_id where dt.id is null;

  2. Version: Give your Dataset a random_sortorder column either directly in datatable or in a persistent extra table datatable_sortorder. Index that column. Generate a Random-Value in your Application (I'll call it $rand).

    select l.*
    from datatable l 
    order by abs(random_sortorder - $rand) desc 
    limit 1;
    

This solution discriminates the 'edge rows' with the highest and the lowest random_sortorder, so rearrange them in intervals (once a day).

Does Android support near real time push notification?

XMPP is a good solution. I have used it for a push enabled, realtime, Android application. XMPP is powerful, highly extensible and easy to integrate and use.

There are loads of free XMPP servers (though out of courtesy you shouldn't abuse them) and there are open source servers you can run on one of your own boxes. OpenFire is an excellent choice.

The library you want isn't Smack as noted above, it's aSmack. But note, this is a build environment - you will have to build the library.

This is a calculation I did on battery life impact of an XMPP solution:

The Android client must maintain a persistent TCP connection by waking up periodically to send a heartbeat to the XMPP server.
This clearly imposes a cost in terms of power usage. An estimate of this cost is provided below:

  • Using a 1400mAh battery (as supplied in the Nexus One and HTC Desire)
  • An idle device, connected to an 3G network, uses approximately 5mA
  • The wake-up, heartbeat, sleep cycle occurs every 5 minutes, takes three seconds to complete and uses 300mA
  • The cost in battery usage per hour is therefore:
    • 36 seconds 300mA = 3mAh sending heartbeat
    • 3600 seconds 5mA = 5mAh at idle
    • 4:95 + 3 = 7:95mAh combined
  • A 1400mAh battery lasts approximately 11.6 days at idle and 7.3 days when running the application, which represents an approximate 37% reduction in battery life.
  • However, a reduction in battery life of 37% represents the absolute worst case in practice given that devices are rarely completely idle.

Request UAC elevation from within a Python script?

Just adding this answer in case others are directed here by Google Search as I was. I used the elevate module in my Python script and the script executed with Administrator Privileges in Windows 10.

https://pypi.org/project/elevate/

How do I do top 1 in Oracle?

I had the same issue, and I can fix this with this solution:

select a.*, rownum 
from (select Fname from MyTbl order by Fname DESC) a
where
rownum = 1

You can order your result before to have the first value on top.

Good luck

What's the difference between size_t and int in C++?

From the friendly Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

Also, check Why size_t matters

How do I fix a NoSuchMethodError?

The problem in my case was having two versions of the same library in the build path. The older version of the library didn't have the function, and newer one did.

curl.h no such file or directory

To those who use centos and have stumbled upon this post :

 $ yum install curl-devel

and when compiling your program example.cpp, link to the curl library:

 $ g++ example.cpp -lcurl -o example

"-o example" creates the executable example instead of the default a.out.

The next line runs example:

 $ ./example

How to delete a file via PHP?

I know this question is a bit old, but this is something simple that works for me very well to delete images off my project I'm working on.

unlink(dirname(__FILE__) . "/img/tasks/" . 'image.jpg');

The dirname(__FILE__) section prints out the base path to your project. The /img/tasks/ are two folders down from my base path. And finally, there's my image I want to delete which you can make into anything you need to.

With this I have not had any problem getting to my files on my server and deleting them.

DTO and DAO concepts and MVC

DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

  • DTO should only contain private fields for your data, getters, setters, and constructors.
  • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

Here is an example of how the DAO and DTO interfaces would look like:

interface PersonDTO {
    String getName();
    void setName(String name);
    //.....
}

interface PersonDAO {
    PersonDTO findById(long id);
    void save(PersonDTO person);
    //.....
}

The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.

As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.

JPA 2.0, Criteria API, Subqueries, In Expressions

CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
CriteriaQuery<Employee> criteriaQuery = criteriaBuilder.createQuery(Employee.class);
Root<Employee> empleoyeeRoot = criteriaQuery.from(Employee.class);

Subquery<Project> projectSubquery = criteriaQuery.subquery(Project.class);
Root<Project> projectRoot = projectSubquery.from(Project.class);
projectSubquery.select(projectRoot);

Expression<String> stringExpression = empleoyeeRoot.get(Employee_.ID);
Predicate predicateIn = stringExpression.in(projectSubquery);

criteriaQuery.select(criteriaBuilder.count(empleoyeeRoot)).where(predicateIn);

How can I convert a string to boolean in JavaScript?

To evaluate both boolean and boolean-like strings like boolean I used this easy formula:

var trueOrStringTrue = (trueOrStringTrue === true) || (trueOrStringTrue === 'true');

As is apparent, it will return true for both true and 'true'. Everything else returns false.

How to display an alert box from C# in ASP.NET?

You can create a global method to show message(alert) in your web form application.

public static class PageUtility
{
    public static void MessageBox(System.Web.UI.Page page,string strMsg)
    {
        //+ character added after strMsg "')"
        ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "alertMessage", "alert('" + strMsg + "')", true);

    }
}

webform.aspx

protected void btnSave_Click(object sender, EventArgs e)
{
    PageUtility.MessageBox(this, "Success !");
}

jQuery - prevent default, then continue default

      $('#myform').on('submit',function(event){
        // block form submit event
        event.preventDefault();

        // Do some stuff here
        ...

        // Continue the form submit
        event.currentTarget.submit();
  });

Why would a JavaScript variable start with a dollar sign?

I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.

The accepted answer gives this example:

var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself

But that doesn't really illustrate it well. Even without the $, we would still have two different variable names here, email and email_field. That's plenty good right there. Why would we need to throw a $ into one of the names when we already have two different names?

Actually, I wouldn't have used email_field here for two reasons: names_with_underscores are not idiomatic JavaScript, and field doesn't really make sense for a DOM element. But I did follow the same idea.

I tried a few different things, among them something very similar to the example:

var email = $("#email"), emailElement = $("#email")[0];
// Now email is a jQuery object and emailElement is the first/only DOM element in it

(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of id selectors, so in those cases there was a 1:1 correspondence.)

I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:

// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
    var emailJQ = $(email);
    // Now email is the DOM element and emailJQ is a jQuery object for it
}

Well that's a little confusing! In one of my bits of code, email is the jQuery object and emailElement is the DOM element, but in the other, email is the DOM element and emailJQ is the jQuery object.

There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides email, emailElement, and emailJQ, I kept trying other variations too.

Then I noticed a common pattern:

var email = $("#email");
var emailJQ = $(email);

Since JavaScript treats $ as simply another letter for names, and since I always got a jQuery object back from a $(whatever) call, the pattern finally dawned on me. I could take a $(...) call and just remove some characters, and it would come up with a pretty nice name:

$("#email")
$(email)

Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:

$email

That's when I realized I didn't need to make up a convention like emailElement or emailJQ. There was already a nice convention staring at me: take some characters out of a $(whatever) call and it turns into $whatever.

var $email = $("#email"), email = $email[0];
// $email is the jQuery object and email is the DOM object

and:

// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
    var $email = $(email);
    // $email is the jQuery object and email is the DOM object
    // Same names as in the code above. Yay!
}

So I didn't have to make up two different names all the time but could just use the same name with or without a $ prefix. And the $ prefix was a nice reminder that I was dealing with a jQuery object:

$('#email').click( ... );

or:

var $email = $('#email');
// Maybe do some other stuff with $email here
$email.click( ... );

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

On Windows only, you can get the motherboard ID using WMI, through a COM bridge such as JACOB.

Example:

import java.util.Enumeration;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class Test {
    public static void main(String[] args) {
        ComThread.InitMTA();
        try {
            ActiveXComponent wmi = new ActiveXComponent("winmgmts:\\\\.");
            Variant instances = wmi.invoke("InstancesOf", "Win32_BaseBoard");
            Enumeration<Variant> en = new EnumVariant(instances.getDispatch());
            while (en.hasMoreElements())
            {
                ActiveXComponent bb = new ActiveXComponent(en.nextElement().getDispatch());
                System.out.println(bb.getPropertyAsString("SerialNumber"));
                break;
            }
        } finally {
            ComThread.Release();
        }
    }
}

And if you choose to use the MAC address to identify the machine, you can use WMI to determine whether an interface is connected via USB (if you want to exclude USB adapters.)

It's also possible to get a hard drive ID via WMI but this is unreliable.

Change One Cell's Data in mysql

You probably need to specify which rows you want to update...

UPDATE 
    mytable
SET 
    column1 = value1,
    column2 = value2
WHERE 
    key_value = some_value;

Catching multiple exception types in one catch block

Update:

As of PHP 7.1, this is available.

The syntax is:

try
{
    // Some code...
}
catch(AError | BError $e)
{
    // Handle exceptions
}
catch(Exception $e)
{
    // Handle the general case
}

Docs: https://www.php.net/manual/en/language.exceptions.php#example-294

RFC: https://wiki.php.net/rfc/multiple-catch

Commit: https://github.com/php/php-src/commit/0aed2cc2a440e7be17552cc669d71fdd24d1204a


For PHP before 7.1:

Despite what these other answers say, you can catch AError and BError in the same block (it is somewhat easier if you are the one defining the exceptions). Even given that there are exceptions you want to "fall through", you should still be able to define a hierarchy to match your needs.

abstract class MyExceptions extends Exception {}

abstract class LetterError extends MyExceptions {}

class AError extends LetterError {}

class BError extends LetterError {}

Then:

catch(LetterError $e){
    //voodoo
}

As you can see here and here, even the SPL default exceptions have a hierarchy you can leverage. Additionally, as stated in the PHP Manual:

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block.

This means you could also have

class CError extends LetterError {}

which you need to handle differently than AError or BError, so your catch statement would look like this:

catch(CError $e){
    //voodoo
}
catch(LetterError $e){
    //voodoo
}

If you had the case where there were twenty or more exceptions that legitimately belonged under the same superclass, and you needed to handle five (or whatever large-ish group) of them one way and the rest the other, you can STILL do this.

interface Group1 {}

class AError extends LetterError implements Group1 {}

class BError extends LetterError implements Group1 {}

And then:

catch (Group1 $e) {}

Using OOP when it comes to exceptions is very powerful. Using things like get_class or instanceof are hacks, and should be avoided if possible.

Another solution I would like to add is putting the exception handling functionality in its own method.

You could have

function handleExceptionMethod1(Exception $e)
{
    //voodoo
}

function handleExceptionMethod2(Exception $e)
{
    //voodoo
}

Assuming there is absolutely no way you can control exception class hierarchies or interfaces (and there almost always will be a way), you can do the following:

try
{
    stuff()
}
catch(ExceptionA $e)
{
    $this->handleExceptionMethod1($e);
}
catch(ExceptionB $e)
{
    $this->handleExceptionMethod1($e);
}
catch(ExceptionC $e)
{
    $this->handleExceptionMethod1($e);
}
catch(Exception $e)
{
    $this->handleExceptionMethod2($e);
}

In this way, you are still have a only single code location you have to modify if your exception handling mechanism needs to change, and you are working within the general constructs of OOP.

Invoking a PHP script from a MySQL trigger

A friend and I have figured out how to call Bernardo Damele's sys_eval UDF, but the solution isn't as elegant as I'd like. Here's what we did:

  1. Since we're using Windows, we had to compile the UDF library for Windows using Roland Bouman's instructions and install them on our MySQL server.
  2. We created a stored procedure that calls sys_eval.
  3. We created a trigger that calls the stored procedure.

Stored Procedure code:

DELIMITER $$
CREATE PROCEDURE udfwrapper_sp
(p1   DOUBLE,
 p2   DOUBLE,
 p3 BIGINT)
BEGIN
 DECLARE cmd CHAR(255);
 DECLARE result CHAR(255);
 SET cmd = CONCAT('C:/xampp/php/php.exe -f "C:/xampp/htdocs/phpFile.php" ', p1, ' ', p2, ' ', p3);
 SET result = sys_eval(cmd);
END$$;

Trigger code:

CREATE TRIGGER udfwrapper_trigger AFTER INSERT ON sometable
FOR EACH ROW
CALL udfwrapper_sp(NEW.Column1, NEW.Column2, NEW.Column3);

I'm not thrilled about having the stored procedure, and I don't know if it creates extra overhead, but it does work. Each time a row is added to sometable, the trigger fires.

What does "hashable" mean in Python?

In python it means that the object can be members of sets in order to return a index. That is, they have unique identity/ id.

for example, in python 3.3:

the data structure Lists are not hashable but the data structure Tuples are hashable.

What's the difference between faking, mocking, and stubbing?

If you are familiar with Arrange-Act-Assert, then one way of explaining the difference between stub and mock that might be useful for you, is that stubs belong to the arrange section, as they are for arranging input state, and mocks belong to the assert section as they are for asserting results against.

Dummies don't do anything. They are just for filling up parameter lists, so that you don't get undefined or null errors. They also exist to satisfy the type checker in strictly typed languages, so that you can be allowed to compile and run.

How to solve npm install throwing fsevents warning on non-MAC OS?

package.json counts with a optionalDependencies key. NPM on Optional Dependencies.

You can add fsevents to this object and if you find yourself installing packages in a different platform than MacOS, fsevents will be skipped by either yarn or npm.

"optionalDependencies": {
  "fsevents": "2.1.2"
},

You will find a message like the following in the installation log:

info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
info [email protected]: The platform "linux" is incompatible with this module.
info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.

Hope it helps!

VBA to copy a file from one directory to another

Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:

Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")

Then you could use

Call fso.CopyFile(source, destination[, overwrite] )

where source and destination are the full names (including paths) of the file.

See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method

How do check if a PHP session is empty?

you are looking for PHP’s empty() function

How to change XAMPP apache server port?

If the XAMPP server is running for the moment, stop XAMPP server.

Follow these steps to change the port number.

Open the file in following location.

[XAMPP Installation Folder]/apache/conf/httpd.conf

Open the httpd.conf file and search for the String:

Listen 80

This is the port number used by XAMMP.

Then search for the string ServerName and update the Port Number which you entered earlier for Listen

Now save and re-start XAMPP server.

Interactive shell using Docker Compose

You need to include the following lines in your docker-compose.yml:

version: "3"
services:
  app:
    image: app:1.2.3
    stdin_open: true # docker run -i
    tty: true        # docker run -t

The first corresponds to -i in docker run and the second to -t.

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

How to POST raw whole JSON in the body of a Retrofit request?

you need to set @Body in interface

@Headers({ "Content-Type: application/json;charset=UTF-8"})
    @POST("Auth/Login")
    Call<ApiResponse> loginWithPhone(@Body HashMap<String, String> fields);

To pass the raw body to retrofit just use:

 HashMap<String,String> SendData =new HashMap<>();
        SendData.put("countryCode",ccode);
        SendData.put("phoneNumber",phone);

        Call<ApiResponse>call = serviceInterface.loginWithPhone(SendData);

this works for me:

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.

What's the difference between the 'ref' and 'out' keywords?

ref means that the value in the ref parameter is already set, the method can read and modify it. Using the ref keyword is the same as saying that the caller is responsible for initializing the value of the parameter.


out tells the compiler that the initialization of object is the responsibility of the function, the function has to assign to the out parameter. It's not allowed to leave it unassigned.

Python: OSError: [Errno 2] No such file or directory: ''

I had this error because I was providing a string of arguments to subprocess.call instead of an array of arguments. To prevent this, use shlex.split:

import shlex, subprocess
command_line = "ls -a"
args = shlex.split(command_line)
p = subprocess.Popen(args)

Add column to dataframe with constant value

Summing up what the others have suggested, and adding a third way

You can:

where the argument loc ( 0 <= loc <= len(columns) ) allows you to insert the column where you want.

'loc' gives you the index that your column will be at after the insertion. For example, the code above inserts the column Name as the 0-th column, i.e. it will be inserted before the first column, becoming the new first column. (Indexing starts from 0).

All these methods allow you to add a new column from a Series as well (just substitute the 'abc' default argument above with the series).

How to prevent default event handling in an onclick method?

Try this (but please use buttons for such cases if you don't have a valid href value for graceful degradation)

<a href="#" onclick="callmymethod(24); return false;">Call</a>

How to insert a file in MySQL database?

The BLOB datatype is best for storing files.

Count occurrences of a char in a string using Bash

awk is very cool, but why not keep it simple?

num=$(echo $var | grep -o "," | wc -l)

Best way to store passwords in MYSQL database

best to use crypt for password storing in DB

example code :

$crypted_pass = crypt($password);

//$pass_from_login is the user entered password
//$crypted_pass is the encryption
if(crypt($pass_from_login,$crypted_pass)) == $crypted_pass)
{
   echo("hello user!")
}

documentation :

http://www.php.net/manual/en/function.crypt.php

How do I show the schema of a table in a MySQL database?

SHOW CREATE TABLE yourTable;

or

SHOW COLUMNS FROM yourTable;

What evaluates to True/False in R?

This is documented on ?logical. The pertinent section of which is:

Details:

     ‘TRUE’ and ‘FALSE’ are reserved words denoting logical constants
     in the R language, whereas ‘T’ and ‘F’ are global variables whose
     initial values set to these.  All four are ‘logical(1)’ vectors.

     Logical vectors are coerced to integer vectors in contexts where a
     numerical value is required, with ‘TRUE’ being mapped to ‘1L’,
     ‘FALSE’ to ‘0L’ and ‘NA’ to ‘NA_integer_’.

The second paragraph there explains the behaviour you are seeing, namely 5 == 1L and 5 == 0L respectively, which should both return FALSE, where as 1 == 1L and 0 == 0L should be TRUE for 1 == TRUE and 0 == FALSE respectively. I believe these are not testing what you want them to test; the comparison is on the basis of the numerical representation of TRUE and FALSE in R, i.e. what numeric values they take when coerced to numeric.

However, only TRUE is guaranteed to the be TRUE:

> isTRUE(TRUE)
[1] TRUE
> isTRUE(1)
[1] FALSE
> isTRUE(T)
[1] TRUE
> T <- 2
> isTRUE(T)
[1] FALSE

isTRUE is a wrapper for identical(x, TRUE), and from ?isTRUE we note:

Details:
....

     ‘isTRUE(x)’ is an abbreviation of ‘identical(TRUE, x)’, and so is
     true if and only if ‘x’ is a length-one logical vector whose only
     element is ‘TRUE’ and which has no attributes (not even names).

So by the same virtue, only FALSE is guaranteed to be exactly equal to FALSE.

> identical(F, FALSE)
[1] TRUE
> identical(0, FALSE)
[1] FALSE
> F <- "hello"
> identical(F, FALSE)
[1] FALSE

If this concerns you, always use isTRUE() or identical(x, FALSE) to check for equivalence with TRUE and FALSE respectively. == is not doing what you think it is.

How do I load an org.w3c.dom.Document from XML in a string?

To manipulate XML in Java, I always tend to use the Transformer API:

import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.stream.StreamSource;

public static Document loadXMLFrom(String xml) throws TransformerException {
    Source source = new StreamSource(new StringReader(xml));
    DOMResult result = new DOMResult();
    TransformerFactory.newInstance().newTransformer().transform(source , result);
    return (Document) result.getNode();
}   

How do I combine 2 javascript variables into a string

ES6 introduce template strings for concatenation. Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:

// Simple string substitution
let name = "Brendan";
console.log(`Yo, ${name}!`);

// => "Yo, Brendan!"

var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`);

//=> JavaScript first appeared 20 years ago. Crazy!

How to allow http content within an iframe on a https site

Using Google as the SSL proxy is not working currently,

Why?

If you opened any page from google, you will find there is a x-frame-options field in the header. Google response header

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe> or <object>. Sites can use this to avoid clickjacking attacks, by ensuring that their content is not embedded into other sites.

(Quote from MDN)

One of the solution

Below is my work around for this problem:

Upload the content to AWS S3, and it will create a https link for the resource.
Notice: set the permission to the html file for allowing everyone view it.

After that, we can using it as the src of iframe in the https websites. AWS

Procedure expects parameter which was not supplied

In addition to the other answers here, if you've forgotten to put:

cmd.CommandType = CommandType.StoredProcedure;

Then you will also get this error.

Select from where field not equal to Mysql Php

$sqlquery = "SELECT field1, field2 FROM table WHERE columnA <> 'x' AND columbB <> 'y'";

I'd suggest using the diamond operator (<>) in favor of != as the first one is valid SQL and the second one is a MySQL addition.

How to get public directory?

I know this is a little late, but if someone else comes across this looking, you can now use public_path(); in Laravel 4, it has been added to the helper.php file in the support folder see here.

Disable asp.net button after click to prevent double clicking

This works with a regular html button.

    <input id="Button1"
    onclick="this.disabled='true';" type="button"
    value="Submit" name="Button1"
    runat="server" onserverclick="Button1_Click">

The button is disabled until the postback is finished, preventing double clicking.

What is the use of adding a null key or value to a HashMap in Java?

A null key can also be helpful when the map stores data for UI selections where the map key represents a bean field.

A corresponding null field value would for example be represented as "(please select)" in the UI selection.

How to unmount a busy device

Check out umount2:

Linux 2.1.116 added the umount2() system call, which, like umount(), unmounts a target, but allows additional flags controlling the behaviour of the operation:

MNT_FORCE (since Linux 2.1.116) Force unmount even if busy. (Only for NFS mounts.) MNT_DETACH (since Linux 2.4.11) Perform a lazy unmount: make the mount point unavailable for new accesses, and actually perform the unmount when the mount point ceases to be busy. MNT_EXPIRE (since Linux 2.6.8) Mark the mount point as expired. If a mount point is not currently in use, then an initial call to umount2() with this flag fails with the error EAGAIN, but marks the mount point as expired. The mount point remains expired as long as it isn't accessed by any process. A second umount2() call specifying MNT_EXPIRE unmounts an expired mount point. This flag cannot be specified with either MNT_FORCE or MNT_DETACH. Return Value

On success, zero is returned. On error, -1 is returned, and errno is set appropriately.

java.lang.ClassNotFoundException on working app

In my case, the icon of the app was causing the error:

<application
    android:name="com.test.MyApp"
    android:icon="@drawable/myicon"

Why? Because I put the icon only in the folder "drawable", and I'm using a high resolution testing device, so it looks in the folder "drawable-hdpi" for the icon. The default behaviour for everything else is use the icons from "drawable" if they aren't in "drawable-hdpi". But for the launching icon this doesn't seem to be valid.

So the solution is to put a copy of the icon (with the same name, of course) in "drawable-hdpi" (or whichever supported resolutions the devices have).

ASP.NET email validator regex

Apart from the client side validation with a Validator, I also recommend doing server side validation as well.

bool isValidEmail(string input)
{
    try
    {
        var email = new System.Net.Mail.MailAddress(input);
        return true;
    }
    catch
    {
        return false;
    }
}

What is the difference between tree depth and height?

The answer by Daniel A.A. Pelsmaeker and Yesh analogy is excellent. I would like to add a bit more from hackerrank tutorial. Hope it helps a bit too.

  • The depth(or level) of a node is its distance(i.e. no of edges) from tree's root node.
  • The height is number of edges between root node and furthest leaf.
  • height(node) = 1 + max(height(node.leftSubtree),height(node.rightSubtree)).
    Keep in mind the following points before reading the example ahead.
  • Any node has a height of 1.
  • Height of empty subtree is -1.
  • Height of single element tree or leaf node is 0.
    Example to calculate height of tree

Add to integers in a list

If you try appending the number like, say listName.append(4) , this will append 4 at last. But if you are trying to take <int> and then append it as, num = 4 followed by listName.append(num), this will give you an error as 'num' is of <int> type and listName is of type <list>. So do type cast int(num) before appending it.

How to use basic authorization in PHP curl

$headers = array(
    'Authorization: Basic '. base64_encode($username.':'.$password),
);
...
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

Angular2 set value for formGroup

To set all FormGroup values use, setValue:

this.myFormGroup.setValue({
  formControlName1: myValue1, 
  formControlName2: myValue2
});

To set only some values, use patchValue:

this.myFormGroup.patchValue({
  formControlName1: myValue1, 
  // formControlName2: myValue2 (can be omitted)
});

With this second technique, not all values need to be supplied and fields whos values were not set will not be affected.

Drop all tables command

rm db/development.sqlite3

Order of items in classes: Fields, Properties, Constructors, Methods

I don't know about a language or industry standard, but I tend to put things in this order with each section wrapped in a #region:

using Statements

Namespace

Class

Private members

Public properties

Constructors

Public methods

Private methods

How to write to a CSV line by line?

You could just write to the file as you would write any normal file.

with open('csvfile.csv','wb') as file:
    for l in text:
        file.write(l)
        file.write('\n')

If just in case, it is a list of lists, you could directly use built-in csv module

import csv

with open("csvfile.csv", "wb") as file:
    writer = csv.writer(file)
    writer.writerows(text)

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

In an AngularJS directive the scope allows you to access the data in the attributes of the element to which the directive is applied.

This is illustrated best with an example:

<div my-customer name="Customer XYZ"></div>

and the directive definition:

angular.module('myModule', [])
.directive('myCustomer', function() {
  return {
    restrict: 'E',
    scope: {
      customerName: '@name'
    },
    controllerAs: 'vm',
    bindToController: true,
    controller: ['$http', function($http) {
      var vm = this;

      vm.doStuff = function(pane) {
        console.log(vm.customerName);
      };
    }],
    link: function(scope, element, attrs) {
      console.log(scope.customerName);
    }
  };
});

When the scope property is used the directive is in the so called "isolated scope" mode, meaning it can not directly access the scope of the parent controller.

In very simple terms, the meaning of the binding symbols is:

someObject: '=' (two-way data binding)

someString: '@' (passed directly or through interpolation with double curly braces notation {{}})

someExpression: '&' (e.g. hideDialog())

This information is present in the AngularJS directive documentation page, although somewhat spread throughout the page.

The symbol > is not part of the syntax.

However, < does exist as part of the AngularJS component bindings and means one way binding.

Python: "TypeError: __str__ returned non-string" but still prints to output?

You can also surround the output with str(). I had this same problem because my model had the following (as a simplified example):

def __str__(self):
    return self.pressid

Where pressid was an IntegerField type object. Django (and python in general) expects a string for a str function, so returning an integer causes this error to be thrown.

def __str__(self):
    return str(self.pressid)

That solved the problems I was encountering on the Django management side of the house. Hope it helps with yours.

Could not install packages due to a "Environment error :[error 13]: permission denied : 'usr/local/bin/f2py'"

On Windows this has worked for me. From the command line, specify the path to the exe for Python: & "C:/Program Files (x86)/Python37-32/python.exe" -m pip install --upgrade pip --user

How can I write variables inside the tasks file in ansible

I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.

Just move the var inside the "name" block:

- name: Download apache
  vars:
    url: czxcxz
  shell: wget {{url}} 

LIKE vs CONTAINS on SQL Server

I think that CONTAINS took longer and used Merge because you had a dash("-") in your query adventure-works.com.

The dash is a break word so the CONTAINS searched the full-text index for adventure and than it searched for works.com and merged the results.

Difference between malloc and calloc?

One often-overlooked advantage of calloc is that (conformant implementations of) it will help protect you against integer overflow vulnerabilities. Compare:

size_t count = get_int32(file);
struct foo *bar = malloc(count * sizeof *bar);

vs.

size_t count = get_int32(file);
struct foo *bar = calloc(count, sizeof *bar);

The former could result in a tiny allocation and subsequent buffer overflows, if count is greater than SIZE_MAX/sizeof *bar. The latter will automatically fail in this case since an object that large cannot be created.

Of course you may have to be on the lookout for non-conformant implementations which simply ignore the possibility of overflow... If this is a concern on platforms you target, you'll have to do a manual test for overflow anyway.

Where does application data file actually stored on android device?

This is a simple way to identify the application related storage paths of a particular app.

Steps:

  1. Have the android device connected to your mac or android emulator open
  2. Open the terminal
  3. adb shell
  4. find .

The "find ." command will list all the files with their paths in the terminal.

./apex/com.android.media.swcodec
./apex/com.android.media.swcodec/etc
./apex/com.android.media.swcodec/etc/init.rc
./apex/com.android.media.swcodec/etc/seccomp_policy
./apex/com.android.media.swcodec/etc/seccomp_policy/mediaswcodec.policy
./apex/com.android.media.swcodec/etc/ld.config.txt
./apex/com.android.media.swcodec/etc/media_codecs.xml
./apex/com.android.media.swcodec/apex_manifest.json
./apex/com.android.media.swcodec/lib
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_common.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libcodec2_soft_vorbisdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263dec.so
./apex/com.android.media.swcodec/lib/libhidltransport.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_h263enc.so
./apex/com.android.media.swcodec/lib/libcodec2_vndk.so
./apex/com.android.media.swcodec/lib/[email protected]
./apex/com.android.media.swcodec/lib/libmedia_codecserviceregistrant.so
./apex/com.android.media.swcodec/lib/libhidlbase.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_aacdec.so
./apex/com.android.media.swcodec/lib/libcodec2_soft_vp9dec.so
.....

After this, just search for your app with the bundle identifier and you can use adb pull command to download the files to your local directory.

What's your favorite "programmer" cartoon?

I think the IT consultant's image is the best:

Reasons why people who work with computers have a lot of spare time

(linking because the picture's pretty big)

Is there a way to cache GitHub credentials for pushing commits?

If you are using osxkeychain and had a token expire and want to update it, follow these steps:

Run in terminal, then press enter twice.

git credential-osxkeychain erase
 host=github.com
 protocol=https

Now you should be prompted for a username/password. However sometimes it seems this does not 'take' and you have to keep re-entering.

If so, restart your computer. Now the next time you run a git command and enter your username/password, it will be saved.

What is the difference between C# and .NET?

In addition to what Andrew said, it is worth noting that:

  • .NET isn't just a library, but also a runtime for executing applications.
  • The knowledge of C# implies some knowledge of .NET (because the C# object model corresponds to the .NET object model and you can do something interesting in C# just by using .NET libraries). The opposite isn't necessarily true as you can use other languages to write .NET applications.

The distinction between a language, a runtime, and a library is more strict in .NET/C# than for example in C++, where the language specification also includes some basic library functions. The C# specification says only a very little about the environment (basically, that it should contain some types such as int, but that's more or less all).

Parameter in like clause JPQL

  1. Use below JPQL query.
select i from Instructor i where i.address LIKE CONCAT('%',:address ,'%')");
  1. Use below Criteria code for the same:
@Test
public void findAllHavingAddressLike() {
    CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
    CriteriaQuery<Instructor> cq = cb.createQuery(Instructor.class);
    Root<Instructor> root = cq.from(Instructor.class);
    printResultList(cq.select(root).where(
        cb.like(root.get(Instructor_.address), "%#1074%")));
}

How to reload or re-render the entire page using AngularJS

I've had a hard fight with this problem for months, and the only solution that worked for me is this:

var landingUrl = "http://www.ytopic.es"; //URL complete
$window.location.href = landingUrl;

How to install multiple python packages at once using pip

You can use the following steps:

Step 1: Create a requirements.txt with list of packages to be installed. If you want to copy packages in a particular environment, do this

pip freeze >> requirements.txt

else store package names in a file named requirements.txt

Step 2: Execute pip command with this file

pip install -r requirements.txt

Eloquent ->first() if ->exists()

(ps - I couldn't comment) I think your best bet is something like you've done, or similar to:

$user = User::where('mobile', Input::get('mobile'));
$user->exists() and $user = $user->first();

Oh, also: count() instead if exists but this could be something used after get.

What are naming conventions for MongoDB?

Until we get SERVER-863 keeping the field names as short as possible is advisable especially where you have a lot of records.

Depending on your use case, field names can have a huge impact on storage. Cant understand why this is not a higher priority for MongoDb, as this will have a positive impact on all users. If nothing else, we can start being more descriptive with our field names, without thinking twice about bandwidth & storage costs.

Please do vote.

Call Javascript onchange event by programmatically changing textbox value

You can fire the event simply with

document.getElementById("elementID").onchange();

I dont know if this doesnt work on some browsers, but it should work on FF 3 and IE 7+

HTML select form with option to enter custom value

jQuery Solution!

Demo: http://jsfiddle.net/69wP6/2/

Another Demo Below(updated!)

I needed something similar in a case when i had some fixed Options and i wanted one other option to be editable! In this case i made a hidden input that would overlap the select option and would be editable and used jQuery to make it all work seamlessly.

I am sharing the fiddle with all of you!

HTML

<div id="billdesc">
    <select id="test">
      <option class="non" value="option1">Option1</option>
      <option class="non" value="option2">Option2</option>
      <option class="editable" value="other">Other</option>
    </select>
    <input class="editOption" style="display:none;"></input>
</div>

CSS

body{
    background: blue;
}
#billdesc{
    padding-top: 50px;
}
#test{
    width: 100%;
    height: 30px;
}
option {
    height: 30px;
    line-height: 30px;
}

.editOption{
    width: 90%;
    height: 24px;
    position: relative;
    top: -30px

}

jQuery

var initialText = $('.editable').val();
$('.editOption').val(initialText);

$('#test').change(function(){
var selected = $('option:selected', this).attr('class');
var optionText = $('.editable').text();

if(selected == "editable"){
  $('.editOption').show();


  $('.editOption').keyup(function(){
      var editText = $('.editOption').val();
      $('.editable').val(editText);
      $('.editable').html(editText);
  });

}else{
  $('.editOption').hide();
}
});

Edit : Added some simple touches design wise, so people can clearly see where the input ends!

JS Fiddle : http://jsfiddle.net/69wP6/4/

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

#
# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#
#Header set X-Content-Type-Options: "nosniff"

#
# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
#
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self' www.google-analytics.com adserver.example.com www.example.com;"
Header always set Content-Security-Policy: "style-src 'self' www.example.com;"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, www.example.com and example.com configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

https://developers.google.com/web/fundamentals/security/csp/

https://www.w3.org/TR/CSP/

node.js + mysql connection pooling

Using the standard mysql.createPool(), connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. However if you configure it for 500 connections and use all 500 they will remain open for the durations of the process, even if they are idle!

This means if your MySQL Server max_connections is 510 your system will only have 10 mySQL connections available until your MySQL Server closes them (depends on what you have set your wait_timeout to) or your application closes! The only way to free them up is to manually close the connections via the pool instance or close the pool.

mysql-connection-pool-manager module was created to fix this issue and automatically scale the number of connections dependant on the load. Inactive connections are closed and idle connection pools are eventually closed if there has not been any activity.

    // Load modules
const PoolManager = require('mysql-connection-pool-manager');

// Options
const options = {
  ...example settings
}

// Initialising the instance
const mySQL = PoolManager(options);

// Accessing mySQL directly
var connection = mySQL.raw.createConnection({
  host     : 'localhost',
  user     : 'me',
  password : 'secret',
  database : 'my_db'
});

// Initialising connection
connection.connect();

// Performing query
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
  if (error) throw error;
  console.log('The solution is: ', results[0].solution);
});

// Ending connection
connection.end();

Ref: https://www.npmjs.com/package/mysql-connection-pool-manager

How to prevent robots from automatically filling up a form?

Many of those spam-bots are just server-side scripts that prowl the web. You can combat many of them by using some javascript to manipulate the form request before its sent (ie, setting an additional field based on some client variable). This isn't a full solution, and can lead to many problems (eg, users w/o javascript, on mobile devices, etc), but it can be part of your attack plan.

Here is a trivial example...

<script>
function checkForm()
{
    // When a user submits the form, the secretField's value is changed
    $('input[name=secretField]').val('goodValueEqualsGoodClient');

    return true;
}
</script>

<form id="cheese" onsubmit="checkForm">
<input type="text" name="burger">

<!-- Check that this value isn't the default value in your php script -->
<input type="hidden" name="secretField" value="badValueEqualsBadClient">

<input type="submit">
</form>

Somewhere in your php script...

<?php

if ($_REQUEST['secretField'] != 'goodValueEqualsGoodClient')
{
    die('you are a bad client, go away pls.');
}

?>

Also, captchas are great, and really the best defense against spam.

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

How do I read a file line by line in VB Script?

If anyone like me is searching to read only a specific line, example only line 18 here is the code:

filename = "C:\log.log"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

For i = 1 to 17
    f.ReadLine
Next

strLine = f.ReadLine
Wscript.Echo strLine

f.Close

Different ways of loading a file as an InputStream

Use MyClass.class.getClassLoader().getResourceAsStream(path) to load resource associated with your code. Use MyClass.class.getResourceAsStream(path) as a shortcut, and for resources packaged within your class' package.

Use Thread.currentThread().getContextClassLoader().getResourceAsStream(path) to get resources that are part of client code, not tightly bounds to the calling code. You should be careful with this as the thread context class loader could be pointing at anything.

Generating random integer from a range

How about the Mersenne Twister? The boost implementation is rather easy to use and is well tested in many real-world applications. I've used it myself in several academic projects such as artificial intelligence and evolutionary algorithms.

Here's their example where they make a simple function to roll a six-sided die:

#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>

boost::mt19937 gen;

int roll_die() {
    boost::uniform_int<> dist(1, 6);
    boost::variate_generator<boost::mt19937&, boost::uniform_int<> > die(gen, dist);
    return die();
}

Oh, and here's some more pimping of this generator just in case you aren't convinced you should use it over the vastly inferior rand():

The Mersenne Twister is a "random number" generator invented by Makoto Matsumoto and Takuji Nishimura; their website includes numerous implementations of the algorithm.

Essentially, the Mersenne Twister is a very large linear-feedback shift register. The algorithm operates on a 19,937 bit seed, stored in an 624-element array of 32-bit unsigned integers. The value 2^19937-1 is a Mersenne prime; the technique for manipulating the seed is based on an older "twisting" algorithm -- hence the name "Mersenne Twister".

An appealing aspect of the Mersenne Twister is its use of binary operations -- as opposed to time-consuming multiplication -- for generating numbers. The algorithm also has a very long period, and good granularity. It is both fast and effective for non-cryptographic applications.

SVN 405 Method Not Allowed

I encountered the same issue and was able to fix it by:

  1. Copy the folder to another place.
  2. Delete .svn from copied folder
  3. Right click the original folder and select 'SVN Checkout'
  4. If you can't find (3), then your case is different than mine.
  5. See if the directory on the REPO-BROWSER is correct. For my case, this was the cause.
  6. Check out
  7. Get back the files from the copied folder into the original directory.
  8. Commit.

OkHttp Post Body as JSON

Just use JSONObject.toString(); method. And have a look at OkHttp's tutorial:

public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String url, String json) throws IOException {
  RequestBody body = RequestBody.create(JSON, json); // new
  // RequestBody body = RequestBody.create(JSON, json); // old
  Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();
  Response response = client.newCall(request).execute();
  return response.body().string();
}

How to create byte array from HttpPostedFile

BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);

line 2 should be replaced with

byte[] binData = b.ReadBytes(file.ContentLength);

batch file to copy files to another location?

It's easy to copy a folder in a batch file.

 @echo off
 set src_folder = c:\whatever\*.*
 set dst_folder = c:\foo
 xcopy /S/E/U %src_folder% %dst_folder%

And you can add that batch file to your Windows login script pretty easily (assuming you have admin rights on the machine). Just go to the "User Manager" control panel, choose properties for your user, choose profile and set a logon script.

How you get to the user manager control panel depends on which version of Windows you run. But right clicking on My Computer and choosing manage and then choosing Local users and groups works for most versions.

The only sticky bit is "when the folder is updated". This sounds like a folder watcher, which you can't do in a batch file, but you can do pretty easily with .NET.

How can I open Windows Explorer to a certain directory from within a WPF app?

You can use System.Diagnostics.Process.Start.

Or use the WinApi directly with something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.

public partial class Window1 : Window
{
    public Window1()
    {
        ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
        InitializeComponent();
    }

    public enum ShowCommands : int
    {
        SW_HIDE = 0,
        SW_SHOWNORMAL = 1,
        SW_NORMAL = 1,
        SW_SHOWMINIMIZED = 2,
        SW_SHOWMAXIMIZED = 3,
        SW_MAXIMIZE = 3,
        SW_SHOWNOACTIVATE = 4,
        SW_SHOW = 5,
        SW_MINIMIZE = 6,
        SW_SHOWMINNOACTIVE = 7,
        SW_SHOWNA = 8,
        SW_RESTORE = 9,
        SW_SHOWDEFAULT = 10,
        SW_FORCEMINIMIZE = 11,
        SW_MAX = 11
    }

    [DllImport("shell32.dll")]
    static extern IntPtr ShellExecute(
        IntPtr hwnd,
        string lpOperation,
        string lpFile,
        string lpParameters,
        string lpDirectory,
        ShowCommands nShowCmd);
}

The declarations come from the pinvoke.net website.

Setting Elastic search limit to "unlimited"

use the scan method e.g.

 curl -XGET 'localhost:9200/_search?search_type=scan&scroll=10m&size=50' -d '
 {
    "query" : {
       "match_all" : {}
     }
 }

see here

type object 'datetime.datetime' has no attribute 'datetime'

Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.

Your error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.

>>> import datetime
>>> datetime
<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>
>>> datetime.datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

But, if you import datetime.datetime:

>>> from datetime import datetime
>>> datetime
<type 'datetime.datetime'>
>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work 
                                # as you imported the type, not the module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

I suspect you or one of the modules you're using has imported like this: from datetime import datetime.

How to add a right button to a UINavigationController?

- (void)viewWillAppear:(BOOL)animated
{    
    [self setDetailViewNavigationBar];    
}
-(void)setDetailViewNavigationBar
{
    self.navigationController.navigationBar.tintColor = [UIColor purpleColor];
    [self setNavigationBarRightButton];
    [self setNavigationBarBackButton];    
}
-(void)setNavigationBarBackButton// using custom button 
{
   UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithTitle:@"  Back " style:UIBarButtonItemStylePlain target:self action:@selector(onClickLeftButton:)];          
   self.navigationItem.leftBarButtonItem = leftButton;    
}
- (void)onClickLeftButton:(id)sender 
{
   NSLog(@"onClickLeftButton");        
}
-(void)setNavigationBarRightButton
{

  UIBarButtonItem *anotherButton = [[UIBarButtonItem alloc] initWithTitle:@"Show" style:UIBarButtonItemStylePlain target:self action:@selector(onClickrighttButton:)];          
self.navigationItem.rightBarButtonItem = anotherButton;   

}
- (void)onClickrighttButton:(id)sender 
{
   NSLog(@"onClickrighttButton");  
}

How to change bower's default components folder?

Create a Bower configuration file .bowerrc in the project root (as opposed to your home directory) with the content:

{
  "directory" : "public/components"
}

Run bower install again.

C# int to enum conversion

I'm pretty sure you can do explicit casting here.

foo f = (foo)value;

So long as you say the enum inherits(?) from int, which you have.

enum foo : int

EDIT Yes it turns out that by default, an enums underlying type is int. You can however use any integral type except char.

You can also cast from a value that's not in the enum, producing an invalid enum. I suspect this works by just changing the type of the reference and not actually changing the value in memory.

enum (C# Reference)
Enumeration Types (C# Programming Guide)

Linq to Sql: Multiple left outer joins

Don't have access to VisualStudio (I'm on my Mac), but using the information from http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx it looks like you may be able to do something like this:

var query = from o in dc.Orders
            join v in dc.Vendors on o.VendorId equals v.Id into ov
            from x in ov.DefaultIfEmpty()
            join s in dc.Status on o.StatusId equals s.Id into os
            from y in os.DefaultIfEmpty()
            select new { o.OrderNumber, x.VendorName, y.StatusName }

Best way to use Google's hosted jQuery, but fall back to my hosted library on Google fail

I consider that should escape the last < to \x3C in string. When the browser sees , it considers this to be the end of the script block (since the HTML parser has no idea about JavaScript, it can't distinguish between something that just appears in a string, and something that's actually meant to end the script element). So appearing literally in JavaScript that's inside an HTML page will (in the best case) cause errors, and (in the worst case) be a huge security hole.

<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.0.0.min.js"></script>
<script>window.jQuery || document.write('<script src="js/jquery-2.0.0.min.js">\x3C/script>')</script>

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

From the javadocs:

When a Statement object is closed, its current ResultSet object, if one exists, is also closed.

However, the javadocs are not very clear on whether the Statement and ResultSet are closed when you close the underlying Connection. They simply state that closing a Connection:

Releases this Connection object's database and JDBC resources immediately instead of waiting for them to be automatically released.

In my opinion, always explicitly close ResultSets, Statements and Connections when you are finished with them as the implementation of close could vary between database drivers.

You can save yourself a lot of boiler-plate code by using methods such as closeQuietly in DBUtils from Apache.

In Typescript, How to check if a string is Numeric

Whether a string can be parsed as a number is a runtime concern. Typescript does not support this use case as it is focused on compile time (not runtime) safety.

Access is denied when attaching a database

In my case what solved the problem was the folowing:

USE [master]
GO
CREATE DATABASE [AdventureWorks2008R2] ON
( FILENAME = 'C:\Program Files\Microsfot SQL Server\MSSQL10_50.SQLEXPRESS\MSSQL\DATA\AdventureWors2008R2_Data.mdf')
FOR ATTACH_REBUILD_LOG

Android Use Done button on Keyboard to click button

I copied the following code from AndroidStudio when you create a LoginActivity. I use the ime attributes

In your layout

<EditText android:id="@+id/unidades" android:layout_width="match_parent"
                    android:layout_height="wrap_content" android:hint="@string/prompt_unidades"
                    android:inputType="number" android:maxLines="1"
                    android:singleLine="true"
                    android:textAppearance="?android:textAppearanceSmall"
                    android:enabled="true" android:focusable="true"
                    android:gravity="right"
                    android:imeActionId="@+id/cantidad"
                    android:imeActionLabel="@string/add"
                    android:imeOptions="actionUnspecified"/>

In your Activity

editTextUnidades.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == R.id.cantidad || actionId == EditorInfo.IME_NULL) {
                addDetalle(null);
                return true;
            }
            return false;
        }
    });

Webview load html from assets directory

Download source code from here (Open html file from assets android)

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:background="#FFFFFF"
 android:layout_height="match_parent">

<WebView
 android:layout_width="match_parent"
 android:id="@+id/webview"
 android:layout_height="match_parent"
 android:layout_margin="10dp"></WebView>
</RelativeLayout>

MainActivity.java

package com.deepshikha.htmlfromassets;
 import android.app.ProgressDialog;
 import android.support.v7.app.AppCompatActivity;
 import android.os.Bundle;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {

WebView webview;
 ProgressDialog progressDialog;

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

private void init(){
 webview = (WebView)findViewById(R.id.webview);
 webview.loadUrl("file:///android_asset/download.html");
 webview.requestFocus();

progressDialog = new ProgressDialog(MainActivity.this);
 progressDialog.setMessage("Loading");
 progressDialog.setCancelable(false);
 progressDialog.show();

webview.setWebViewClient(new WebViewClient() {

public void onPageFinished(WebView view, String url) {
 try {
 progressDialog.dismiss();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 });
 }
 }

How do I check if an element is really visible with JavaScript?

As jkl pointed out, checking the element's visibility or display is not enough. You do have to check its ancestors. Selenium does this when it verifies visibility on an element.

Check out the method Selenium.prototype.isVisible in the selenium-api.js file.

http://svn.openqa.org/svn/selenium-on-rails/selenium-on-rails/selenium-core/scripts/selenium-api.js

Plot mean and standard deviation

plt.errorbar can be used to plot x, y, error data (as opposed to the usual plt.plot)

import matplotlib.pyplot as plt
import numpy as np

x = np.array([1, 2, 3, 4, 5])
y = np.power(x, 2) # Effectively y = x**2
e = np.array([1.5, 2.6, 3.7, 4.6, 5.5])

plt.errorbar(x, y, e, linestyle='None', marker='^')

plt.show()

plt.errorbar accepts the same arguments as plt.plot with additional yerr and xerr which default to None (i.e. if you leave them blank it will act as plt.plot).

Example plot

How to delete a folder with files using Java

If you have subfolders, you will find troubles with the Cemron answers. so you should create a method that works like this:

private void deleteTempFile(File tempFile) {
        try
        {
            if(tempFile.isDirectory()){
               File[] entries = tempFile.listFiles();
               for(File currentFile: entries){
                   deleteTempFile(currentFile);
               }
               tempFile.delete();
            }else{
               tempFile.delete();
            }
        getLogger().info("DELETED Temporal File: " + tempFile.getPath());
        }
        catch(Throwable t)
        {
            getLogger().error("Could not DELETE file: " + tempFile.getPath(), t);
        }
    }

Java Try and Catch IOException Problem

Your countLines(String filename) method throws IOException.

You can't use it in a member declaration. You'll need to perform the operation in a main(String[] args) method.

Your main(String[] args) method will get the IOException thrown to it by countLines and it will need to handle or declare it.

Try this to just throw the IOException from main

public class MyClass {
  private int lineCount;
  public static void main(String[] args) throws IOException {
    lineCount = LineCounter.countLines(sFileName);
  }
}

or this to handle it and wrap it in an unchecked IllegalArgumentException:

public class MyClass {
  private int lineCount;
  private String sFileName  = "myfile";
  public static void main(String[] args) throws IOException {
    try {
      lineCount = LineCounter.countLines(sFileName);
     } catch (IOException e) {
       throw new IllegalArgumentException("Unable to load " + sFileName, e);
     }
  }
}

How to get EditText value and display it on screen through TextView?

First get the value from edit text in a String variable

String value = edttxt.getText().toString();

Then set that value to textView

txtview.setText(value);

Where edttxt refers to edit text field in XML file and txtview refers to textfield in XML file to show the value

Scanning Java annotations at runtime

The Classloader API doesn't have an "enumerate" method, because class loading is an "on-demand" activity -- you usually have thousands of classes in your classpath, only a fraction of which will ever be needed (the rt.jar alone is 48MB nowadays!).

So, even if you could enumerate all classes, this would be very time- and memory-consuming.

The simple approach is to list the concerned classes in a setup file (xml or whatever suits your fancy); if you want to do this automatically, restrict yourself to one JAR or one class directory.

Why does git status show branch is up-to-date when changes exist upstream?

This is because your local repo hasn't checked in with the upstream remotes. To have this work as you're expecting it to, use git fetch then run a git status again.

For loop in multidimensional javascript array

Or you can do this alternatively with "forEach()":

var cubes = [
 [1, 2, 3],
 [4, 5, 6],    
 [7, 8, 9],
];

cubes.forEach(function each(item) {
  if (Array.isArray(item)) {
    // If is array, continue repeat loop
    item.forEach(each);
  } else {
    console.log(item);
  }
});

If you need array's index, please try this code:

var i = 0; j = 0;

cubes.forEach(function each(item) {
  if (Array.isArray(item)) {
    // If is array, continue repeat loop
    item.forEach(each);
    i++;
    j = 0;
  } else {
    console.log("[" + i + "][" + j + "] = " + item);
    j++;
  }
});

And the result will look like this:

[0][0] = 1
[0][1] = 2
[0][2] = 3
[1][0] = 4
[1][1] = 5
[1][2] = 6
[2][0] = 7
[2][1] = 8
[2][2] = 9

Find and replace Android studio

In Android studio, Edit -- > Find --> Replace in path, this will check in whole project including comments and code.

Getting the inputstream from a classpath resource (XML file)

someClassWithinYourSourceDir.getClass().getResourceAsStream();

Delete directory with files in it?

Here you have one nice and simple recursion for deleting all files in source directory including that directory:

function delete_dir($src) { 
    $dir = opendir($src);
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                delete_dir($src . '/' . $file); 
            } 
            else { 
                unlink($src . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
    rmdir($src);

}

Function is based on recursion made for copying directory. You can find that function here: Copy entire contents of a directory to another using php

how to make jni.h be found?

Installing the OpenJDK Development Kit (JDK) should fix your problem.

sudo apt-get install openjdk-X-jdk

This should make you able to compile without problems.

Can you display HTML5 <video> as a full screen background?

Use position:fixed on the video, set it to 100% width/height, and put a negative z-index on it so it appears behind everything.

If you look at VideoJS, the controls are just html elements sitting on top of the video, using z-index to make sure they're above.

HTML

<video id="video_background" src="video.mp4" autoplay>

(Add webm and ogg sources to support more browsers)

CSS

#video_background {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -1000;
}

It'll work in most HTML5 browsers, but probably not iPhone/iPad, where the video needs to be activated, and doesn't like elements over it.

Android: How to use webcam in emulator?

I would suggest checking the drivers and updating them if required.

Best way to find if an item is in a JavaScript array?

As of ECMAScript 2016 you can use includes()

arr.includes(obj);

If you want to support IE or other older browsers:

function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

  1. Mozilla's (ECMA-262) version:

       if (!Array.prototype.indexOf)
       {
    
            Array.prototype.indexOf = function(searchElement /*, fromIndex */)
    
         {
    
    
         "use strict";
    
         if (this === void 0 || this === null)
           throw new TypeError();
    
         var t = Object(this);
         var len = t.length >>> 0;
         if (len === 0)
           return -1;
    
         var n = 0;
         if (arguments.length > 0)
         {
           n = Number(arguments[1]);
           if (n !== n)
             n = 0;
           else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
             n = (n > 0 || -1) * Math.floor(Math.abs(n));
         }
    
         if (n >= len)
           return -1;
    
         var k = n >= 0
               ? n
               : Math.max(len - Math.abs(n), 0);
    
         for (; k < len; k++)
         {
           if (k in t && t[k] === searchElement)
             return k;
         }
         return -1;
       };
    
     }
    
  2. Daniel James's version:

     if (!Array.prototype.indexOf) {
       Array.prototype.indexOf = function (obj, fromIndex) {
         if (fromIndex == null) {
             fromIndex = 0;
         } else if (fromIndex < 0) {
             fromIndex = Math.max(0, this.length + fromIndex);
         }
         for (var i = fromIndex, j = this.length; i < j; i++) {
             if (this[i] === obj)
                 return i;
         }
         return -1;
       };
     }
    
  3. roosteronacid's version:

     Array.prototype.hasObject = (
       !Array.indexOf ? function (o)
       {
         var l = this.length + 1;
         while (l -= 1)
         {
             if (this[l - 1] === o)
             {
                 return true;
             }
         }
         return false;
       } : function (o)
       {
         return (this.indexOf(o) !== -1);
       }
     );
    

AngularJS: How can I pass variables between controllers?

Solution without creating Service, using $rootScope:

To share properties across app Controllers you can use Angular $rootScope. This is another option to share data, putting it so that people know about it.

The preferred way to share some functionality across Controllers is Services, to read or change a global property you can use $rootscope.

var app = angular.module('mymodule',[]);
app.controller('Ctrl1', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = true;
}]);

app.controller('Ctrl2', ['$scope','$rootScope',
  function($scope, $rootScope) {
    $rootScope.showBanner = false;
}]);

Using $rootScope in a template (Access properties with $root):

<div ng-controller="Ctrl1">
    <div class="banner" ng-show="$root.showBanner"> </div>
</div>

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

I stumbled upon another solution, which is quite nice.

Basically, only do step 2 from the blog posted mentioned, and define a custom ObjectMapper as a Spring @Component. (Things started working when I just removed all the AnnotationMethodHandlerAdapter stuff from step 3.)

@Component
@Primary
public class CustomObjectMapper extends ObjectMapper {
    public CustomObjectMapper() {
        setSerializationInclusion(JsonInclude.Include.NON_NULL); 
        configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    }
}

Works as long as the component is in a package scanned by Spring. (Using @Primary is not mandatory in my case, but why not make things explicit.)

For me there are two benefits compared to the other approach:

  • This is simpler; I can just extend a class from Jackson and don't need to know about highly Spring-specific stuff like Jackson2ObjectMapperBuilder.
  • I want to use the same Jackson configs for deserialising JSON in another part of my app, and this way it's very simple: new CustomObjectMapper() instead of new ObjectMapper().

Copy files on Windows Command Line with Progress

You could easily write a program to do that, I've got several that I've written, that display bytes copied as the file is being copied. If you're interested, comment and I'll post a link to one.

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

How about some recursion:

private static string ReturnSize(double size, string sizeLabel)
{
  if (size > 1024)
  {
    if (sizeLabel.Length == 0)
      return ReturnSize(size / 1024, "KB");
    else if (sizeLabel == "KB")
      return ReturnSize(size / 1024, "MB");
    else if (sizeLabel == "MB")
      return ReturnSize(size / 1024, "GB");
    else if (sizeLabel == "GB")
      return ReturnSize(size / 1024, "TB");
    else
      return ReturnSize(size / 1024, "PB");
  }
  else
  {
    if (sizeLabel.Length > 0)
      return string.Concat(size.ToString("0.00"), sizeLabel);
    else
      return string.Concat(size.ToString("0.00"), "Bytes");
  }
}

Then you can call it:

ReturnSize(size, string.Empty);

Remove all newlines from inside a string

strip() returns the string with leading and trailing whitespaces(by default) removed.

So it would turn " Hello World " to "Hello World", but it won't remove the \n character as it is present in between the string.

Try replace().

str = "Hello \n World"
str2 = str.replace('\n', '')
print str2

How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
    With lst
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        On Error Resume Next
        With .DataBodyRange
            .Offset(1).Rows.Clear
            .Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        End With
        On Error GoTo 0
        .Resize .Range.Rows("1:2")
    End With
End Sub

Read .doc file with python

One can use the textract library. It take care of both "doc" as well as "docx"

import textract
text = textract.process("path/to/file.extension")

You can even use 'antiword' (sudo apt-get install antiword) and then convert doc to first into docx and then read through docx2txt.

antiword filename.doc > filename.docx

Ultimately, textract in the backend is using antiword.

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

INNER JOIN gets all records that are common between both tables based on the supplied ON clause.

LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.

RIGHT JOIN is like the above but gets all records in the RIGHT table.

FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.

How can I decrease the size of Ratingbar?

This Worked for me.
Check this image

            android:id="@+id/ratingBar"
            style="?android:attr/ratingBarStyleIndicator"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:numStars="5"
            android:scaleX=".8"
            android:scaleY=".8"
            android:stepSize="0.5"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.543"
            app:layout_constraintStart_toEndOf="@+id/title"
            app:layout_constraintTop_toTopOf="parent" />

how to get the selected index of a drop down

<select name="CCards" id="ccards">
    <option value="0">Select Saved Payment Method:</option>
    <option value="1846">test  xxxx1234</option>
    <option value="1962">test2  xxxx3456</option>
</select>

<script type="text/javascript">

    /** Jquery **/
    var selectedValue = $('#ccards').val();

    //** Regular Javascript **/
    var selectedValue2 = document.getElementById('ccards').value;


</script>

document.getElementById(id).focus() is not working for firefox or chrome

Not all elements are focusable but default, there is a tabindex attribute to fix that.

When you assign tabindex= to an element:

It becomes focusable. A user can use the tab key to move from the element with lesser positive tabindex to the next one. The exception is a special value tabindex="0" means that the element will always be last. The tabindex=-1 means that an element becomes focusable, but the tab key will always skip it. Only the focus() method will work

2D Euclidean vector rotations

Rotating a vector 90 degrees is particularily simple.

(x, y) rotated 90 degrees around (0, 0) is (-y, x).

If you want to rotate clockwise, you simply do it the other way around, getting (y, -x).

Converting JSON to XML in Java

If you have a valid dtd file for the xml then you can easily transform json to xml and xml to json using the eclipselink jar binary.

Refer this: http://www.cubicrace.com/2015/06/How-to-convert-XML-to-JSON-format.html

The article also has a sample project (including the supporting third party jars) as a zip file which can be downloaded for reference purpose.

How to drop all tables from the database with manage.py CLI in Django?

There's no native Django management command to drop all tables. Both sqlclear and reset require an app name.

However, you can install Django Extensions which gives you manage.py reset_db, which does exactly what you want (and gives you access to many more useful management commands).

Getting Integer value from a String using javascript/jquery

For parseInt to work, your string should have only numerical data. Something like this:

 str1 = "123.00";
 str2 = "50.00";
 total = parseInt(str1)+parseInt(str2);
 alert(total);

Can you split the string before you start processing them for a total?

Is there an effective tool to convert C# code to Java code?

Why not write it in Haxe (http://haxe.org/) and convert it to whatever you want it to be?