Programs & Examples On #Code analysis

Code Analysis is the process of analyzing the code of the application to discover, review, validate or verify certain properties of the application. This is useful during the process of development and for testing the application before it is put in production mode, especially for checking the security related aspects.

C# compiler error: "not all code paths return a value"

I also experienced this problem and found the easy solution to be

public string ReturnValues()
{
    string _var = ""; // Setting an innitial value

    if (.....)  // Looking at conditions
    {
        _var = "true"; // Re-assign the value of _var
    }

    return _var; // Return the value of var
}

This also works with other return types and gives the least amount of problems

The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.

How do I fix PyDev "Undefined variable from import" errors?

This worked for me:

step 1) Removing the interpreter, auto configuring it again

step 2) Window - Preferences - PyDev - Interpreters - Python Interpreter Go to the Forced builtins tab Click on New... Type the name of the module (curses in my case) and click OK

step 3) Right click in the project explorer on whichever module is giving errors. Go to PyDev->Code analysis.

Style input type file?

use uniform js plugin to style input of any type, select, textarea.

The URL is http://uniformjs.com/

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

MySQL SELECT statement for the "length" of the field is greater than 1

Just in case anybody want to find how in oracle and came here (like me), the syntax is

select length(FIELD) from TABLE

just in case ;)

how to increase sqlplus column output length?

None of these suggestions were working for me. I finally found something else I could do - dbms_output.put_line. For example:

SET SERVEROUTPUT ON
begin
for i in (select dbms_metadata.get_ddl('INDEX', index_name, owner) as ddl from all_indexes where owner = 'MYUSER') loop
  dbms_output.put_line(i.ddl);
end loop;
end;
/

Boom. It printed out everything I wanted - no truncating or anything like that. And that works straight in sqlplus - no need to put it in a separate file or anything.

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

I just solved this error for myself, but it was a bit silly on my part. Still worth checking if the above doesn't help you.

In my case, I was editing the config files in /etc/phpmyadmin, my install was located in /usr/share/phpmyadmin, and my install was not actually opening the /etc/phpmyadmin config files, as I thought it would. So I just did this command:

ln -s /etc/phpmyadmin/conf* /usr/share/phpmyadmin

For those not in the know, ln -s makes a soft link (basically a shortcut). So that command just makes shortcuts from the config files in /etc to the /usr/share install.

By the way, I figured this out after using the program opensnoop, which shows you what files are being opened (technically, traces open() syscalls and the pid of the process, as they happen), which you can install on Ubuntu with apt-get install perf-tools-unstable, or you can get it here.

I can't access http://localhost/phpmyadmin/

I had the same problem. Couldn't access http://localhost/joomla neither.
and I did not quite understand the other answers.
The simple solution for me:

  1. stop all actions in xampp (I had apache and mysql running. apache on port 80 and 7000something)
  2. quit firefox
  3. restart the actions (apache and mysql)
  4. restart firefox.
  5. open http://localhost/phpmyadmin (or http://localhost/joomla - whatever it be)
  6. voila!

Now apache runs on port 80 and 443 and mysql on 3306.

How to work with progress indicator in flutter?

I took the following approach, which uses a simple modal progress indicator widget that wraps whatever you want to make modal during an async call.

The example in the package also addresses how to handle form validation while making async calls to validate the form (see flutter/issues/9688 for details of this problem). For example, without leaving the form, this async form validation method can be used to validate a new user name against existing names in a database while signing up.

https://pub.dartlang.org/packages/modal_progress_hud

Here is the demo of the example provided with the package (with source code):

async form validation with modal progress indicator

Example could be adapted to other modal progress indicator behaviour (like different animations, additional text in modal, etc..).

Fatal error in launcher: Unable to create process using ""C:\Program Files (x86)\Python33\python.exe" "C:\Program Files (x86)\Python33\pip.exe""

having the same trouble I read in https://pip.pypa.io/en/latest/installing.html#install-pip that to update pip it's:

python -m pip install -U pip

So I made (for example)

python -m pip install virtualenv

And it worked! So you can do the same being 'virtualenv' another package you want.

Git: How to return from 'detached HEAD' state

I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:

git checkout 1.87.1                                    
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. 
Example:

  git checkout -b <new-branch-name>

HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'

In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).

git checkout master did not work:

$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...

git checkout master --force (or git checkout master -f) worked:

git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.

Method to get all files within folder and subfolders that will return a list

Try this
class Program { static void Main(string[] args) {

        getfiles get = new getfiles();
        List<string> files =  get.GetAllFiles(@"D:\Rishi");

        foreach(string f in files)
        {
            Console.WriteLine(f);
        }


        Console.Read();
    }


}

class getfiles
{
    public List<string> GetAllFiles(string sDirt)
    {
        List<string> files = new List<string>();

        try
        {
            foreach (string file in Directory.GetFiles(sDirt))
            {
                files.Add(file);
            }
            foreach (string fl in Directory.GetDirectories(sDirt))
            {
                files.AddRange(GetAllFiles(fl));
            }
        }
        catch (Exception ex)
        {

            Console.WriteLine(ex.Message);
        }



        return files;
    }
}

Using jQuery to test if an input has focus

As far as I know, you can't ask the browser if any input on the screen has focus, you have to set up some sort of focus tracking.

I usually have a variable called "noFocus" and set it to true. Then I add a focus event to all inputs that makes noFocus false. Then I add a blur event to all inputs that set noFocus back to true.

I have a MooTools class that handles this quite easily, I'm sure you could create a jquery plugin to do the same.

Once that's created, you could do check noFocus before doing any border swapping.

Iterating through a JSON object

I would solve this problem more like this

import json
import urllib2

def last_song(user, limit):
    # Assembling strings with "foo" + str(bar) + "baz" + ... generally isn't 
    # as nice as using real string formatting. It can seem simpler at first, 
    # but leaves you less happy in the long run.
    url = 'http://gsuser.com/lastSong/%s/%d/' % (user, limit)

    # urllib.urlopen is deprecated in favour of urllib2.urlopen
    site = urllib2.urlopen(url)

    # The json module has a function load for loading from file-like objects, 
    # like the one you get from `urllib2.urlopen`. You don't need to turn 
    # your data into a string and use loads and you definitely don't need to 
    # use readlines or readline (there is seldom if ever reason to use a 
    # file-like object's readline(s) methods.)
    songs = json.load(site)

    # I don't know why "lastSong" stuff returns something like this, but 
    # your json thing was a JSON array of two JSON objects. This will 
    # deserialise as a list of two dicts, with each item representing 
    # each of those two songs.
    #
    # Since each of the songs is represented by a dict, it will iterate 
    # over its keys (like any other Python dict). 
    baby, feel_good = songs

    # Rather than printing in a function, it's usually better to 
    # return the string then let the caller do whatever with it. 
    # You said you wanted to make the output pretty but you didn't 
    # mention *how*, so here's an example of a prettyish representation
    # from the song information given.
    return "%(SongName)s by %(ArtistName)s - listen at %(link)s" % baby

When should I write the keyword 'inline' for a function/method?

Inline keyword requests the compiler to replace the function call with the body of the function ,it first evaluates the expression and then passed.It reduces the function call overhead as there is no need to store the return address and stack memory is not required for function arguments.

When to use:

  • To Improve performance
  • To reduce call overhead .
  • As it's just a request to the compiler, certain functions won't be inlined *large functions
    • functions having too many conditional arguments
    • recursive code and code with loops etc.

Is there a RegExp.escape function in JavaScript?

Nothing should prevent you from just escaping every non-alphanumeric character:

usersString.replace(/(?=\W)/g, '\\');

You lose a certain degree of readability when doing re.toString() but you win a great deal of simplicity (and security).

According to ECMA-262, on the one hand, regular expression "syntax characters" are always non-alphanumeric, such that the result is secure, and special escape sequences (\d, \w, \n) are always alphanumeric such that no false control escapes will be produced.

How can I analyze a heap dump in IntelliJ? (memory leak)

You can install the JVisualVM plugin from here: https://plugins.jetbrains.com/plugin/3749?pr=

This will allow you to analyse the dump within the plugin.

How can I get argv[] as int?

Basic usage

The "string to long" (strtol) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:

#include <stdlib.h>

long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)

Since we use the decimal system, base is 10. The endpointer argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL instead of passing a pointer, as shown.

Error checking (1)

If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0 is always the last character of a string in C:

#include <stdlib.h>

char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string

Error checking (2)

As the man page mentions, you can use errno to check that no errors occurred (in this case overflows or underflows).

#include <stdlib.h>
#include <errno.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

// Everything went well, print it as 'long decimal'
printf("%ld", arg);

Convert to integer

So now we are stuck with this long, but we often want to work with integers. To convert a long into an int, we should first check that the number is within the limited capacity of an int. To do this, we add a second if-statement, and if it matches, we can just cast it.

#include <stdlib.h>
#include <errno.h>
#include <limits.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

if (arg < INT_MIN || arg > INT_MAX) {
    return 1;
}
int arg_int = arg;

// Everything went well, print it as a regular number
printf("%d", arg_int);

To see what happens if you don't do this check, test the code without the INT_MIN/MAX if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.

Full example

#include <stdio.h>  // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h>  // for errno
#include <limits.h> // for INT_MIN and INT_MAX

int main(int argc, char** argv) {
    char* p;
    errno = 0; // not 'int errno', because the '#include' already defined it
    long arg = strtol(argv[1], &p, 10);
    if (*p != '\0' || errno != 0) {
        return 1; // In main(), returning non-zero means failure
    }

    if (arg < INT_MIN || arg > INT_MAX) {
        return 1;
    }
    int arg_int = arg;

    // Everything went well, print it as a regular number plus a newline
    printf("Your value was: %d\n", arg_int);
    return 0;
}

In Bash, you can test this with:

cc code.c -o example  # Compile, output to 'example'
./example $((2**31-1))  # Run it
echo "exit status: $?"  # Show the return value, also called 'exit status'

Using 2**31-1, it should print the number and 0, because 231-1 is just in range. If you pass 2**31 instead (without -1), it will not print the number and the exit status will be 1.

Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc), test whether the number is in the range that you want, etc.

How to install PHP intl extension in Ubuntu 14.04

you could search with aptitude search intl after you can choose the right one, for example sudo aptitude install php-intl and finally sudo service apache2 restart

good Luck!

How do I create/edit a Manifest file?

As ibram stated, add the manifest thru solution explorer:

enter image description here

This creates a default manifest. Now, edit the manifest.

  • Update the assemblyIdentity name as your application.
  • Ask users to trust your application

enter image description here

  • Add supported OS

enter image description here

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

How to normalize a vector in MATLAB efficiently? Any related built-in function?

By the rational of making everything multiplication I add the entry at the end of the list

    clc; clear all;
    V = rand(1024*1024*32,1);
    N = 10;
    tic; for i=1:N, V1 = V/norm(V);         end; toc % 4.5 s
    tic; for i=1:N, V2 = V/sqrt(sum(V.*V)); end; toc % 7.5 s
    tic; for i=1:N, V3 = V/sqrt(V'*V);      end; toc % 4.9 s
    tic; for i=1:N, V4 = V/sqrt(sum(V.^2)); end; toc % 6.8 s
    tic; for i=1:N, V1 = V/norm(V);         end; toc % 4.7 s
    tic; for i=1:N, d = 1/norm(V); V1 = V*d;end; toc % 4.9 s
    tic; for i=1:N, d = norm(V)^-1; V1 = V*d;end;toc % 4.4 s

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

To solve this problem first make sure that your java software should be 32bit version if it is 64 bit version clearly it will show the mismatch error so try to re-install 32bit of java version And execute the java program in the command of c:\windows\sysWOW64\odbcad32.exe (easiest to copy and paste into run dialog) that's enough your program definitely work

How should I validate an e-mail address?

Kotlin Extension Function

fun EditText.isValidEmail() : Boolean{
    return if(Pattern
            .compile("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")
            .matcher(text.toString()).matches()){
        true
    }else {
        hint = context.getString(R.string.invalid_email_adress)
        false
    }
}

Use

if(!emailEt.isValidEmail()){
    return
}

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

I have tried many suggestions above but docker keeps complaining about hardware assisted virtualization error. Virtualization is enabled in BIOS, and also Hyper-V is installed and enabled. After a few try and errors, I eventually downloaded coreinfo tool and found out that Hypervisor was not actually enabled. Using ISE (64 bit) as admin and run command from above Solution B and that enables Hypervisor successfully (checked via coreinfo -v again). After restart, docker is now running successfully.

Why do we use web.xml?

It's the default configuration for a Java web application; it's required.

WicketFilter

is applied to every HTTP request that's sent to this web app.

Reading a file character by character in C

Here's one simple way to ignore everything but valid brainfuck characters:

#define BF_VALID "+-><[].,"

if (strchr(BF_VALID, c))
    code[n++] = c;

Wait until page is loaded with Selenium WebDriver for Python

Solution for ajax pages that continuously load data. The previews methods stated do not work. What we can do instead is grab the page dom and hash it and compare old and new hash values together over a delta time.

import time
from selenium import webdriver

def page_has_loaded(driver, sleep_time = 2):
    '''
    Waits for page to completely load by comparing current page hash values.
    '''

    def get_page_hash(driver):
        '''
        Returns html dom hash
        '''
        # can find element by either 'html' tag or by the html 'root' id
        dom = driver.find_element_by_tag_name('html').get_attribute('innerHTML')
        # dom = driver.find_element_by_id('root').get_attribute('innerHTML')
        dom_hash = hash(dom.encode('utf-8'))
        return dom_hash

    page_hash = 'empty'
    page_hash_new = ''
    
    # comparing old and new page DOM hash together to verify the page is fully loaded
    while page_hash != page_hash_new: 
        page_hash = get_page_hash(driver)
        time.sleep(sleep_time)
        page_hash_new = get_page_hash(driver)
        print('<page_has_loaded> - page not loaded')

    print('<page_has_loaded> - page loaded: {}'.format(driver.current_url))

Python DNS module import error

I have faced similar issue when importing on mac.i have python 3.7.3 installed Following steps helped me resolve it:

  1. pip3 uninstall dnspython
  2. sudo -H pip3 install dnspython

Import dns

Import dns.resolver

Android Spinner : Avoid onItemSelected calls during initialization

My solution:

protected boolean inhibit_spinner = true;


@Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int pos, long arg3) {

            if (inhibit_spinner) {
                inhibit_spinner = false;
            }else {

            if (getDataTask != null) getDataTask.cancel(true);
            updateData();
            }

        }

How to create a POJO?

When you aren't doing anything to make your class particularly designed to work with a given framework, ORM, or other system that needs a special sort of class, you have a Plain Old Java Object, or POJO.

Ironically, one of the reasons for coining the term is that people were avoiding them in cases where they were sensible and some people concluded that this was because they didn't have a fancy name. Ironic, because your question demonstrates that the approach worked.

Compare the older POD "Plain Old Data" to mean a C++ class that doesn't do anything a C struct couldn't do (more or less, non-virtual members that aren't destructors or trivial constructors don't stop it being considered POD), and the newer (and more directly comparable) POCO "Plain Old CLR Object" in .NET.

ImageView - have height match width?

I couldn't get David Chu's answer to work for a RecyclerView item and figured out I needed to constrain the ImageView to the parent. Set the ImageView width to 0dp and constrain its start and end to the parent. I'm not sure if setting the width to wrap_content or match_parent works in some cases, but I think this is a better way to get the child of a ConstraintLayout to fill its parent.

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintDimensionRatio="1:1"/>

</android.support.constraint.ConstraintLayout>

How to add column to numpy array

If you have an array, a of say 210 rows by 8 columns:

a = numpy.empty([210,8])

and want to add a ninth column of zeros you can do this:

b = numpy.append(a,numpy.zeros([len(a),1]),1)

Java: Calculating the angle between two points in degrees

The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.

How to check if a word is an English word with Python?

For a semantic web approach, you could run a sparql query against WordNet in RDF format. Basically just use urllib module to issue GET request and return results in JSON format, parse using python 'json' module. If it's not English word you'll get no results.

As another idea, you could query Wiktionary's API.

How do I change the font color in an html table?

<table>
<tbody>
<tr>
<td>
<select name="test" style="color: red;">
<option value="Basic">Basic : $30.00 USD - yearly</option>
<option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
<option value="Supporting">Supporting : $120.00 USD - yearly</option>
</select>
</td>
</tr>
</tbody>
</table>

cin and getline skipping input

Here, the '\n' left by cin, is creating issues.

do {
    system("cls");
    manageCustomerMenu();
    cin >> choice;               #This cin is leaving a trailing \n
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

This \n is being consumed by next getline in createNewCustomer(). You should use getline instead -

do {
    system("cls");
    manageCustomerMenu();
    getline(cin, choice)               
    system("cls");

    switch (choice) {
        case '1':
            createNewCustomer();
            break;

I think this would resolve the issue.

What does "<>" mean in Oracle

In mysql extended version, <> gives out error. You are using mysql_query Eventually, you have to use extended version of my mysql. Old will be replaced in future browser. Rather use something like

$con = mysqli_connect("host", "username", "password", "databaseName");

mysqli_query($con, "select orderid != 650");

Get the time difference between two datetimes

EPOCH TIME DIFFERENCE USING MOMENTJS:

To Get Difference between two epoch times:

Syntax: moment.duration(moment(moment(date1).diff(moment(date2)))).asHours()

Difference in Hours: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asHours()

Difference in minutes: moment.duration(moment(moment(1590597744551).diff(moment(1590597909877)))).asMinutes().toFixed()

Note: You could remove .toFixed() if you need precise values.

Code:

const moment = require('moment')

console.log('Date 1',moment(1590597909877).toISOString())
console.log('Date 2',moment(1590597744551).toISOString())
console.log('Date1 - Date 2 time diffrence is : ',moment.duration(moment(moment(1590597909877).diff(moment(1590597744551)))).asMinutes().toFixed()+' minutes')

Refer working example here: https://repl.it/repls/MoccasinDearDimension

Decompile an APK, modify it and then recompile it

dex2jar with jd-gui will give all the java source files but they are not exactly the same. They are almost equivalent .class files (not 100%). So if you want to change the code for an apk file:

  • decompile using apktool

  • apktool will generate smali(Assembly version of dex) file for every java file with same name.

  • smali is human understandable, make changes in the relevant file, recompile using same apktool(apktool b Nw.apk <Folder Containing Modified Files>)

Getting started with OpenCV 2.4 and MinGW on Windows 7

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-file-extracting so just double click the file to start installation. Install it in a directory, say C:\.

OpenCV self-extracting

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add C:\opencv\build\x86\mingw\bin directory to your system PATH. This directory contains OpenCV DLLs which is required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced TabEnvironment variables...

You will see a window like shown below:

Add OpenCV DLL directory to system path

On the System Variables section,
select Path (1), click Edit... (2), add C:\opencv\build\x86\mingw\bin (3) then click Ok.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Installing MinGW compiler suite

I highly recommend you to use gcc (GNU Compiler Collection) for compiling your code. gcc is the compiler suite widely available in Linux systems and MinGW is the native port for Windows.

Download the MinGW installer from Sourceforge.net and double click to start installation. Just follow the wizard and select the directory to be installed, say C:\MinGW.

Select directory in MinGW installation

Select "C Compiler" and "C++ Compiler" to be installed.

Select components to be installed

The installer will download some packages from the internet so you have to wait for a while. After the installation finished, add C:\MinGW\bin to your system path using the steps described before.

Add MinGW bin directory to system path

To test if your MinGW installation is success, open a command-line box and type: gcc. If everything is ok, it will display this message:

gcc: fatal error: no input files
compilation terminated

This completes the MinGW installation, now is the time to write your "Hello, World!" program.


3. Write a sample code

Open your text editor and type the code below and save the file to loadimg.cpp.

#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
  Mat im = imread(argc == 2 ? argv[1] : "lena.jpg", 1);
  if (im.empty())
  {
    cout << "Cannot open image!" << endl;
    return -1;
  }

  imshow("image", im);
  waitKey(0);

  return 0;
}

Put lena.jpg or any image you like in the same directory with the file above. Open a command-line box and compile the code above by typing:

g++ -I"C:\opencv\build\include" -L"C:\opencv\build\x86\mingw\lib" loadimg.cpp -lopencv_core243 -lopencv_highgui243 -o loadimg

If it compiles successfully, it will create an executable named loadimg.exe.

Type:

loadimg

To execute the program. Result:

The result of your first OpenCV program


4. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → C:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

MySQL Error 1093 - Can't specify target table for update in FROM clause

The inner join in your sub-query is unnecessary. It looks like you want to delete the entries in story_category where the category_id is not in the category table.

Do this:

DELETE FROM story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category);

Instead of that:

DELETE FROM story_category 
WHERE category_id NOT IN (
    SELECT DISTINCT category.id 
    FROM category INNER JOIN
         story_category ON category_id=category.id);

Why does git revert complain about a missing -m option?

By default git revert refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD is in fact a merge commit.

If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.

Often this will be parent number one, for example if you were on master and did git merge unwanted and then decided to revert the merge of unwanted. The first parent would be your pre-merge master branch and the second parent would be the tip of unwanted.

In this case you could do:

git revert -m 1 HEAD

How to tell if string starts with a number with Python?

You could use regular expressions.

You can detect digits using:

if(re.search([0-9], yourstring[:1])):
#do something

The [0-9] par matches any digit, and yourstring[:1] matches the first character of your string

Aren't promises just callbacks?

Promises are not callbacks. A promise represents the future result of an asynchronous operation. Of course, writing them the way you do, you get little benefit. But if you write them the way they are meant to be used, you can write asynchronous code in a way that resembles synchronous code and is much more easy to follow:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
});

Certainly, not much less code, but much more readable.

But this is not the end. Let's discover the true benefits: What if you wanted to check for any error in any of the steps? It would be hell to do it with callbacks, but with promises, is a piece of cake:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
});

Pretty much the same as a try { ... } catch block.

Even better:

api().then(function(result){
    return api2();
}).then(function(result2){
    return api3();
}).then(function(result3){
     // do work
}).catch(function(error) {
     //handle any error that may occur before this point
}).then(function() {
     //do something whether there was an error or not
     //like hiding an spinner if you were performing an AJAX request.
});

And even better: What if those 3 calls to api, api2, api3 could run simultaneously (e.g. if they were AJAX calls) but you needed to wait for the three? Without promises, you should have to create some sort of counter. With promises, using the ES6 notation, is another piece of cake and pretty neat:

Promise.all([api(), api2(), api3()]).then(function(result) {
    //do work. result is an array contains the values of the three fulfilled promises.
}).catch(function(error) {
    //handle the error. At least one of the promises rejected.
});

Hope you see Promises in a new light now.

How to run stored procedures in Entity Framework Core?

Stored procedure support is not yet (as of 7.0.0-beta3) implemented in EF7. You can track the progress of this feature using issue #245.

For now, you can do it the old fashioned way using ADO.NET.

var connection = (SqlConnection)context.Database.AsSqlServer().Connection.DbConnection;

var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "MySproc";
command.Parameters.AddWithValue("@MyParameter", 42);

command.ExecuteNonQuery();

How do I do redo (i.e. "undo undo") in Vim?

CTRL+r

The "r" is lower-case.

When do items in HTML5 local storage expire?

If anyone still looking for a quick solution and don't want dependencies like jquery etc I wrote a mini lib that add expiration to local / session / custom storage, you can find it with source here:

https://github.com/RonenNess/ExpiredStorage

How to Extract Year from DATE in POSTGRESQL

This line solved my same problem in postgresql:

SELECT DATE_PART('year', column_name::date) from tableName;

If you want month, then simply replacing year with month solves that as well and likewise.

How do you find the sum of all the numbers in an array in Java?

Most of the answers here are using inbuilt functions-
Here is my answer if you want to know the whole logic behind this ques:

import java.util.*;

public class SumOfArray {
    public static void main(String[] args){
        Scanner inp = new Scanner(System.in);
        int n = inp.nextInt();
        int[] arr = new int[n];
        for(int i = 0; i < n; i++){
            arr[i] = inp.nextInt();
        }
        System.out.println("The sum of the array is :" + sum(arr));
    }
    static int sum(int[] arr){
        int sum = 0;
        for (int a = 0; a < arr.length; a++){
            sum = sum + arr[a];
        }
        return sum;
    }
}

How to validate date with format "mm/dd/yyyy" in JavaScript?

var date = new Date(date_string)

returns the literal 'Invalid Date' for any invalid date_string.

Note: Please see the comment's below.

Uninstall all installed gems, in OSX?

First make sure you have at least gem version 2.1.0

gem update --system
gem --version
# 2.6.4

To uninstall simply run:

gem uninstall --all

You may need to use the sudo command:

sudo gem uninstall --all

Free ASP.Net and/or CSS Themes

Microsoft hired one fo the kids from A List Apart to whip some out. The .Net projects are free of charge for download.

http://msdn.microsoft.com/en-us/asp.net/aa336613.aspx

Google Maps API v3: InfoWindow not sizing correctly

Also important is height of the map container. If to small infoWindow always will be on 80px height. Otherwise maxWidth and #innerDiv fix works like a charm.

Select rows having 2 columns equal value

SELECT t1.* FROM table t1 JOIN table t2 ON t1.Id=t2.Id WHERE t1.C4=t2.C4;

Giving Accurate Result for me.

How do I keep two side-by-side divs the same height?

The Fiddle

HTML

<div class="container">

    <div class="left-column">

    </div>

    <div class="right-column">
        <h1>Hello Kitty!</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
    </div>

</div>

CSS

.container {
    float: left;
    width: 100%;
    background-color: black;
    position: relative;
    left: 0;
}

.container:before,
.container:after {
    content: " ";
    display: table;
}

.container:after {
    clear: both;
}

.left-column {
    float: left;
    width: 30%;
    height: 100%;
    position: absolute;
    background: wheat;
}

.right-column {
    float: right;
    width: 70%;
    position: relative;
    padding: 0;
    margin: 0;
    background: rebeccapurple;            
}

Rails 4: List of available datatypes

Rails4 has some added datatypes for Postgres.

For example, railscast #400 names two of them:

Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.

Besides, you can also use cidr, inet and macaddr. For more information:

https://blog.engineyard.com/2013/new-in-rails-4

Android Layout Weight

i would suppose to set the EditTexts width to wrap_content and put the two buttons into a LinearLayout whose width is fill_parent and weight set to 1.

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

I added @Service before impl class and the error is gone.

@Service
public class FCSPAnalysisImpl implements FCSPAnalysis
{}

set dropdown value by text using jquery

For GOOGLE, GOOGLEDOWN, GOOGLEUP i.e similar kind of value you can try below code

   $("#HowYouKnow option:contains('GOOGLE')").each(function () {

                        if($(this).html()=='GOOGLE'){
                            $(this).attr('selected', 'selected');
                        }
                    });

In this way,number of loop iteration can be reduced and will work in all situation.

jQuery - Redirect with post data

This would redirect with posted data

$(function() {
       $('<form action="url.php" method="post"><input type="hidden" name="name" value="value1"></input></form>').appendTo('body').submit().remove();
    });

    }

the .submit() function does the submit to url automatically
the .remove() function kills the form after submitting

How to detect shake event with android?

Do the following:

private float xAccel, yAccel, zAccel;
private float xPreviousAccel, yPreviousAccel, zPreviousAccel;
private boolean firstUpdate = true;
private final float shakeThreshold = 1.5f;
private boolean shakeInitiated = false;
SensorEventListener mySensorEventListener;
SensorManager mySensorManager;

Put this in onCreate method.

mySensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mySensorManager.registerListener(mySensorEventListener,
            mySensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
            SensorManager.SENSOR_DELAY_NORMAL);

And now the main part.

private boolean isAccelerationChanged() {
    float deltaX = Math.abs(xPreviousAccel - xAccel);
    float deltaY = Math.abs(yPreviousAccel - yAccel);
    float deltaZ = Math.abs(zPreviousAccel - zAccel);
    return (deltaX > shakeThreshold && deltaY > shakeThreshold)
            || (deltaX > shakeThreshold && deltaZ > shakeThreshold)
            || (deltaY > shakeThreshold && deltaZ > shakeThreshold);
}

private void updateAccelParameters(float xNewAccel, float yNewAccel, float zNewAccel) {
    if (firstUpdate) {
        xPreviousAccel = xNewAccel;
        yPreviousAccel = yNewAccel;
        zPreviousAccel = zNewAccel;
        firstUpdate = false;
    }else{
        xPreviousAccel = xAccel;
        yPreviousAccel = yAccel;
        zPreviousAccel = zAccel;
    }
    xAccel = xNewAccel;
    yAccel = yNewAccel;
    zAccel = zNewAccel;
}

private void executeShakeAction() {
    //this method is called when devices shakes
}

public void onSensorChanged(SensorEvent se) {
    updateAccelParameters(se.values[0], se.values[1], se.values[2]);
    if ((!shakeInitiated) && isAccelerationChanged()) {
        shakeInitiated = true;
    }else if ((shakeInitiated) && isAccelerationChanged()){
        executeShakeAction();
    }else if((shakeInitiated) && (!isAccelerationChanged())){
        shakeInitiated = false;
    }
}

public void onAccuracyChanged(Sensor sensor, int accuracy) {
    //setting the accuracy
}

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You can still use the textmode and force the linefeed-newline with the keyword argument newline

f = open("./foo",'w',newline='\n')

Tested with Python 3.4.2.

Edit: This does not work in Python 2.7.

Javascript: Unicode string to hex

how do you get "\u6f22\u5b57" from ?? in JavaScript?

These are JavaScript Unicode escape sequences e.g. \u12AB. To convert them, you could iterate over every code unit in the string, call .toString(16) on it, and go from there.

However, it is more efficient to also use hexadecimal escape sequences e.g. \xAA in the output wherever possible.

Also note that ASCII symbols such as A, b, and - probably don’t need to be escaped.

I’ve written a small JavaScript library that does all this for you, called jsesc. It has lots of options to control the output.

Here’s an online demo of the tool in action: http://mothereff.in/js-escapes#1%E6%BC%A2%E5%AD%97


Your question was tagged as utf-8. Reading the rest of your question, UTF-8 encoding/decoding didn’t seem to be what you wanted here, but in case you ever need it: use utf8.js (online demo).

What is the purpose of backbone.js?

Backbone.js is a JavaScript framework that helps you organize your code. It is literally a backbone upon which you build your application. It doesn't provide widgets (like jQuery UI or Dojo).

It gives you a cool set of base classes that you can extend to create clean JavaScript code that interfaces with RESTful endpoints on your server.

Image height and width not working?

You have a class on your CSS that is overwriting your width and height, the class reads as such:

.postItem img {
    height: auto;
    width: 450px;
}

Remove that and your width/height properties on the img tag should work.

vertical alignment of text element in SVG

After looking at the SVG Recommendation I've come to the understanding that the baseline properties are meant to position text relative to other text, especially when mixing different fonts and or languages. If you want to postion text so that it's top is at y then you need use dy = "y + the height of your text".

How to dynamically change a web page's title?

Update: as per the comments and reference on SearchEngineLand most web crawlers will index the updated title. Below answer is obsolete, but the code is still applicable.

You can just do something like, document.title = "This is the new page title.";, but that would totally defeat the purpose of SEO. Most crawlers aren't going to support javascript in the first place, so they will take whatever is in the element as the page title.

If you want this to be compatible with most of the important crawlers, you're going to need to actually change the title tag itself, which would involve reloading the page (PHP, or the like). You're not going to be able to get around that, if you want to change the page title in a way that a crawler can see.

Can I get the name of the current controller in the view?

If you want to use all stylesheet in your app just adds this line in application.html.erb. Insert it inside <head> tag

  <%= stylesheet_link_tag  controller.controller_name , media: 'all', 'data-turbolinks-track': 'reload' %>

Also, to specify the same class CSS on a different controller
Add this line in the body of application.html.erb

  <body class="<%= controller.controller_name %>-<%= controller.action_name %>">

So, now for example I would like to change the p tag in 'home' controller and 'index' action. Inside index.scss file adds.

.nameOfController-nameOfAction <tag> { }

 .home-index p {
        color:red !important;
      }

What is the difference between an Instance and an Object?

Regarding the difference between an object and an instance, I do not think there is any consensus.

It looks to me like people change it pretty much interchangeably, in papers, blog posts, books or conversations.

As for me, the way I see it is, an object is a generic and alive entity in the memory, specified by the language it is used in. Just like the Object class in Java. We do not much care its type, or anything else associated with it, whether it is managed by a container or not.

An instance is an object but associated with a type, as in this method accepts Foo instances, or you can not put Animal instances in an instance of a List of Vehicles.

objects for example have locks associated with them, not instances, whereas instances have methods. objects are garbage collected, not instances.

But as I said, this is only how I see it, and I do not think there is any organisation we can refer to for a standard definition between them and everyone will pretty much have their slightly different understanding / definitions (of course within limits).

How to convert a string into double and vice versa?

from this example here, you can see the the conversions both ways:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);

OpenSSL: unable to verify the first certificate for Experian URL

The first error message is telling you more about the problem:

verify error:num=20:unable to get local issuer certificate

The issuing certificate authority of the end entity server certificate is

VeriSign Class 3 Secure Server CA - G3

Look closely in your CA file - you will not find this certificate since it is an intermediary CA - what you found was a similar-named G3 Public Primary CA of VeriSign.

But why does the other connection succeed, but this one doesn't? The problem is a misconfiguration of the servers (see for yourself using the -debug option). The "good" server sends the entire certificate chain during the handshake, therefore providing you with the necessary intermediate certificates.

But the server that is failing sends you only the end entity certificate, and OpenSSL is not capable of downloading the missing intermediate certificate "on the fly" (which would be possible by interpreting the Authority Information Access extension). Therefore your attempt fails using s_client but it would succeed nevertheless if you browse to the same URL using e.g. FireFox (which does support the "certificate discovery" feature).

Your options to solve the problem are either fixing this on the server side by making the server send the entire chain, too, or by passing the missing intermediate certificate to OpenSSL as a client-side parameter.

Scheduling Python Script to run every hour accurately

the simplest option I can suggest is using the schedule library.

In your question, you said "I will need to run a function once every hour" the code to do this is very simple:

    import schedule

    def thing_you_wanna_do():
        ...
        ...
        return


    schedule.every().hour.do(thing_you_wanna_do)

    while True:
        schedule.run_pending()

you also asked how to do something at a certain time of the day some examples of how to do this are:

    import schedule


    def thing_you_wanna_do():
        ...
        ...
        return


    schedule.every().day.at("10:30").do(thing_you_wanna_do)
    schedule.every().monday.do(thing_you_wanna_do)
    schedule.every().wednesday.at("13:15").do(thing_you_wanna_do)
    # If you would like some randomness / variation you could also do something like this
    schedule.every(1).to(2).hours.do(thing_you_wanna_do)

    while True:
        schedule.run_pending()

90% of the code used is the example code of the schedule library. Happy scheduling!

Java generics - why is "extends T" allowed but not "implements T"?

It may be that the base type is a generic parameter, so the actual type may be an interface of a class. Consider:

class MyGen<T, U extends T> {

Also from client code perspective interfaces are almost indistinguishable from classes, whereas for subtype it is important.

How can I have Github on my own server?

I'm quite surprised nobody mentioned the open-source project gogs (http://gogs.io) or a derived fork of it called gitea (http://gitea.io) which basically offers the same what gitlab does, but with minimal system resources (low footprint), being perfect to run in a Raspberry Pi for example. Installation and maintenance is also way simpler.

How can I commit files with git?

It looks like all of the edits are already a part of the index. So to commit just use the commit command

git commit -m "My Commit Message"

Looking at your messages though my instinct says that you probably don't want the cache files to be included in your depot. Especially if it something that is built on the fly when running your program. If so then you should add the following line to your .gitignore file

httpdocs/newsite/manifest/cache/*

Using Thymeleaf when the value is null

you can use this solution it is working for me

<span th:text="${#objects.nullSafe(doctor?.cabinet?.name,'')}"></span>

How can I remove a character from a string using JavaScript?

return this.substr(0, index) + char + this.substr(index + char.length);

char.length is zero. You need to add 1 in this case in order to skip character.

Set Memory Limit in htaccess

In your .htaccess you can add:

PHP 5.x

<IfModule mod_php5.c>
    php_value memory_limit 64M
</IfModule>

PHP 7.x

<IfModule mod_php7.c>
    php_value memory_limit 64M
</IfModule>

If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

Read more on http://support.tigertech.net/php-value

How do I preserve line breaks when getting text from a textarea?

The easiest solution is to simply style the element you're inserting the text into with the following CSS property:

white-space: pre-wrap;

This property causes whitespace and newlines within the matching elements to be treated in the same way as inside a <textarea>. That is, consecutive whitespace is not collapsed, and lines are broken at explicit newlines (but are also wrapped automatically if they exceed the width of the element).

Given that several of the answers posted here so far have been vulnerable to HTML injection (e.g. because they assign unescaped user input to innerHTML) or otherwise buggy, let me give an example of how to do this safely and correctly, based on your original code:

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.append(postText);_x000D_
  var card = document.createElement('div');_x000D_
  card.append(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.prepend(card);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Note that, like your original code, the snippet above uses append() and prepend(). As of this writing, those functions are still considered experimental and not fully supported by all browsers. If you want to be safe and remain compatible with older browsers, you can substitute them pretty easily as follows:

  • element.append(otherElement) can be replaced with element.appendChild(otherElement);
  • element.prepend(otherElement) can be replaced with element.insertBefore(otherElement, element.firstChild);
  • element.append(stringOfText) can be replaced with element.appendChild(document.createTextNode(stringOfText));
  • element.prepend(stringOfText) can be replaced with element.insertBefore(document.createTextNode(stringOfText), element.firstChild);
  • as a special case, if element is empty, both element.append(stringOfText) and element.prepend(stringOfText) can simply be replaced with element.textContent = stringOfText.

Here's the same snippet as above, but without using append() or prepend():

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
  white-space: pre-wrap;  /* <-- THIS PRESERVES THE LINE BREAKS */_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_


Ps. If you really want to do this without using the CSS white-space property, an alternative solution would be to explicitly replace any newline characters in the text with <br> HTML tags. The tricky part is that, to avoid introducing subtle bugs and potential security holes, you have to first escape any HTML metacharacters (at a minimum, & and <) in the text before you do this replacement.

Probably the simplest and safest way to do that is to let the browser handle the HTML-escaping for you, like this:

var post = document.createElement('p');
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');

_x000D_
_x000D_
document.getElementById('post-button').addEventListener('click', function () {_x000D_
  var post = document.createElement('p');_x000D_
  var postText = document.getElementById('post-text').value;_x000D_
  post.textContent = postText;_x000D_
  post.innerHTML = post.innerHTML.replace(/\n/g, '<br>\n');  // <-- THIS FIXES THE LINE BREAKS_x000D_
  var card = document.createElement('div');_x000D_
  card.appendChild(post);_x000D_
  var cardStack = document.getElementById('card-stack');_x000D_
  cardStack.insertBefore(card, cardStack.firstChild);_x000D_
});
_x000D_
#card-stack p {_x000D_
  background: #ddd;_x000D_
}_x000D_
textarea {_x000D_
  width: 100%;_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="8" placeholder="What's up?" required>Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea><br>_x000D_
<input type="button" id="post-button" value="Post!">_x000D_
<div id="card-stack"></div>
_x000D_
_x000D_
_x000D_

Note that, while this will fix the line breaks, it won't prevent consecutive whitespace from being collapsed by the HTML renderer. It's possible to (sort of) emulate that by replacing some of the whitespace in the text with non-breaking spaces, but honestly, that's getting rather complicated for something that can be trivially solved with a single line of CSS.

Why does sudo change the PATH?

Secure_path is your friend, but if you want to exempt yourself from secure_path just do

sudo visudo

And append

Defaults exempt_group=your_goup

If you want to exempt a bunch of users create a group, add all the users to it, and use that as your exempt_group. man 5 sudoers for more.

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

java.lang.IllegalStateException: The specified child already has a parent

This solution can help :

public class FragmentItem extends Android.Support.V4.App.Fragment
{
    View rootView;
    TextView textView;

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView != null) 
        {
            ViewGroup parent = (ViewGroup)rootView.Parent;
            parent.RemoveView(rootView);
        } else {
            rootView = inflater.Inflate(Resource.Layout.FragmentItem, container, false);
            textView = rootView.FindViewById<TextView>(Resource.Id.textViewDisplay);            
        }
        return rootView;
    }
}

How to open a WPF Popup when another control is clicked, using XAML markup only?

I had some issues with the MouseDown part of this, but here is some code that might get your started.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Control VerticalAlignment="Top">
            <Control.Template>
                <ControlTemplate>
                    <StackPanel>
                    <TextBox x:Name="MyText"></TextBox>
                    <Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
                        <Border Background="Red">
                            <TextBlock>Test Popup Content</TextBlock>
                        </Border>
                    </Popup>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Control.Template>
        </Control>
    </Grid>
</Window>

Calculating how many days are between two dates in DB2?

It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,

So your Query will be

select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';

How to convert MySQL time to UNIX timestamp using PHP?

You can mysql's UNIX_TIMESTAMP function directly from your query, here is an example:

SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');

Similarly, you can pass in the date/datetime field:

SELECT UNIX_TIMESTAMP(yourField);

How do you use variables in a simple PostgreSQL script?

Building on @nad2000's answer and @Pavel's answer here, this is where I ended up for my Flyway migration scripts. Handling for scenarios where the database schema was manually modified.

DO $$
BEGIN
    IF NOT EXISTS(
        SELECT TRUE FROM pg_attribute 
        WHERE attrelid = (
            SELECT c.oid
            FROM pg_class c
            JOIN pg_namespace n ON n.oid = c.relnamespace
            WHERE 
                n.nspname = CURRENT_SCHEMA() 
                AND c.relname = 'device_ip_lookups'
            )
        AND attname = 'active_date'
        AND NOT attisdropped
        AND attnum > 0
        )
    THEN
        RAISE NOTICE 'ADDING COLUMN';        
        ALTER TABLE device_ip_lookups
            ADD COLUMN active_date TIMESTAMP;
    ELSE
        RAISE NOTICE 'SKIPPING, COLUMN ALREADY EXISTS';
    END IF;
END $$;

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

How do I add my new User Control to the Toolbox or a new Winform?

One way to get this error is trying to add a usercontrol to a form while the project is set to compile as x64. Visual Studio throws the unhelpful: "Failed to load toolbox item . It will be removed from the toolbox."

Workaround is to design with "Any CPU" and compile to x64 as necessary.

Reference: https://support.microsoft.com/en-us/kb/963017

How do you create a REST client for Java?

I am currently using https://github.com/kevinsawicki/http-request I like their simplicity and the way examples are shown, but mostly I was sold when I read:

What are the dependencies?

None. The goal of this library is to be a single class class with some inner static classes. The test project does require Jetty in order to test requests against an actual HTTP server implementation.

which sorted out some problems on a java 1.6 project. As for decoding json into objects gson is just invincible :)

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

for Xcode 8:

What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.

Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.

I once saved over 50GB doing this since I did so much testing on older iOS versions.

How to Handle Button Click Events in jQuery?

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

<script>
$(document).ready(function(){
  $("#button").click(function(){
    alert("Hello");
  });
});
</script>

<input type="button" id="button" value="Click me">

Get MAC address using shell script

Observe that the interface name and the MAC address are the first and last fields on a line with no leading whitespace.

If one of the indented lines contains inet addr: the latest interface name and MAC address should be printed.

ifconfig -a |
awk '/^[a-z]/ { iface=$1; mac=$NF; next }
    /inet addr:/ { print iface, mac }'

Note that multiple interfaces could meet your criteria. Then, the script will print multiple lines. (You can add ; exit just before the final closing brace if you always only want to print the first match.)

jquery <a> tag click event

That's because your hidden fields have duplicate IDs, so jQuery only returns the first in the set. Give them classes instead, like .uid and grab them via:

var uids = $(".uid").map(function() {
    return this.value;
}).get();

Demo: http://jsfiddle.net/karim79/FtcnJ/

EDIT: say your output looks like the following (notice, IDs have changed to classes)

<fieldset><legend>John Smith</legend>
<img src='foo.jpg'/><br>
<a href="#" class="aaf">add as friend</a>
<input name="uid" type="hidden" value='<?php echo $row->uid;?>' class="uid">
</fieldset>

You can target the 'uid' relative to the clicked anchor like this:

$("a.aaf").click(function() {
    alert($(this).next('.uid').val());
});

Important: do not have any duplicate IDs. They will cause problems. They are invalid, bad and you should not do it.

Android Drawing Separator/Divider Line in Layout?

I usually use this code to add horizontal line:

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@android:color/darker_gray"/>

To add vertical separator, switch the layout_width and layout_height values

How to get current route in react-router 2.0.0-rc5

If you use the history,then Router put everything into the location from the history,such as:

this.props.location.pathname;
this.props.location.query;

get it?

JavaScript before leaving the page

In order to have a popop with Chrome 14+, you need to do the following :

jQuery(window).bind('beforeunload', function(){
    return 'my text';
});

The user will be asked if he want to stay or leave.

JavaScript .replace only replaces first Match

The same, if you need "generic" regex from string :

_x000D_
_x000D_
const textTitle = "this is a test";_x000D_
const regEx = new RegExp(' ', "g");_x000D_
const result = textTitle.replace(regEx , '%20');_x000D_
console.log(result); // "this%20is%20a%20test" will be a result_x000D_
    
_x000D_
_x000D_
_x000D_

Is it possible to set the stacking order of pseudo-elements below their parent element?

I know this question is ancient and has an accepted answer, but I found a better solution to the problem. I am posting it here so I don't create a duplicate question, and the solution is still available to others.

Switch the order of the elements. Use the :before pseudo-element for the content that should be underneath, and adjust margins to compensate. The margin cleanup can be messy, but the desired z-index will be preserved.

I've tested this with IE8 and FF3.6 successfully.

RESTful URL design for search

There are a lot of good options for your case here. Still you should considering using the POST body.

The query string is perfect for your example, but if you have something more complicated, e.g. an arbitrary long list of items or boolean conditionals, you might want to define the post as a document, that the client sends over POST.

This allows a more flexible description of the search, as well as avoids the Server URL length limit.

How to change the background color on a Java panel?

I think what he is trying to say is to use the getContentPane().setBackground(Color.the_Color_you_want_here)

but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)

Eg:

jPanel.setbackground(Color.BLUE)

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

How do I open a new window using jQuery?

Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.

Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/

It gives a great example on how to open a new window*.

If you wish to use raw javascript then this is what you're looking for:

window.open(URL,name,specs,replace)

As seen in http://www.w3schools.com/jsref/met_win_open.asp

What is the difference between call and apply?

The main difference is, using call, we can change the scope and pass arguments as normal, but apply lets you call it using arguments as an Array (pass them as an array). But in terms of what they to do in your code, they are pretty similar.

While the syntax of this function is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.

So as you see, there is not a big difference, but still, there are cases we prefer using call() or apply(). For example, look at the code below, which finding the smallest and largest number in an array from MDN, using the apply method:

// min/max number in an array
var numbers = [5, 6, 2, 3, 7];

// using Math.min/Math.max apply
var max = Math.max.apply(null, numbers); 
// This about equal to Math.max(numbers[0], ...)
// or Math.max(5, 6, ...)

var min = Math.min.apply(null, numbers)

So the main difference is just the way we passing the arguments:

Call:

function.call(thisArg, arg1, arg2, ...);

Apply:

function.apply(thisArg, [argsArray]);

application/x-www-form-urlencoded or multipart/form-data?

TL;DR

Summary; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use multipart/form-data. Otherwise, use application/x-www-form-urlencoded.


The MIME types you mention are the two Content-Type headers for HTTP POST requests that user-agents (browsers) must support. The purpose of both of those types of requests is to send a list of name/value pairs to the server. Depending on the type and amount of data being transmitted, one of the methods will be more efficient than the other. To understand why, you have to look at what each is doing under the covers.

For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be: 

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

According to the specification:

[Reserved and] non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character

That means that for each non-alphanumeric byte that exists in one of our values, it's going to take three bytes to represent it. For large binary files, tripling the payload is going to be highly inefficient.

That's where multipart/form-data comes in. With this method of transmitting name/value pairs, each pair is represented as a "part" in a MIME message (as described by other answers). Parts are separated by a particular string boundary (chosen specifically so that this boundary string does not occur in any of the "value" payloads). Each part has its own set of MIME headers like Content-Type, and particularly Content-Disposition, which can give each part its "name." The value piece of each name/value pair is the payload of each part of the MIME message. The MIME spec gives us more options when representing the value payload -- we can choose a more efficient encoding of binary data to save bandwidth (e.g. base 64 or even raw binary).

Why not use multipart/form-data all the time? For short alphanumeric values (like most web forms), the overhead of adding all of the MIME headers is going to significantly outweigh any savings from more efficient binary encoding.

MySQL skip first 10 results

If your table has ordering by id, you could easily done by:

select * from table where id > 10

Using CSS for a fade-in effect on page load

Looking forward to Web Animations in 2020.

_x000D_
_x000D_
async function moveToPosition(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        transform: `translateY(${el.getBoundingClientRect().top}px)`
      },
    ], {
      duration: durationInMs,
      easing: 'ease-in',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeIn(el, durationInMs) {
  return new Promise((resolve) => {
    const animation = el.animate([{
        opacity: '0'
      },
      {
        opacity: '0.5',
        offset: 0.5
      },
      {
        opacity: '1',
        offset: 1
      }
    ], {
      duration: durationInMs,
      easing: 'linear',
      iterations: 1,
      direction: 'normal',
      fill: 'forwards',
      delay: 0,
      endDelay: 0
    });
    animation.onfinish = () => resolve();
  });
}

async function fadeInSections() {
  for (const section of document.getElementsByTagName('section')) {
    await fadeIn(section, 200);
  }
}

window.addEventListener('load', async() => {
  await moveToPosition(document.getElementById('headerContent'), 500);
  await fadeInSections();
  await fadeIn(document.getElementsByTagName('footer')[0], 200);
});
_x000D_
body,
html {
  height: 100vh;
}

header {
  height: 20%;
}

.text-center {
  text-align: center;
}

.leading-none {
  line-height: 1;
}

.leading-3 {
  line-height: .75rem;
}

.leading-2 {
  line-height: .25rem;
}

.bg-black {
  background-color: rgba(0, 0, 0, 1);
}

.bg-gray-50 {
  background-color: rgba(249, 250, 251, 1);
}

.pt-12 {
  padding-top: 3rem;
}

.pt-2 {
  padding-top: 0.5rem;
}

.text-lightGray {
  color: lightGray;
}

.container {
  display: flex;
  /* or inline-flex */
  justify-content: space-between;
}

.container section {
  padding: 0.5rem;
}

.opacity-0 {
  opacity: 0;
}
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <link rel="icon" href="/favicon.ico" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="Web site created using create-snowpack-app" />
  <link rel="stylesheet" type="text/css" href="./assets/syles/index.css" />
</head>

<body>
  <header class="bg-gray-50">
    <div id="headerContent">
      <h1 class="text-center leading-none pt-2 leading-2">Hello</h1>
      <p class="text-center leading-2"><i>Ipsum lipmsum emus tiris mism</i></p>
    </div>
  </header>
  <div class="container">
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 1</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 2</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>

    <section class="opacity-0">
      <h2 class="text-center"><i>ipsum 3</i></h2>
      <p>Cras purus ante, dictum non ultricies eu, dapibus non tellus. Nam et ipsum nec nunc vestibulum efficitur nec nec magna. Proin sodales ex et finibus congue</p>
    </section>
  </div>
  <footer class="opacity-0">
    <h1 class="text-center leading-3 text-lightGray"><i>dictum non ultricies eu, dapibus non tellus</i></h1>
    <p class="text-center leading-3"><i>Ipsum lipmsum emus tiris mism</i></p>
  </footer>
</body>

</html>
_x000D_
_x000D_
_x000D_

How can I create basic timestamps or dates? (Python 3.4)

Ultimately you want to review the datetime documentation and become familiar with the formatting variables, but here are some examples to get you started:

import datetime

print('Timestamp: {:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Timestamp: {:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()))
print('Date now: %s' % datetime.datetime.now())
print('Date today: %s' % datetime.date.today())

today = datetime.date.today()
print("Today's date is {:%b, %d %Y}".format(today))

schedule = '{:%b, %d %Y}'.format(today) + ' - 6 PM to 10 PM Pacific'
schedule2 = '{:%B, %d %Y}'.format(today) + ' - 1 PM to 6 PM Central'
print('Maintenance: %s' % schedule)
print('Maintenance: %s' % schedule2)

The output:

Timestamp: 2014-10-18 21:31:12

Timestamp: 2014-Oct-18 21:31:12

Date now: 2014-10-18 21:31:12.318340

Date today: 2014-10-18

Today's date is Oct, 18 2014

Maintenance: Oct, 18 2014 - 6 PM to 10 PM Pacific

Maintenance: October, 18 2014 - 1 PM to 6 PM Central

Reference link: https://docs.python.org/3.4/library/datetime.html#strftime-strptime-behavior

(WAMP/XAMP) send Mail using SMTP localhost

I prefer using PHPMailer script to send emails from localhost as it lets me use my Gmail account as SMTP. You can find the PHPMailer from http://phpmailer.worxware.com/ . Help regarding how to use gmail as SMTP or any other SMTP can be found at http://www.mittalpatel.co.in/php_send_mail_from_localhost_using_gmail_smtp . Hope this helps!

Detect HTTP or HTTPS then force HTTPS in JavaScript

if (location.protocol == 'http:')
  location.href = location.href.replace(/^http:/, 'https:')

Error In PHP5 ..Unable to load dynamic library

(For Ubuntu users)

I had the same problem, but none of the answers above solved that. Here is how I solved the problem.

Open your php.ini file (mine was in /etc/php/7.3/cli/php.ini).

You may have something like this:

extension=pdo_mysql

Or maybe:

extension=/here/is/the/path/to/your/file/pdo_mysql.so

Add the following line before extension=pdo_mysql

extension=pdo

So, you will have:

extension=pdo
extension=pdo_mysql

It seems that the problem is (at least in my case) that we need to load pdo extension first to load the pdo_mysql extension.

Hope that helps!

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

Yes you can usually see what SOAP version is supported based on the WSDL.

Take a look at Demo web service WSDL. It has a reference to the soap12 namespace indicating it supports SOAP 1.2. If that was absent then you'd probably be safe assuming the service only supported SOAP 1.1.

How to exit when back button is pressed?

Why wouldn't the user just hit the home button? Then they can exit your app from any of your activities, not just a specific one.

If you are worried about your application continuing to do something in the background. Make sure to stop it in the relevant onPause and onStop commands (which will get triggered when the user presses Home).

If your issue is that you want the next time the user clicks on your app for it to start back at the beginning, I recommend putting some kind of menu item or UI button on the screen that takes the user back to the starting activity of your app. Like the twitter bird in the official twitter app, etc.

Programmatically switching between tabs within Swift

In a typical application there is a UITabBarController and it embeds 3 or more UIViewController as its tabs. In such a case if you subclassed a UITabBarController as YourTabBarController then you can set the selected index simply by:

selectedIndex = 1 // Displays 2nd tab. The index starts from 0.

In case you are navigating to YourTabBarController from any other view, then in that view controller's prepare(for segue:) method you can do:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
        if segue.identifier == "SegueToYourTabBarController" {
            if let destVC = segue.destination as? YourTabBarController {
                destVC.selectedIndex = 0
            }
        }

I am using this way of setting tab with Xcode 10 and Swift 4.2.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Try jQuery's delegate() function, like so:

$(document).ready(function(){
    $("div.custList table").delegate('tr', 'click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

A delegate works in the same way as live() except that live() cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.

Retrieve Button value with jQuery

try this for your button:

<input type="button" class="my_button" name="buttonName" value="buttonValue" />

Can multiple different HTML elements have the same ID if they're different elements?

SLaks answer is correct, but as an addendum note that the x/html specs specify that all ids must be unique within a (single) html document. Although it's not exactly what the op asked, there could be valid instances where the same id is attached to different entities across multiple pages.

Example:

(served to modern browsers) article#main-content {styled one way}
(served to legacy) div#main-content {styled another way}

Probably an antipattern though. Just leaving here as a devil's advocate point.

How do I use the includes method in lodash to check if an object is in the collection?

The includes (formerly called contains and include) method compares objects by reference (or more precisely, with ===). Because the two object literals of {"b": 2} in your example represent different instances, they are not equal. Notice:

({"b": 2} === {"b": 2})
> false

However, this will work because there is only one instance of {"b": 2}:

var a = {"a": 1}, b = {"b": 2};
_.includes([a, b], b);
> true

On the other hand, the where(deprecated in v4) and find methods compare objects by their properties, so they don't require reference equality. As an alternative to includes, you might want to try some (also aliased as any):

_.some([{"a": 1}, {"b": 2}], {"b": 2})
> true

C# Copy a file to another location with a different name

If you want to use only FileInfo class try this

             string oldPath = @"C:\MyFolder\Myfile.xyz";
             string newpath = @"C:\NewFolder\";
             string newFileName = "new file name";
             FileInfo f1 = new FileInfo(oldPath);
           if(f1.Exists)
             {
                if(!Directory.Exists(newpath))
                {
                    Directory.CreateDirectory(newpath); 
                }
                 f1.CopyTo(string.Format("{0}{1}{2}", newpath, newFileName, f1.Extension));
             }

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

Explanation of BASE terminology

It has to do with BASE: the BASE jumper kind is always Basically Available (to new relationships), in a Soft state (none of his relationship last very long) and Eventually consistent (one day he will get married).

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

SELECT o.OrderID
CASE WHEN o.NegotiatedPrice > o.SuggestedPrice THEN
 o.NegotiatedPrice
ELSE
 o.SuggestedPrice
END AS Price

How to catch an Exception from a thread

Use Callable instead of Thread, then you can call Future#get() which throws any exception that the Callable threw.

Catching KeyboardInterrupt in Python during program shutdown

You could ignore SIGINTs after shutdown starts by calling signal.signal(signal.SIGINT, signal.SIG_IGN) before you start your cleanup code.

PHP MySQL Query Where x = $variable

You have to do this to echo it:

echo $row['note'];

(The data is coming as an array)

ImportError: No module named xlsxwriter

Even if it looks like the module is installed, as far as Python is concerned it isn't since it throws that exception.

Try installing the module again using one of the installation methods shown in the XlsxWriter docs and look out for any installation errors.

If there are none then run a sample program like the following:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Hello world')

workbook.close()

SpringApplication.run main method

You need to run Application.run() because this method starts whole Spring Framework. Code below integrates your main() with Spring Boot.

Application.java

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

ReconTool.java

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        main(args);
    }

    public static void main(String[] args) {
        // Recon Logic
    }
}

Why not SpringApplication.run(ReconTool.class, args)

Because this way spring is not fully configured (no component scan etc.). Only bean defined in run() is created (ReconTool).

Example project: https://github.com/mariuszs/spring-run-magic

JavaScript function to add X months to a date

As demonstrated by many of the complicated, ugly answers presented, Dates and Times can be a nightmare for programmers using any language. My approach is to convert dates and 'delta t' values into Epoch Time (in ms), perform any arithmetic, then convert back to "human time."

// Given a number of days, return a Date object
//   that many days in the future. 
function getFutureDate( days ) {

    // Convert 'days' to milliseconds
    var millies = 1000 * 60 * 60 * 24 * days;

    // Get the current date/time
    var todaysDate = new Date();

    // Get 'todaysDate' as Epoch Time, then add 'days' number of mSecs to it
    var futureMillies = todaysDate.getTime() + millies;

    // Use the Epoch time of the targeted future date to create
    //   a new Date object, and then return it.
    return new Date( futureMillies );
}

// Use case: get a Date that's 60 days from now.
var twoMonthsOut = getFutureDate( 60 );

This was written for a slightly different use case, but you should be able to easily adapt it for related tasks.

EDIT: Full source here!

How can I create a simple message box in Python?

A recent message box version is the prompt_box module. It has two packages: alert and message. Message gives you greater control over the box, but takes longer to type up.

Example Alert code:

import prompt_box

prompt_box.alert('Hello') #This will output a dialog box with title Neutrino and the 
#text you inputted. The buttons will be Yes, No and Cancel

Example Message code:

import prompt_box

prompt_box.message('Hello', 'Neutrino', 'You pressed yes', 'You pressed no', 'You 
pressed cancel') #The first two are text and title, and the other three are what is 
#printed when you press a certain button

How do I get the size of a java.sql.ResultSet?

I got an exception when using rs.last()

if(rs.last()){
    rowCount = rs.getRow(); 
    rs.beforeFirst();
}

:

java.sql.SQLException: Invalid operation for forward only resultset

it's due to by default it is ResultSet.TYPE_FORWARD_ONLY, which means you can only use rs.next()

the solution is:

stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY); 

Java Error: illegal start of expression

Remove the public keyword from int[] locations={1,2,3};. An access modifier isn't allowed inside a method, as its accessbility is defined by its method scope.

If your goal is to use this reference in many a method, you might want to move the declaration outside the method.

How to encode URL to avoid special characters in Java?

If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec

String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);

What is the garbage collector in Java?

The garbage collector allows your computer to simulate a computer with infinite memory. The rest is just mechanism.

It does this by detecting when chunks of memory are no longer accessible from your code, and returning those chunks to the free store.

EDIT: Yes, the link is for C#, but C# and Java are identical in this regard.

How to change the bootstrap primary color?

Since Bootstrap 4 you can easily change the primary color of your Bootstrap by downloading a simple CSS file on BootstrapColor.net. You don't need to know SASS and the CSS file is ready to use for your website. You can choose the color you want like blue, indigo, purple, pink, red, orange, yellow, green, teal or cyan color.

How to get the ASCII value of a character

You are looking for:

ord()

How do I select elements of an array given condition?

IMO OP does not actually want np.bitwise_and() (aka &) but actually wants np.logical_and() because they are comparing logical values such as True and False - see this SO post on logical vs. bitwise to see the difference.

>>> x = array([5, 2, 3, 1, 4, 5])
>>> y = array(['f','o','o','b','a','r'])
>>> output = y[np.logical_and(x > 1, x < 5)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
      dtype='|S1')

And equivalent way to do this is with np.all() by setting the axis argument appropriately.

>>> output = y[np.all([x > 1, x < 5], axis=0)] # desired output is ['o','o','a']
>>> output
array(['o', 'o', 'a'],
      dtype='|S1')

by the numbers:

>>> %timeit (a < b) & (b < c)
The slowest run took 32.97 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 1.15 µs per loop

>>> %timeit np.logical_and(a < b, b < c)
The slowest run took 32.59 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 1.17 µs per loop

>>> %timeit np.all([a < b, b < c], 0)
The slowest run took 67.47 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 5.06 µs per loop

so using np.all() is slower, but & and logical_and are about the same.

String comparison in bash. [[: not found

[[ is a bash-builtin. Your /bin/bash doesn't seem to be an actual bash.

From a comment:

Add #!/bin/bash at the top of file

How to make a function wait until a callback has been called using node.js

Since node 4.8.0 you are able to use the feature of ES6 called generator. You may follow this article for deeper concepts. But basically you can use generators and promises to get this job done. I'm using bluebird to promisify and manage the generator.

Your code should be fine like the example below.

const Promise = require('bluebird');

function* getResponse(query) {
  const r = yield new Promise(resolve => myApi.exec('SomeCommand', resolve);
  return r;
}

Promise.coroutine(getResponse)()
  .then(response => console.log(response));

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

Angularjs - display current date

A solution similar to the one of @Nick G. by using filter, but make the parameter meaningful:

Implement an filter called relativedate which calculate the date relative to current date by the given parameter as diff. As a result, (0 | relativedate) means today and (1 | relativedate) means tomorrow.

.filter('relativedate', ['$filter', function ($filter) {
  return function (rel, format) {
    let date = new Date();
    date.setDate(date.getDate() + rel);
    return $filter('date')(date, format || 'yyyy-MM-dd')
  };
}]);

and your html:

<div ng-app="myApp">
    <div>Yesterday: {{-1 | relativedate}}</div>
    <div>Today: {{0 | relativedate}}</div>
    <div>Tomorrow: {{1 | relativedate}}</div>
</div>

How do I check out an SVN project into Eclipse as a Java project?

If it wasn't checked in as a Java Project, you can add the java nature as shown here.

Chrome ignores autocomplete="off"

Chrome version 34 now ignores the autocomplete=off, see this.

Lots of discussion on whether this is a good thing or a bad thing? Whats your views?

Python: Generate random number between x and y which is a multiple of 5

Create an integer random between e.g. 1-11 and multiply it by 5. Simple math.

import random
for x in range(20):
  print random.randint(1,11)*5,
print

produces e.g.

5 40 50 55 5 15 40 45 15 20 25 40 15 50 25 40 20 15 50 10

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

javascript - match string against the array of regular expressions

So we make a function that takes in a literal string, and the array we want to look through. it returns a new array with the matches found. We create a new regexp object inside this function and then execute a String.search on each element element in the array. If found, it pushes the string into a new array and returns.

// literal_string: a regex search, like /thisword/ig
// target_arr: the array you want to search /thisword/ig for.

function arr_grep(literal_string, target_arr) {
  var match_bin = [];
  // o_regex: a new regex object.
  var o_regex = new RegExp(literal_string);
  for (var i = 0; i < target_arr.length; i++) {
    //loop through array. regex search each element.
    var test = String(target_arr[i]).search(o_regex);
    if (test > -1) {
    // if found push the element@index into our matchbin.
    match_bin.push(target_arr[i]);
    }
  }
  return match_bin;
}

// arr_grep(/.*this_word.*/ig, someArray)

How to force the browser to reload cached CSS and JavaScript files

Small improvement from existing answers...

Using a random number or session id would cause it to reload on each request. Ideally, we may need to change only if some code changes were done in any JavaScript or CSS file.

When using a common JSP file as a template to many other JSP and JavaScript files, add the below in a common JSP file

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var = "version" scope = "application" value = "1.0.0" />

Now use the above variable in all locations as below in your JavaScript file inclusions.

<script src='<spring:url value="/js/myChangedFile.js?version=${version}"/>'></script>

Advantages:

  1. This approach will help you in changing version number at one location only.
  1. Maintaining a proper version number (usually build/release number) will help you to check/verify your code changes being deployed properly (from developer console of the browser).

Another useful tip:

If you are using the Chrome browser, you can disable caching when Dev Tools is open. In Chrome, hit F12 ? F1 and scroll to Settings ? Preferences ? Network ? *Disable caching (while DevTools is open)

Chrome DevTools

Color different parts of a RichTextBox string

Selecting text as said from somebody, may the selection appear momentarily. In Windows Forms applications there is no other solutions for the problem, but today I found a bad, working, way to solve: you can put a PictureBox in overlapping to the RichtextBox with the screenshot of if, during the selection and the changing color or font, making it after reappear all, when the operation is complete.

Code is here...

//The PictureBox has to be invisible before this, at creation
//tb variable is your RichTextBox
//inputPreview variable is your PictureBox
using (Graphics g = inputPreview.CreateGraphics())
{
    Point loc = tb.PointToScreen(new Point(0, 0));
    g.CopyFromScreen(loc, loc, tb.Size);
    Point pt = tb.GetPositionFromCharIndex(tb.TextLength);
    g.FillRectangle(new SolidBrush(Color.Red), new Rectangle(pt.X, 0, 100, tb.Height));
}
inputPreview.Invalidate();
inputPreview.Show();
//Your code here (example: tb.Select(...); tb.SelectionColor = ...;)
inputPreview.Hide();

Better is to use WPF; this solution isn't perfect, but for Winform it works.

How do I get the width and height of a HTML5 canvas?

I had a problem because my canvas was inside of a container without ID so I used this jquery code below

$('.cropArea canvas').width()

How to remove foreign key constraint in sql server?

If you find yourself in a situation where the FK name of a table has been auto-generated and you aren't able to view what it exactly is (in the case of not having rights to a database for instance) you could try something like this:

DECLARE @table NVARCHAR(512), @sql NVARCHAR(MAX);
SELECT @table = N'dbo.Table';
SELECT @sql = 'ALTER TABLE ' + @table
    + ' DROP CONSTRAINT ' + NAME + ';'
    FROM sys.foreign_keys
    WHERE [type] = 'F'
    AND [parent_object_id] = OBJECT_ID(@table);
EXEC sp_executeSQL @sql;

Build up a stored proc which drops the constraint of the specified table without specifying the actual FK name. It drops the constraint where the object [type] is equal to F (Foreign Key constraint).

Note: if there are multiple FK's in the table it will drop them all. So this solution works best if the table you are targeting has just one FK.

How to set a timeout on a http.request() in Node?

There is simpler method.

Instead of using setTimeout or working with socket directly,
We can use 'timeout' in the 'options' in client uses

Below is code of both server and client, in 3 parts.

Module and options part:

'use strict';

// Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js

const assert = require('assert');
const http = require('http');

const options = {
    host: '127.0.0.1', // server uses this
    port: 3000, // server uses this

    method: 'GET', // client uses this
    path: '/', // client uses this
    timeout: 2000 // client uses this, timesout in 2 seconds if server does not respond in time
};

Server part:

function startServer() {
    console.log('startServer');

    const server = http.createServer();
    server
            .listen(options.port, options.host, function () {
                console.log('Server listening on http://' + options.host + ':' + options.port);
                console.log('');

                // server is listening now
                // so, let's start the client

                startClient();
            });
}

Client part:

function startClient() {
    console.log('startClient');

    const req = http.request(options);

    req.on('close', function () {
        console.log("got closed!");
    });

    req.on('timeout', function () {
        console.log("timeout! " + (options.timeout / 1000) + " seconds expired");

        // Source: https://github.com/nodejs/node/blob/master/test/parallel/test-http-client-timeout-option.js#L27
        req.destroy();
    });

    req.on('error', function (e) {
        // Source: https://github.com/nodejs/node/blob/master/lib/_http_outgoing.js#L248
        if (req.connection.destroyed) {
            console.log("got error, req.destroy() was called!");
            return;
        }

        console.log("got error! ", e);
    });

    // Finish sending the request
    req.end();
}


startServer();

If you put all the above 3 parts in one file, "a.js", and then run:

node a.js

then, output will be:

startServer
Server listening on http://127.0.0.1:3000

startClient
timeout! 2 seconds expired
got closed!
got error, req.destroy() was called!

Hope that helps.

Toad for Oracle..How to execute multiple statements?

begin

insert into fiscal_year values(2001,'01-jan-2001','31-dec-2001');
insert into fiscal_year values(2002,'01-jan-2002','31-dec-2002');
insert into fiscal_year values(2003,'01-jan-2003','31-dec-2003');
insert into fiscal_year values(2004,'01-jan-2004','31-dec-2004');

end;

Use like this and then commit.

Jersey client: How to add a list as query parameter

If you are sending anything other than simple strings I would recommend using a POST with an appropriate request body, or passing the entire list as an appropriately encoded JSON string. However, with simple strings you just need to append each value to the request URL appropriately and Jersey will deserialize it for you. So given the following example endpoint:

@Path("/service/echo") public class MyServiceImpl {
    public MyServiceImpl() {
        super();
    }

    @GET
    @Path("/withlist")
    @Produces(MediaType.TEXT_PLAIN)
    public Response echoInputList(@QueryParam("list") final List<String> inputList) {
        return Response.ok(inputList).build();
    }
}

Your client would send a request corresponding to:

GET http://example.com/services/echo?list=Hello&list=Stay&list=Goodbye

Which would result in inputList being deserialized to contain the values 'Hello', 'Stay' and 'Goodbye'

Finding element in XDocument?

Elements() will only check direct children - which in the first case is the root element, in the second case children of the root element, hence you get a match in the second case. If you just want any matching descendant use Descendants() instead:

var query = from c in xmlFile.Descendants("Band") select c;

Also I would suggest you re-structure your Xml: The band name should be an attribute or element value, not the element name itself - this makes querying (and schema validation for that matter) much harder, i.e. something like this:

<Band>
  <BandProperties Name ="Doors" ID="222" started="1968" />
  <Description>regular Band<![CDATA[lalala]]></Description>
  <Last>1</Last>
  <Salary>2</Salary>
</Band>

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Try this. It's very easy:

driver.getPageSource().contains("text to search");

This really worked for me in Selenium WebDriver.

Key existence check in HashMap

You can also use the computeIfAbsent() method in the HashMap class.

In the following example, map stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100 and 200 to checking_account you can write:

HashMap<String, ArrayList<Integer>> map = new HashMap<>();
map.computeIfAbsent("checking_account", key -> new ArrayList<>())
   .add(100)
   .add(200);

This way you don't have to check to see if the key checking_account exists or not.

  • If it does not exist, one will be created and returned by the lambda expression.
  • If it exists, then the value for the key will be returned by computeIfAbsent().

Really elegant!

Sort ArrayList of custom Objects by property

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;

public class test {

public static class Person {
    public String name;
    public int id;
    public Date hireDate;

    public Person(String iname, int iid, Date ihireDate) {
        name = iname;
        id = iid;
        hireDate = ihireDate;
    }

    public String toString() {
        return name + " " + id + " " + hireDate.toString();
    }

    // Comparator
    public static class CompId implements Comparator<Person> {
        @Override
        public int compare(Person arg0, Person arg1) {
            return arg0.id - arg1.id;
        }
    }

    public static class CompDate implements Comparator<Person> {
        private int mod = 1;
        public CompDate(boolean desc) {
            if (desc) mod =-1;
        }
        @Override
        public int compare(Person arg0, Person arg1) {
            return mod*arg0.hireDate.compareTo(arg1.hireDate);
        }
    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub
    SimpleDateFormat df = new SimpleDateFormat("mm-dd-yyyy");
    ArrayList<Person> people;
    people = new ArrayList<Person>();
    try {
        people.add(new Person("Joe", 92422, df.parse("12-12-2010")));
        people.add(new Person("Joef", 24122, df.parse("1-12-2010")));
        people.add(new Person("Joee", 24922, df.parse("12-2-2010")));
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Collections.sort(people, new Person.CompId());
    System.out.println("BY ID");
    for (Person p : people) {
        System.out.println(p.toString());
    }

    Collections.sort(people, new Person.CompDate(false));
    System.out.println("BY Date asc");
    for (Person p : people) {
        System.out.println(p.toString());
    }
    Collections.sort(people, new Person.CompDate(true));
    System.out.println("BY Date desc");
    for (Person p : people) {
        System.out.println(p.toString());
    }

}

}

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

How do I programmatically determine operating system in Java?

If you're working in a security sensitive environment, then please read this through.

Please refrain from ever trusting a property obtained via the System#getProperty(String) subroutine! Actually, almost every property including os.arch, os.name, and os.version isn't readonly as you'd might expect — instead, they're actually quite the opposite.

First of all, any code with sufficient permission of invoking the System#setProperty(String, String) subroutine can modify the returned literal at will. However, that's not necessarily the primary issue here, as it can be resolved through the use of a so called SecurityManager, as described in greater detail over here.

The actual issue is that any user is able to edit these properties when running the JAR in question (through -Dos.name=, -Dos.arch=, etc.). A possible way to avoid tampering with the application parameters is by querying the RuntimeMXBean as shown here. The following code snippet should provide some insight into how this may be achieved.

RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();

for (String argument : arguments) {
    if (argument.startsWith("-Dos.name") {
        // System.getProperty("os.name") altered
    } else if (argument.startsWith("-Dos.arch") {
        // System.getProperty("os.arch") altered
    }
}

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

Target build x64 Target Server Hosting IIS 64 Bit

Right Click appPool hosting running the website/web application and set the enable 32 bit application = false.

enter image description here

Sum one number to every element in a list (or array) in Python

If you don't want list comprehensions:

a = [1,1,1,1,1]
b = []
for i in a:
    b.append(i+1)

What's the best way to store a group of constants that my program uses?

You probably could have them in a static class, with static read-only properties.

public static class Routes
{
    public static string SignUp => "signup";
}

Style input element to fill remaining width of its container

Very easy trick is using a CSS calc formula. All modern browsers, IE9, wide range of mobile browsers should support this.

<div style='white-space:nowrap'>
  <span style='display:inline-block;width:80px;font-weight:bold'>
    <label for='field1'>Field1</label>
  </span>
  <input id='field1' name='field1' type='text' value='Some text' size='30' style='width:calc(100% - 80px)' />
</div>

Android Studio - UNEXPECTED TOP-LEVEL EXCEPTION:

Hi all I had the same issue that was being caused by a duplicate support version 4 file that I had included while trying to get parse integrated. Deleted the extra inclusion from the libs directory and it works fine now!

Find if listA contains any elements not in listB

Get the difference of two lists using Any(). The Linq Any() function returns a boolean if a condition is met but you can use it to return the difference of two lists:

var difference = ListA.Where(a => !ListB.Any(b => b.ListItem == a.ListItem)).ToList();

Python: Pandas Dataframe how to multiply entire column with a scalar

Also it's possible to use numerical indeces with .iloc.

df.iloc[:,0]  *= -1

PHP function to get the subdomain of a URL

Try this...

$domain = 'en.example.com';
$tmp = explode('.', $domain);
$subdomain = current($tmp);
echo($subdomain);     // echo "en"

Cannot edit in read-only editor VS Code

I was experiencing this issue while using the SFTP extension in VSCode. In this case, all you have to do is right-click somewhere in the file and select 'edit in local'

enter image description here

enter image description here

enter image description here

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Javascript, viewing [object HTMLInputElement]

It's not because you are using alert, it will happen when use document.write() too. This problem generally arises when you name your id or class of any tag as same as any variable which you are using in you javascript code. Try by changing either the javascript variable name or by changing your tag's id/class name.

My code example: bank.html

<!doctype html>
<html>
<head>
    <title>Transaction Tracker</title>
    <script src="bank.js"></script> 
</head>
    <body>
        <div><button onclick="bitch()">Press me!</button></div>
    </body>
</html>

Javascript code: bank.js

function bitch(){ amt = 0;
var a = Math.random(); ran = Math.floor(a * 100);
return ran; }

function all(){
amt = amt + bitch(); document.write(amt + "
"); } setInterval(all,2000);

you can have a look and understand the concept from my code. Here i have used a variable named 'amt' in JS. You just try to run my code. It will work fine but as you put an [id="amt"](without square brackets) (which is a variable name in JS code )for div tag in body of html you will see the same error that you are talking about. So simple solution is to change either the variable name or the id or class name.

What does $_ mean in PowerShell?

I think the easiest way to think about this variable like input parameter in lambda expression in C#. I.e. $_ is similar to x in x => Console.WriteLine(x) anonymous function in C#. Consider following examples:

PowerShell:

1,2,3 | ForEach-Object {Write-Host $_}

Prints:

1
2
3

or

1,2,3 | Where-Object {$_ -gt 1}

Prints:

2
3

And compare this with C# syntax using LINQ:

var list = new List<int> { 1, 2, 3 };
list.ForEach( _ => Console.WriteLine( _ ));

Prints:

1
2
3

or

list.Where( _ => _ > 1)
    .ToList()
    .ForEach(s => Console.WriteLine(s));

Prints:

2
3

Refused to display 'url' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

I was facing this issue in Grafana and all I had to do was go to the config file and change allow_embedding to true and restart the server :)

Remove gutter space for a specific div only

Update : link for TWBS 3 getbootstrap.com/customize/#grid-system


Twitter Bootstrap offers a customize form to download all or some components with custom configuration.

You can use this form to download a grid without gutters, and it will be responsive - you only need the grid component and the responsive ones concerning the width.

Demo (jsfiddle) custom grid

If you know a little about LESS, then you can include the generated CSS in a selector of your choice.

/* LESS */
.some-thing {
    /* The custom grid
      ...
    */
}

If not, you should add this selector in front of each rule (not that much anyway).


If you know LESS and use the LESS scripts to manage your styles, you might want to use directly the Grid mixins v2 (github)

Grid mixins v3 (github)

How to disable XDebug

in xubuntu I totally disabled xdebug for the CLI with this...

sudo rm /etc/php5/cli/conf.d/*xdebug*

Read JSON data in a shell script

There is jq for parsing json on the command line:

 jq '.Body'

Visit this for jq: https://stedolan.github.io/jq/

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

How to convert text to binary code in JavaScript?

The other answers will work for most cases. But it's worth noting that charCodeAt() and related don't work with UTF-8 strings (that is, they throw errors if there are any characters outside the standard ASCII range). Here's a workaround.

// UTF-8 to binary
var utf8ToBin = function( s ){
    s = unescape( encodeURIComponent( s ) );
    var chr, i = 0, l = s.length, out = '';
    for( ; i < l; i ++ ){
        chr = s.charCodeAt( i ).toString( 2 );
        while( chr.length % 8 != 0 ){ chr = '0' + chr; }
        out += chr;
    }
    return out;
};

// Binary to UTF-8
var binToUtf8 = function( s ){
    var i = 0, l = s.length, chr, out = '';
    for( ; i < l; i += 8 ){
        chr = parseInt( s.substr( i, 8 ), 2 ).toString( 16 );
        out += '%' + ( ( chr.length % 2 == 0 ) ? chr : '0' + chr );
    }
    return decodeURIComponent( out );
};

The escape/unescape() functions are deprecated. If you need polyfills for them, you can check out the more comprehensive UTF-8 encoding example found here: http://jsfiddle.net/47zwb41o

HTML Display Current date

Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.

_x000D_
_x000D_
n =  new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
_x000D_
_x000D_

How can I do an asc and desc sort using underscore.js?

You can use .sortBy, it will always return an ascending list:

_.sortBy([2, 3, 1], function(num) {
    return num;
}); // [1, 2, 3]

But you can use the .reverse method to get it descending:

var array = _.sortBy([2, 3, 1], function(num) {
    return num;
});

console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]

Or when dealing with numbers add a negative sign to the return to descend the list:

_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
    return -num;
}); // [3, 2, 1, 0, -1, -2, -3]

Under the hood .sortBy uses the built in .sort([handler]):

// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]

// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
    // a = current item in array
    // b = next item in array
    return b - a;
});

String concatenation in Jinja

My bad, in trying to simplify it, I went too far, actually stuffs is a record of all kinds of info, I just want the id in it.

stuffs = [[123, first, last], [456, first, last]]

I want my_sting to be

my_sting = '123, 456'

My original code should have looked like this:

{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}

Thinking about it, stuffs is probably a dictionary, but you get the gist.

Yes I found the join filter, and was going to approach it like this:

 {% set my_string = [] %}
 {% for stuff in stuffs %}
 {% do my_string.append(stuff.id) %}
 {% endfor%}
 {%  my_string|join(', ') %}

But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.

Get list of data-* attributes using javascript / jQuery

One way of finding all data attributes is using element.attributes. Using .attributes, you can loop through all of the element attributes, filtering out the items which include the string "data-".

let element = document.getElementById("element");

function getDataAttributes(element){
    let elementAttributes = {},
        i = 0;

    while(i < element.attributes.length){
        if(element.attributes[i].name.includes("data-")){
            elementAttributes[element.attributes[i].name] = element.attributes[i].value
        }
        i++;
    }

    return elementAttributes;

}

Convert IQueryable<> type object to List<T> type?

Here's a couple of extension methods I've jury-rigged together to convert IQueryables and IEnumerables from one type to another (i.e. DTO). It's mainly used to convert from a larger type (i.e. the type of the row in the database that has unneeded fields) to a smaller one.

The positive sides of this approach are:

  • it requires almost no code to use - a simple call to .Transform<DtoType>() is all you need
  • it works just like .Select(s=>new{...}) i.e. when used with IQueryable it produces the optimal SQL code, excluding Type1 fields that DtoType doesn't have.

LinqHelper.cs:

public static IQueryable<TResult> Transform<TResult>(this IQueryable source)
{
    var resultType = typeof(TResult);
    var resultProperties = resultType.GetProperties().Where(p => p.CanWrite);

    ParameterExpression s = Expression.Parameter(source.ElementType, "s");

    var memberBindings =
        resultProperties.Select(p =>
            Expression.Bind(typeof(TResult).GetMember(p.Name)[0], Expression.Property(s, p.Name))).OfType<MemberBinding>();

    Expression memberInit = Expression.MemberInit(
        Expression.New(typeof(TResult)),
        memberBindings
        );

    var memberInitLambda = Expression.Lambda(memberInit, s);

    var typeArgs = new[]
        {
            source.ElementType, 
            memberInit.Type
        };

    var mc = Expression.Call(typeof(Queryable), "Select", typeArgs, source.Expression, memberInitLambda);

    var query = source.Provider.CreateQuery<TResult>(mc);

    return query;
}

public static IEnumerable<TResult> Transform<TResult>(this IEnumerable source)
{
    return source.AsQueryable().Transform<TResult>();
}

Display calendar to pick a date in java

  1. Open your Java source code document and navigate to the JTable object you have created inside of your Swing class.

  2. Create a new TableModel object that holds a DatePickerTable. You must create the DatePickerTable with a range of date values in MMDDYYYY format. The first value is the begin date and the last is the end date. In code, this looks like:

    TableModel datePicker = new DatePickerTable("01011999","12302000");
    
  3. Set the display interval in the datePicker object. By default each day is displayed, but you may set a regular interval. To set a 15-day interval between date options, use this code:

    datePicker.interval = 15;
    
  4. Attach your table model into your JTable:

    JTable newtable = new JTable (datePicker);
    

    Your Java application now has a drop-down date selection dialog.

Using css transform property in jQuery

Setting a -vendor prefix that isn't supported in older browsers can cause them to throw an exception with .css. Instead detect the supported prefix first:

// Start with a fall back
var newCss = { 'zoom' : ui.value };

// Replace with transform, if supported
if('WebkitTransform' in document.body.style) 
{
    newCss = { '-webkit-transform': 'scale(' + ui.value + ')'};
}
// repeat for supported browsers
else if('transform' in document.body.style) 
{
    newCss = { 'transform': 'scale(' + ui.value + ')'};
}

// Set the CSS
$('.user-text').css(newCss)

That works in old browsers. I've done scale here but you could replace it with whatever other transform you wanted.

How can I remove item from querystring in asp.net using c#?

I answered a similar question a while ago. Basically, the best way would be to use the class HttpValueCollection, which the QueryString property actually is, unfortunately it is internal in the .NET framework. You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.

HttpValueCollection extends NameValueCollection, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString() method to later rebuild the query string from the underlying collection.

Php $_POST method to get textarea value

Remove some of your textarea class like

<textarea name="Address" rows="3" class="input-text full-width" placeholder="Your Address" ></textarea>

To

<textarea name="Address" rows="3" class="full-width" placeholder="Your Address" ></textarea>

It's dependent on your template (Purchased Template). The developer has included some JavaScript to get the value from correct object on UI, but class like input-text just finds only $('input[type=text]'), that's why.

Issue with background color and Google Chrome

body, html { 
   width: 100%;
   height: 100%;
}

Worked for me :)

What is stdClass in PHP?

Its also worth noting that by using Casting you do not actually need to create an object as in the answer given by @Bandula. Instead you can simply cast your array to an object and the stdClass is returned. For example:

$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

$obj = (object) $array;
echo $obj->Property3;

Output: again

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

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

PHP date yesterday

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43

C++ passing an array pointer as a function argument

int *a[], when used as a function parameter (but not in normal declarations), is a pointer to a pointer, not a pointer to an array (in normal declarations, it is an array of pointers). A pointer to an array looks like this:

int (*aptr)[N]

Where N is a particular positive integer (not a variable).

If you make your function a template, you can do it and you don't even need to pass the size of the array (because it is automatically deduced):

template<size_t SZ>
void generateArray(int (*aptr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        (*aptr)[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(&a);
}

You could also take a reference:

template<size_t SZ>
void generateArray(int (&arr)[SZ])
{
    for (size_t i=0; i<SZ; ++i)
        arr[i] = rand() % 9;
}

int main()
{    
    int a[5];    
    generateArray(a);
}

Single controller with multiple GET methods in ASP.NET Web API

**Add Route function to direct the routine what you want**
    public class SomeController : ApiController
    {
        [HttpGet()]
        [Route("GetItems")]
        public SomeValue GetItems(CustomParam parameter) { ... }

        [HttpGet()]
        [Route("GetChildItems")]
        public SomeValue GetChildItems(CustomParam parameter, SomeObject parent) { ... }
    }

Is there a way to create key-value pairs in Bash script?

in older bash (or in sh) that does not support declare -A, following style can be used to emulate key/value

# key
env=staging


# values
image_dev=gcr.io/abc/dev
image_staging=gcr.io/abc/stage
image_production=gcr.io/abc/stable

img_var_name=image_$env

# active_image=${!var_name}
active_image=$(eval "echo \$$img_var_name")

echo $active_image

Where does Vagrant download its .box files to?

@Luke Peterson: There's a simpler way to get .box file.

Just go to https://atlas.hashicorp.com/boxes/search, search for the box you'd like to download. Notice the URL of the box, e.g:

https://atlas.hashicorp.com/ubuntu/boxes/trusty64/versions/20150530.0.1

Then you can download this box using URL like this:

https://vagrantcloud.com/ubuntu/boxes/trusty64/versions/20150530.0.1/providers/virtualbox.box

I tried and successfully download all the boxes I need. Hope that help.

An internal error occurred during: "Updating Maven Project". Unsupported IClasspathEntry kind=4

Your command line mvn eclipse project generator may not be the same version as that of your eclipse, and eclipse doesn't understand for your command line tool is generating. Just use eclipse's in this case:

  • remove the project from eclipse (including all modules if multi-module)
  • run: rm -rf .settings/ .project .classpath to delete eclipse project files, also from modules
  • import your project as an existing maven project

Get last field using awk substr

I know I'm like 3 years late on this but.... you should consider parameter expansion, it's built-in and faster.

if your input is in a var, let's say, $var1, just do ${var1##*/}. Look below

$ var1='/home/parent/child1/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/filename'
$ echo ${var1##*/}
filename
$ var1='/home/parent/child1/child2/child3/filename'
$ echo ${var1##*/}
filename

Reactjs - Form input validation

We have plenty of options to validate the react js forms. Maybe the npm packages have some own limitations. Based up on your needs you can choose the right validator packages. I would like to recommend some, those are listed below.

If anybody knows a better solution than this, please put it on the comment section for other people references.