Programs & Examples On #Soap client

An application that calls upon a SOAP server.

What SOAP client libraries exist for Python, and where is the documentation for them?

Update (2016):

If you only need SOAP client, there is well maintained library called zeep. It supports both Python 2 and 3 :)


Update:

Additionally to what is mentioned above, I will refer to Python WebServices page which is always up-to-date with all actively maintained and recommended modules to SOAP and all other webservice types.


Unfortunately, at the moment, I don't think there is a "best" Python SOAP library. Each of the mainstream ones available has its own pros and cons.

Older libraries:

  • SOAPy: Was the "best," but no longer maintained. Does not work on Python 2.5+

  • ZSI: Very painful to use, and development is slow. Has a module called "SOAPpy", which is different than SOAPy (above).

"Newer" libraries:

  • SUDS: Very Pythonic, and easy to create WSDL-consuming SOAP clients. Creating SOAP servers is a little bit more difficult. (This package does not work with Python3. For Python3 see SUDS-py3)

  • SUDS-py3: The Python3 version of SUDS

  • spyne: Creating servers is easy, creating clients a little bit more challenging. Documentation is somewhat lacking.

  • ladon: Creating servers is much like in soaplib (using a decorator). Ladon exposes more interfaces than SOAP at the same time without extra user code needed.

  • pysimplesoap: very lightweight but useful for both client and server - includes a web2py server integration that ships with web2py.

  • SOAPpy: Distinct from the abandoned SOAPpy that's hosted at the ZSI link above, this version was actually maintained until 2011, now it seems to be abandoned too.
  • soaplib: Easy to use python library for writing and calling soap web services. Webservices written with soaplib are simple, lightweight, work well with other SOAP implementations, and can be deployed as WSGI applications.
  • osa: A fast/slim easy to use SOAP python client library.

Of the above, I've only used SUDS personally, and I liked it a lot.

SOAP client in .NET - references or examples?

If you can get it to run in a browser then something as simple as this would work

var webRequest = WebRequest.Create(@"http://webservi.se/year/getCurrentYear");

using (var response = webRequest.GetResponse())
{
    using (var rd = new StreamReader(response.GetResponseStream()))
    {
        var soapResult = rd.ReadToEnd();
    }
}

Unicode (UTF-8) reading and writing to files in Python

I was trying to parse iCal using Python 2.7.9:

from icalendar import Calendar

But I was getting:

 Traceback (most recent call last):
 File "ical.py", line 92, in parse
    print "{}".format(e[attr])
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 7: ordinal not in range(128)

and it was fixed with just:

print "{}".format(e[attr].encode("utf-8"))

(Now it can print liké á böss.)

MySQL select with CONCAT condition

Try this:

SELECT * 
  FROM  (
        SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
        FROM users 
    ) a
WHERE firstlast = "Bob Michael Jones"

On design patterns: When should I use the singleton?

A Singleton candidate must satisfy three requirements:

  • controls concurrent access to a shared resource.
  • access to the resource will be requested from multiple, disparate parts of the system.
  • there can be only one object.

If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.

For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.

A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

I also had the same problem with bson.

trying a newer mongoose version

npm install [email protected]

solved the issue.

Massimo.

Inheritance and init method in Python

When you override the init you have also to call the init of the parent class

super(Num2, self).__init__(num)

Understanding Python super() with __init__() methods

How to prevent the "Confirm Form Resubmission" dialog?

This method works for me well and I think the simplest way to do this is to use this javascript code inside the reloaded page's HTML.

_x000D_
_x000D_
if ( window.history.replaceState ) {_x000D_
  window.history.replaceState( null, null, window.location.href );_x000D_
}
_x000D_
_x000D_
_x000D_

jwt check if token expired

You should use jwt.verify it will check if the token is expired. jwt.decode should not be used if the source is not trusted as it doesn't check if the token is valid.

convert string to char*

There are many ways. Here are at least five:

/*
 * An example of converting std::string to (const)char* using five
 * different methods. Error checking is emitted for simplicity.
 *
 * Compile and run example (using gcc on Unix-like systems):
 *
 *  $ g++ -Wall -pedantic -o test ./test.cpp
 *  $ ./test
 *  Original string (0x7fe3294039f8): hello
 *  s1 (0x7fe3294039f8): hello
 *  s2 (0x7fff5dce3a10): hello
 *  s3 (0x7fe3294000e0): hello
 *  s4 (0x7fe329403a00): hello
 *  s5 (0x7fe329403a10): hello
 */

#include <alloca.h>
#include <string>
#include <cstring>

int main()
{
    std::string s0;
    const char *s1;
    char *s2;
    char *s3;
    char *s4;
    char *s5;

    // This is the initial C++ string.
    s0 = "hello";

    // Method #1: Just use "c_str()" method to obtain a pointer to a
    // null-terminated C string stored in std::string object.
    // Be careful though because when `s0` goes out of scope, s1 points
    // to a non-valid memory.
    s1 = s0.c_str();

    // Method #2: Allocate memory on stack and copy the contents of the
    // original string. Keep in mind that once a current function returns,
    // the memory is invalidated.
    s2 = (char *)alloca(s0.size() + 1);
    memcpy(s2, s0.c_str(), s0.size() + 1);

    // Method #3: Allocate memory dynamically and copy the content of the
    // original string. The memory will be valid until you explicitly
    // release it using "free". Forgetting to release it results in memory
    // leak.
    s3 = (char *)malloc(s0.size() + 1);
    memcpy(s3, s0.c_str(), s0.size() + 1);

    // Method #4: Same as method #3, but using C++ new/delete operators.
    s4 = new char[s0.size() + 1];
    memcpy(s4, s0.c_str(), s0.size() + 1);

    // Method #5: Same as 3 but a bit less efficient..
    s5 = strdup(s0.c_str());

    // Print those strings.
    printf("Original string (%p): %s\n", s0.c_str(), s0.c_str());
    printf("s1 (%p): %s\n", s1, s1);
    printf("s2 (%p): %s\n", s2, s2);
    printf("s3 (%p): %s\n", s3, s3);
    printf("s4 (%p): %s\n", s4, s4);
    printf("s5 (%p): %s\n", s5, s5);

    // Release memory...
    free(s3);
    delete [] s4;
    free(s5);
}

How do I query for all dates greater than a certain date in SQL Server?

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

Find out a Git branch creator

We can find out based upon authorname

git for-each-ref --format='%(authorname) %09 %(if)%(HEAD)%(then)*%(else)%(refname:short)%(end) %09 %(creatordate)' refs/remotes/ --sort=authorname DESC

How to convert int[] to Integer[] in Java?

Not sure why you need a Double in your map. In terms of what you're trying to do, you have an int[] and you just want counts of how many times each sequence occurs? Why would this required a Double anyway?

What I would do is to create a wrapper for the int array with a proper .equals and .hashCode methods to account for the fact that int[] object itself doesn't consider the data in it's version of these methods.

public class IntArrayWrapper {
    private int values[];

    public IntArrayWrapper(int[] values) {
        super();
        this.values = values;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + Arrays.hashCode(values);
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        IntArrayWrapper other = (IntArrayWrapper) obj;
        if (!Arrays.equals(values, other.values))
            return false;
        return true;
    }

}

And then use google guava's multiset, which is meant exactly for the purpose of counting occurances, as long as the element type you put in it has proper .equals and .hashCode methods.

List<int[]> list = ...;
HashMultiset<IntArrayWrapper> multiset = HashMultiset.create();
for (int values[] : list) {
    multiset.add(new IntArrayWrapper(values));
}

Then, to get the count for any particular combination:

int cnt = multiset.count(new IntArrayWrapper(new int[] { 0, 1, 2, 3 }));

Pointer-to-pointer dynamic two-dimensional array

This code works well with very few requirements on external libraries and shows a basic use of int **array.

This answer shows that each array is dynamically sized, as well as how to assign a dynamically sized leaf array into the dynamically sized branch array.

This program takes arguments from STDIN in the following format:

2 2   
3 1 5 4
5 1 2 8 9 3
0 1
1 3

Code for program below...

#include <iostream>

int main()
{
    int **array_of_arrays;

    int num_arrays, num_queries;
    num_arrays = num_queries = 0;
    std::cin >> num_arrays >> num_queries;
    //std::cout << num_arrays << " " << num_queries;

    //Process the Arrays
    array_of_arrays = new int*[num_arrays];
    int size_current_array = 0;

    for (int i = 0; i < num_arrays; i++)
    {
        std::cin >> size_current_array;
        int *tmp_array = new int[size_current_array];
        for (int j = 0; j < size_current_array; j++)
        {
            int tmp = 0;
            std::cin >> tmp;
            tmp_array[j] = tmp;
        }
        array_of_arrays[i] = tmp_array;
    }


    //Process the Queries
    int x, y;
    x = y = 0;
    for (int q = 0; q < num_queries; q++)
    {
        std::cin >> x >> y;
        //std::cout << "Current x & y: " << x << ", " << y << "\n";
        std::cout << array_of_arrays[x][y] << "\n";
    }

    return 0;
}

It's a very simple implementation of int main and relies solely on std::cin and std::cout. Barebones, but good enough to show how to work with simple multidimensional arrays.

Windows Task Scheduler doesn't start batch file task

Configuration that worked for me:

  • In General tab: mark radio button - "Run only when user is logged on" <= important !
  • Program/script: just the path to script without quotes or nothing: C:/tools/script.bat
  • Add arguments: kept it empty
  • Start in: kept it empty

In settings, only 2 checkboxes marked:

  • Allow task to be run on demand
  • if the running task does not end when requested, force it to stop

Execute a shell function with timeout

Putting my comment to Tiago Lopo's answer into more readable form:

I think it's more readable to impose a timeout on the most recent subshell, this way we don't need to eval a string and the whole script can be highlighted as shell by your favourite editor. I simply put the commands after the subshell with eval has spawned into a shell-function (tested with zsh, but should work with bash):

timeout_child () {
    trap -- "" SIGTERM
    child=$!
    timeout=$1
    (
            sleep $timeout
            kill $child
    ) &
    wait $child
}

Example usage:

( while true; do echo -n .; sleep 0.1; done) & timeout_child 2

And this way it also works with a shell function (if it runs in the background):

 print_dots () {
     while true
     do
         sleep 0.1
         echo -n .
     done
 }


 > print_dots & timeout_child 2
 [1] 21725
 [3] 21727
 ...................[1]    21725 terminated  print_dots
 [3]  + 21727 done       ( sleep $timeout; kill $child; )

Replace comma with newline in sed on MacOS?

If your sed usage tends to be entirely substitution expressions (as mine tends to be), you can also use perl -pe instead

$ echo 'foo,bar,baz' | perl -pe 's/,/,\n/g'
foo,
bar,
baz

Best way to check if a URL is valid

Actually... filter_var($url, FILTER_VALIDATE_URL); doesn't work very well. When you type in a real url, it works but, it only checks for http:// so if you type something like "http://weirtgcyaurbatc", it will still say it's real.

Confused about Service vs Factory

All providers work the same way. The different methods service, factory, provider just let you accomplish the same thing in less code.

P.S. There's also value and constant.

Each special case down the chain starting with provider and ending with value has an added limitation. So to decide between them you have to ask yourself which let's you accomplish what you want with less code.

Here is a picture that shows you what I mean:

enter image description here

You can a breakdown and reference guide on the blog post I got this image from:

http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

Difference between "on-heap" and "off-heap"

The JVM doesn't know anything about off-heap memory. Ehcache implements an on-disk cache as well as an in-memory cache.

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

How can I set the current working directory to the directory of the script in Bash?

This script seems to work for me:

#!/bin/bash
mypath=`realpath $0`
cd `dirname $mypath`
pwd

The pwd command line echoes the location of the script as the current working directory no matter where I run it from.

how to change namespace of entire project?

I tried everything but I found a solution which really works. It creates independed solution with a new namespace name an so on.

  1. In main form find namespace name -> right click -> Refactor -> Rename and select a new name. Check all boxes and click OK.

  2. In the solution explorer rename solution name to a new name.

  3. In the solution explorer rename project name to a new name.

  4. Close VS and rename folder (in total commander for example) in the solution folder to a new name.

  5. In .sln file rename old name to a new name.

  6. Delete old .suo files (hidden)

  7. Start VS and load project

  8. Project -> properties -> change Assembly name and default namespace to a new name.

Struct Constructor in C++?

In C++, we can declare/define the structure just like class and have the constructors/destructors for the Structures and have variables/functions defined in it. The only difference is the default scope of the variables/functions defined. Other than the above difference, mostly you should be able to imitate the functionality of class using structs.

How to keep indent for second line in ordered lists via CSS?

The following CSS did the trick:

ul{
    margin-left: 1em;
}

li{
    list-style-position: outside;
    padding-left: 0.5em;
}

Read input stream twice

Convert inputstream into bytes and then pass it to savefile function where you assemble the same into inputstream. Also in original function use bytes to use for other tasks

How to change active class while click to another link in bootstrap use jquery?

If you are using server side code like Java then you need to return active tab name and on return page have some function to disable( meaning remove active class) all tabs except the one you returned.

This would require you to add id or name to each tab. Little bit more work :)

Plot mean and standard deviation

You may find an answer with this example : errorbar_demo_features.py

"""
Demo of errorbar function with different ways of specifying error bars.

Errors can be specified as a constant value (as shown in `errorbar_demo.py`),
or as demonstrated in this example, they can be specified by an N x 1 or 2 x N,
where N is the number of data points.

N x 1:
    Error varies for each point, but the error values are symmetric (i.e. the
    lower and upper values are equal).

2 x N:
    Error varies for each point, and the lower and upper limits (in that order)
    are different (asymmetric case)

In addition, this example demonstrates how to use log scale with errorbar.
"""
import numpy as np
import matplotlib.pyplot as plt

# example data
x = np.arange(0.1, 4, 0.5)
y = np.exp(-x)
# example error bar values that vary with x-position
error = 0.1 + 0.2 * x
# error bar values w/ different -/+ errors
lower_error = 0.4 * error
upper_error = error
asymmetric_error = [lower_error, upper_error]

fig, (ax0, ax1) = plt.subplots(nrows=2, sharex=True)
ax0.errorbar(x, y, yerr=error, fmt='-o')
ax0.set_title('variable, symmetric error')

ax1.errorbar(x, y, xerr=asymmetric_error, fmt='o')
ax1.set_title('variable, asymmetric error')
ax1.set_yscale('log')
plt.show()

Which plots this:

enter image description here

List all the files and folders in a Directory with PHP recursive function

This could help if you wish to get directory contents as an array, ignoring hidden files and directories.

function dir_tree($dir_path)
{
    $rdi = new \RecursiveDirectoryIterator($dir_path);

    $rii = new \RecursiveIteratorIterator($rdi);

    $tree = [];

    foreach ($rii as $splFileInfo) {
        $file_name = $splFileInfo->getFilename();

        // Skip hidden files and directories.
        if ($file_name[0] === '.') {
            continue;
        }

        $path = $splFileInfo->isDir() ? array($file_name => array()) : array($file_name);

        for ($depth = $rii->getDepth() - 1; $depth >= 0; $depth--) {
            $path = array($rii->getSubIterator($depth)->current()->getFilename() => $path);
        }

        $tree = array_merge_recursive($tree, $path);
    }

    return $tree;
}

The result would be something like;

dir_tree(__DIR__.'/public');

[
    'css' => [
        'style.css',
        'style.min.css',
    ],
    'js' => [
        'script.js',
        'script.min.js',
    ],
    'favicon.ico',
]

Source

MVC 4 - Return error message from Controller - Show in View

If you want to do a redirect, you can either:

ViewBag.Error = "error message";

or

TempData["Error"] = "error message";

Rename Files and Directories (Add Prefix)

Use the rename script this way:

$ rename 's/^/PRE_/' *

There are no problems with metacharacters or whitespace in filenames.

Import CSV to mysql table

I have google search many ways to import csv to mysql, include " load data infile ", use mysql workbench, etc.

when I use mysql workbench import button, first you need to create the empty table on your own, set each column type on your own. Note: you have to add ID column at the end as primary key and not null and auto_increment, otherwise, the import button will not visible at later. However, when I start load CSV file, nothing loaded, seems like a bug. I give up.

Lucky, the best easy way so far I found is to use Oracle's mysql for excel. you can download it from here mysql for excel

This is what you are going to do: open csv file in excel, at Data tab, find mysql for excel button

select all data, click export to mysql. Note to set a ID column as primary key.

when finished, go to mysql workbench to alter the table, such as currency type should be decimal(19,4) for large amount decimal(10,2) for regular use. other field type may be set to varchar(255).

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

How to validate an email address in PHP

/(?![[:alnum:]]|@|-|_|\.)./

Nowadays, if you use a HTML5 form with type=email then you're already by 80% safe since browser engines have their own validator. To complement it, add this regex to your preg_match_all() and negate it:

if (!preg_match_all("/(?![[:alnum:]]|@|-|_|\.)./",$email)) { .. }

Find the regex used by HTML5 forms for validation
https://regex101.com/r/mPEKmy/1

Render a string in HTML and preserve spaces and linebreaks

Just style the content with white-space: pre-wrap;.

_x000D_
_x000D_
div {_x000D_
    white-space: pre-wrap;_x000D_
}
_x000D_
<div>_x000D_
This is some text   with some extra spacing    and a_x000D_
few newlines along with some trailing spaces        _x000D_
     and five leading spaces thrown in_x000D_
for                                              good_x000D_
measure                                              _x000D_
</div>
_x000D_
_x000D_
_x000D_

CSS Transition doesn't work with top, bottom, left, right

Perhaps you need to specify a top value in your css rule set, so that it will know what value to animate from.

Passing references to pointers in C++

The problem is that you're trying to bind a temporary to the reference, which C++ doesn't allow unless the reference is const.

So you can do one of either the following:

void myfunc(string*& val)
{
    // Do stuff to the string pointer
}


void myfunc2(string* const& val)
{
    // Do stuff to the string pointer
}

int main()
// sometime later 
{
    // ...
    string s;
    string* ps = &s;

    myfunc( ps);   // OK because ps is not a temporary
    myfunc2( &s);  // OK because the parameter is a const&
    // ...

    return 0;
}

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

How to fix error with xml2-config not found when installing PHP from sources?

All you need to do instal install package libxml2-dev for example:

sudo apt-get install libxml2-dev

On CentOS/RHEL:

sudo yum install libxml2-devel

Change arrow colors in Bootstraps carousel

Currently Bootstrap 4 uses a background-image with embbed SVG data info that include the color of the SVG shape. Something like:

.carousel-control-prev-icon { background-image:url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); }

Note the part about fill='%23fff' it fills the shape with a color, in this case #fff (white), for red simply replace with #f00

Finally, it is safe to include this (same change for next-icon):

.carousel-control-prev-icon {background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23f00' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E"); }

Android: Bitmaps loaded from gallery are rotated in ImageView

The first thing you need is the real File path If you have it great, if you are using URI then use this method to get the real Path:

 public static String getRealPathFromURI(Uri contentURI,Context context) {
    String path= contentURI.getPath();
    try {
        Cursor cursor = context.getContentResolver().query(contentURI, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();

        cursor = context.getContentResolver().query(
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
        cursor.moveToFirst();
        path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();
    }
    catch(Exception e)
    {
        return path;
    }
    return path;
}

extract your Bitmap for example:

  try {
                            Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

                        }
                        catch (IOException e)
                        {
                            Log.e("IOException",e.toString());
                        }

you can use decodeFile() instead if you wish.

Now that you have the Bitmap and the real Path get the Orientation of the Image:

 private static int getExifOrientation(String src) throws IOException {
        int orientation = 1;

        ExifInterface exif = new ExifInterface(src);
        String orientationString=exif.getAttribute(ExifInterface.TAG_ORIENTATION);
        try {
            orientation = Integer.parseInt(orientationString);
        }
        catch(NumberFormatException e){}

        return orientation;
    }

and finally rotate it to the right position like so:

public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
        try {
            int orientation = getExifOrientation(src);

            if (orientation == 1) {
                return bitmap;
            }

            Matrix matrix = new Matrix();
            switch (orientation) {
                case 2:
                    matrix.setScale(-1, 1);
                    break;
                case 3:
                    matrix.setRotate(180);
                    break;
                case 4:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case 5:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case 6:
                    matrix.setRotate(90);
                    break;
                case 7:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case 8:
                    matrix.setRotate(-90);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return oriented;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }

That's it , you now have the bitmap rotated to the right position.

cheers.

How to get just the date part of getdate()?

If you are using SQL Server 2008 or later

select convert(date, getdate())

Otherwise

select convert(varchar(10), getdate(),120)

convert datetime to date format dd/mm/yyyy

You can use the ToString() method, if you want a string representation of your date, with the correct formatting.

Like:

DateTime date = new DateTime(2011, 02, 19);
string strDate = date.ToString("dd/MM/yyyy");

get DATEDIFF excluding weekends using sql server

Using https://stackoverflow.com/a/1804095 and JeffFisher30's answer above (https://stackoverflow.com/a/14572370/6147425) and my own need to have fractional days, I wrote this:

DateDiff(second,Start_Time,End_Time)/86400.0
            -2*DateDiff(week, Start_Time, End_Time)
            -Case When (DatePart(weekday, Start_Time)+@@DateFirst)%7 = 1 Then 1 Else 0 End
            +Case When (DatePart(weekday, End_Time)+@@DateFirst)%7 = 1 Then 1 Else 0 End

How to find when a web page was last updated

Open your browsers console(?) and enter the following:

javascript:alert(document.lastModified)

How to download all files (but not HTML) from a website using wget?

To filter for specific file extensions:

wget -A pdf,jpg -m -p -E -k -K -np http://site/path/

Or, if you prefer long option names:

wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent http://site/path/

This will mirror the site, but the files without jpg or pdf extension will be automatically removed.

connect local repo with remote repo

I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.

How do I use this JavaScript variable in HTML?

You can create a <p> element:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <script>_x000D_
  var name = prompt("What's your name?");_x000D_
  var lengthOfName = name.length_x000D_
  p = document.createElement("p");_x000D_
  p.innerHTML = "Your name is "+lengthOfName+" characters long.";_x000D_
  document.body.appendChild(p);_x000D_
  </script>_x000D_
  <body>_x000D_
  </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

jQuery bind/unbind 'scroll' event on $(window)

Very old question, but in case someone else stumbles across it, I would recommend trying:

$j("html, body").stop(true, true).animate({
        scrollTop: $j('#main').offset().top 
}, 300);

How to obtain the query string from the current URL with JavaScript?

Convert that into array then split with '?'

var url= 'http://localhost/PMApp/temp.htm?ProjectID=462';

url.split('?')[1];     //ProjectID=462

Key error when selecting columns in pandas dataframe after read_csv

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

MySQL Removing Some Foreign keys

As everyone said above, you can easily delete a FK. However, I just noticed that it can be necessary to drop the KEY itself at some point. If you have any error message to create another index like the last one, I mean with the same name, it would be useful dropping everything related to that index.

ALTER TABLE your_table_with_fk
  drop FOREIGN KEY name_of_your_fk_from_show_create_table_command_result,
  drop KEY the_same_name_as_above

Convert a matrix to a 1 dimensional array

From ?matrix: "A matrix is the special case of a two-dimensional 'array'." You can simply change the dimensions of the matrix/array.

Elts_int <- as.matrix(tmp_int)  # read.table returns a data.frame as Brandon noted
dim(Elts_int) <- (maxrow_int*maxcol_int,1)

Must issue a STARTTLS command first

Adding

props.put("mail.smtp.starttls.enable", "true");

solved my problem ;)

My problem was :

com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. u186sm7971862pfu.82 - gsmtp

at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:1609)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1117)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at com.example.sendmail.SendEmailExample2.main(SendEmailExample2.java:53)

Linq to Entities join vs groupjoin

Let's suppose you have two different classes:

public class Person
{
    public string Name, Email;
    
    public Person(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
class Data
{
    public string Mail, SlackId;
    
    public Data(string mail, string slackId)
    {
        Mail = mail;
        SlackId = slackId;
    }
}

Now, let's Prepare data to work with:

var people = new Person[]
    {
        new Person("Sudi", "[email protected]"),
        new Person("Simba", "[email protected]"),
        new Person("Sarah", string.Empty)
    };
    
    var records = new Data[]
    {
        new Data("[email protected]", "Sudi_Try"),
        new Data("[email protected]", "Sudi@Test"),
        new Data("[email protected]", "SimbaLion")
    };

You will note that [email protected] has got two slackIds. I have made that for demonstrating how Join works.

Let's now construct the query to join Person with Data:

var query = people.Join(records,
        x => x.Email,
        y => y.Mail,
        (person, record) => new { Name = person.Name, SlackId = record.SlackId});
    Console.WriteLine(query);

After constructing the query, you could also iterate over it with a foreach like so:

foreach (var item in query)
    {
        Console.WriteLine($"{item.Name} has Slack ID {item.SlackId}");
    }

Let's also output the result for GroupJoin:

Console.WriteLine(
    
        people.GroupJoin(
            records,
            x => x.Email,
            y => y.Mail,
            (person, recs) => new {
                Name = person.Name,
                SlackIds = recs.Select(r => r.SlackId).ToArray() // You could materialize //whatever way you want.
            }
        ));

You will notice that the GroupJoin will put all SlackIds in a single group.

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

Access non-numeric Object properties by index?

var obj = {
    'key1':'value',
    '2':'value',
    'key 1':'value'
}

console.log(obj.key1)
console.log(obj['key1'])
console.log(obj['2'])
console.log(obj['key 1'])

// will not work
console.log(obj.2)

Edit:

"I'm specifically looking to target the index, just like the first example - if it's possible."

Actually the 'index' is the key. If you want to store the position of a key you need to create a custom object to handle this.

Unable to copy a file from obj\Debug to bin\Debug

A very simple solution is to open the Task Manager (CTRL + ALT + DELETE), go to Processes tab and search by name the processes with your project name that are still running. Kill all the processes and go on ! :)

Graphviz's executables are not found (Python 3.4)

If you are on Win10, install Graphviz and then use following command to add the path.

import os
os.environ["PATH"] += os.pathsep + 'C:\Program Files (x86)\Graphviz2.38/bin/'

Show/hide 'div' using JavaScript

Using style:

<style type="text/css">
   .hidden {
        display: none;
   {
   .visible {
        display: block;
   }
</style>

Using an event handler in JavaScript is better than the onclick="" attribute in HTML:

<button id="RenderPortfolio_Btn">View Portfolio</button>
<button id="RenderResults_Btn">View Results</button>

<div class="visible" id="portfolio">
    <span>div1</span>
</div>

<div class"hidden" id="results">
    <span>div2</span>
</div>

JavaScript:

<script type="text/javascript">

    var portfolioDiv = document.getElementById('portfolio');
    var resultsDiv = document.getElementById('results');

    var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
    var resultsBtn = document.getElementById('RenderResults_Btn');

    portfolioBtn.onclick = function() {
        resultsDiv.setAttribute('class', 'hidden');
        portfolioDiv.setAttribute('class', 'visible');
    };

    resultsBtn.onclick = function() {
        portfolioDiv.setAttribute('class', 'hidden');
        resultsDiv.setAttribute('class', 'visible');
    };

</script>

jQuery may help you to manipulate DOM elements easy!

Store mysql query output into a shell variable

A more direct way would be:

myvar=$(mysql mydatabase -u $user -p$password -se "SELECT a, b, c FROM table_a")

Pass arguments to Constructor in VBA

Using the trick

Attribute VB_PredeclaredId = True

I found another more compact way:

Option Explicit
Option Base 0
Option Compare Binary

Private v_cBox As ComboBox

'
' Class creaor
Public Function New_(ByRef cBox As ComboBox) As ComboBoxExt_c
  If Me Is ComboBoxExt_c Then
    Set New_ = New ComboBoxExt_c
    Call New_.New_(cBox)
  Else
    Set v_cBox = cBox
  End If
End Function

As you can see the New_ constructor is called to both create and set the private members of the class (like init) only problem is, if called on the non-static instance it will re-initialize the private member. but that can be avoided by setting a flag.

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

You can't. There isn't a feature in my CPAN client to do such a thing. We were talking about how we might do something like that at this weekend's Perl QA Workshop, but it's generally hard for all the reasons that Ether mentioned.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Mine is that if you set MASM listing file option some extra selection, it will give you this error.

Just use

 Enable Assembler Generated Code Listing   Yes/Sg
 Assembled Code Listing $(ProjectName).lst

it is fine.

But any extra you have issue.

How to disable an input type=text?

You can get the DOM element and set disabled attribute to true/false.

If you use vue framework,here is a very easy demo.

_x000D_
_x000D_
  let vm = new Vue({
        el: "#app",
        data() {
            return { flag: true }
        },
        computed: {
            btnText() {
                return this.flag ? "Enable" : "Disable";
            }
        }
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <input type="text" value="something" :disabled="flag" />
    <input type="button" :value="btnText" @click="flag=!flag">
</div>
_x000D_
_x000D_
_x000D_

Intellij idea cannot resolve anything in maven

I was getting this error because my project was not setup correctly. It had imported main and test folders as modules. When I deleted the 2 modules (but retained them as source and test folders), my code started compiling correctly.

DataGridView AutoFit and Fill

public static void Fill(DataGridView dgv2)
   {
        try
        {
            dgv = dgv2;
            foreach (DataGridViewColumn GridCol in dgv.Columns)
            {
                for (int j = 0; j < GridCol.DataGridView.ColumnCount; j++)
                {
                    GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                    GridCol.DataGridView.Columns[j].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
                    GridCol.DataGridView.Columns[j].FillWeight = 1;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Show/Hide Table Rows using Javascript classes

It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.

Here's the fiddle: link.

What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>s with class="cat1" or class="cat2".

I also mark the links with a simple .toggler class. It's not good practice to have onclick attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.

$(".toggler").click(function(e){
    // you handle the event here
});

With this format, you are binding an event handler to the click event of links with class toggler. In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. (The reason for my using a data-* attribute is explained here. You can Google 'html5 data attributes' for more information.)

In the event handler, I do this:

$('.cat'+$(this).attr('data-prod-cat')).toggle();

With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggles the visibility of the specified element(s).

I hope this was explanatory enough.

How to call a method in MainActivity from another class?

Use this code in sub Fragment of MainActivity to call the method on it.

((MainActivity) getActivity()).startChronometer();

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece (in core since Perl 5.10) also has a strftime function and by default overloads localtime and gmtime to return Time::Piece objects:

use Time::Piece;
print localtime->strftime('%Y-%m-%d');

or without the overridden localtime:

use Time::Piece (); 
print Time::Piece::localtime->strftime('%F %T');

Opening a new tab to read a PDF file

Try this, it worked for me.

<td><a href="Docs/Chapter 1_ORG.pdf" target="pdf-frame">Chapter-1 Organizational</a></td>

Combining node.js and Python

If you arrange to have your Python worker in a separate process (either long-running server-type process or a spawned child on demand), your communication with it will be asynchronous on the node.js side. UNIX/TCP sockets and stdin/out/err communication are inherently async in node.

JQuery Event for user pressing enter in a textbox?

I could not get the keypress event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:

"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)

I had to use the keyup or keydown event to catch a press of the enter button.

Convert textbox text to integer

If your SQL database allows Null values for that field try using int? value like that :

if (this.txtboxname.Text == "" || this.txtboxname.text == null)
     value = null;
else
     value = Convert.ToInt32(this.txtboxname.Text);

Take care that Convert.ToInt32 of a null value returns 0 !

Convert.ToInt32(null) returns 0

OR, AND Operator

Logical OR is ||, logical AND is &&. If you need the negation NOT, prefix your expression with !.

Example:

X = (A && B) || C || !D;

Then X will be true when either A and B are true or if C is true or if D is not true (i.e. false).

If you wanted bit-wise AND/OR/NOT, you would use &, | and ~. But if you are dealing with boolean/truth values, you do not want to use those. They do not provide short-circuit evaluation for example due to the way a bitwise operation works.

How do I test which class an object is in Objective-C?

If you want to check for a specific class then you can use

if([MyClass class] == [myClassObj class]) {
//your object is instance of MyClass
}

T-SQL How to create tables dynamically in stored procedures?

You will need to build that CREATE TABLE statement from the inputs and then execute it.

A simple example:

declare @cmd nvarchar(1000), @TableName nvarchar(100);

set @TableName = 'NewTable';

set @cmd = 'CREATE TABLE dbo.' + quotename(@TableName, '[') + '(newCol int not null);';

print @cmd;

--exec(@cmd);

Cannot connect to repo with TortoiseSVN

You need to determine whether this is a problem with TortoiseSVN, your Subversion repository, or your network connection.

  • First of all, check your URL. I never used User-Friendly SVN, so I don't know what it does to the Apache httpd configuration. However, the standard Apache configuration for multiple repositories is usually http://<server>/svn/<module> and not http://<server>/svn/usvn/<module>. Is that /usvn/ directory suppose to be there?
    • By the way, how was Apache configured? Does User-Friendly SVN do that too, or does it merely allow you to configure the repositories? Are you using Visual-SVN, or did someone manually configure Apache httpd?
  • If the URL is correct, try pinging your Subversion server. Can you ping it from your Windows box? If not, you have a network issue. For some reason that IP address isn't even reachable from your client box.
  • Try opening a browser, and putting the URL of the Subversion repository into the window. This should work. If it does, the issue is probably with TortoiseSVN. Download a command line Subversion client, and see if you can checkout with that.
  • Try using the same URL on another box. Can you checkout from there? If so, it points to a problem with the network.

Confusion: @NotNull vs. @Column(nullable = false) with JPA and Hibernate

The most recent versions of hibernate JPA provider applies the bean validation constraints (JSR 303) like @NotNull to DDL by default (thanks to hibernate.validator.apply_to_ddl property defaults to true). But there is no guarantee that other JPA providers do or even have the ability to do that.

You should use bean validation annotations like @NotNull to ensure, that bean properties are set to a none-null value, when validating java beans in the JVM (this has nothing to do with database constraints, but in most situations should correspond to them).

You should additionally use the JPA annotation like @Column(nullable = false) to give the jpa provider hints to generate the right DDL for creating table columns with the database constraints you want. If you can or want to rely on a JPA provider like Hibernate, which applies the bean validation constraints to DDL by default, then you can omit them.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

The configuration I use in my parent level pom where I have separate unit and integration test phases.

I configure the following properties in the parent POM Properties

    <maven.surefire.report.plugin>2.19.1</maven.surefire.report.plugin>
    <jacoco.plugin.version>0.7.6.201602180812</jacoco.plugin.version>
    <jacoco.check.lineRatio>0.52</jacoco.check.lineRatio>
    <jacoco.check.branchRatio>0.40</jacoco.check.branchRatio>
    <jacoco.check.complexityMax>15</jacoco.check.complexityMax>
    <jacoco.skip>false</jacoco.skip>
    <jacoco.excludePattern/>
    <jacoco.destfile>${project.basedir}/../target/coverage-reports/jacoco.exec</jacoco.destfile>

    <sonar.language>java</sonar.language>
    <sonar.exclusions>**/generated-sources/**/*</sonar.exclusions>
    <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
    <sonar.coverage.exclusions>${jacoco.excludePattern}</sonar.coverage.exclusions>
    <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
    <sonar.jacoco.reportPath>${project.basedir}/../target/coverage-reports</sonar.jacoco.reportPath>

    <skip.surefire.tests>${skipTests}</skip.surefire.tests>
    <skip.failsafe.tests>${skipTests}</skip.failsafe.tests>

I place the plugin definitions under plugin management.

Note that I define a property for surefire (surefireArgLine) and failsafe (failsafeArgLine) arguments to allow jacoco to configure the javaagent to run with each test.

Under pluginManagement

  <build>
     <pluginManagment>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <fork>true</fork>
                    <meminitial>1024m</meminitial>
                    <maxmem>1024m</maxmem>
                    <compilerArgument>-g</compilerArgument>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <forkCount>4</forkCount>
                    <reuseForks>false</reuseForks>
                    <argLine>-Xmx2048m ${surefireArgLine}</argLine>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                    <excludes>
                        <exclude>**/*IT.java</exclude>
                    </excludes>
                    <skip>${skip.surefire.tests}</skip>
                </configuration>
            </plugin>
            <plugin>
                <!-- For integration test separation -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>2.19.1</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <forkCount>4</forkCount>
                    <reuseForks>false</reuseForks>
                    <argLine>${failsafeArgLine}</argLine>
                    <includes>
                        <include>**/*IT.java</include>
                    </includes>
                    <skip>${skip.failsafe.tests}</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>verify</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <!-- Code Coverage -->
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco.plugin.version}</version>
                <configuration>
                    <haltOnFailure>true</haltOnFailure>
                    <excludes>
                        <exclude>**/*.mar</exclude>
                        <exclude>${jacoco.excludePattern}</exclude>
                    </excludes>
                    <rules>
                        <rule>
                            <element>BUNDLE</element>
                            <limits>
                                <limit>
                                    <counter>LINE</counter>
                                    <value>COVEREDRATIO</value>
                                    <minimum>${jacoco.check.lineRatio}</minimum>
                                </limit>
                                <limit>
                                    <counter>BRANCH</counter>
                                    <value>COVEREDRATIO</value>
                                    <minimum>${jacoco.check.branchRatio}</minimum>
                                </limit>
                            </limits>
                        </rule>
                        <rule>
                            <element>METHOD</element>
                            <limits>
                                <limit>
                                    <counter>COMPLEXITY</counter>
                                    <value>TOTALCOUNT</value>
                                    <maximum>${jacoco.check.complexityMax}</maximum>
                                </limit>
                            </limits>
                        </rule>
                    </rules>
                </configuration>
                <executions>
                    <execution>
                        <id>pre-unit-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <destFile>${jacoco.destfile}</destFile>
                            <append>true</append>
                            <propertyName>surefireArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                            <outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
                            <skip>${skip.surefire.tests}</skip>
                        </configuration>
                    </execution>
                    <execution>
                        <id>pre-integration-test</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <destFile>${jacoco.destfile}</destFile>
                            <append>true</append>
                            <propertyName>failsafeArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>report-integration</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                            <outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
                            <skip>${skip.failsafe.tests}</skip>
                        </configuration>
                    </execution>
                    <!-- Disabled until such time as code quality stops this tripping
                    <execution>
                        <id>default-check</id>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                        </configuration>
                    </execution>
                    -->
                </executions>
            </plugin>
            ...

And in the build section

 <build>
     <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
        </plugin>

        <plugin>
            <!-- for unit test execution -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
        </plugin>
        <plugin>
            <!-- For integration test separation -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
        </plugin>
        <plugin>
            <!-- For code coverage -->
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
        </plugin>
        ....

And in the reporting section

    <reporting>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-report-plugin</artifactId>
            <version>${maven.surefire.report.plugin}</version>
            <configuration>
                <showSuccess>false</showSuccess>
                <alwaysGenerateFailsafeReport>true</alwaysGenerateFailsafeReport>
                <alwaysGenerateSurefireReport>true</alwaysGenerateSurefireReport>
                <aggregate>true</aggregate>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.plugin.version}</version>
            <configuration>
                <excludes>
                    <exclude>**/*.mar</exclude>
                    <exclude>${jacoco.excludePattern}</exclude>
                </excludes>
            </configuration>
        </plugin>
     </plugins>
  </reporting>

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

Correct way of looping through C++ arrays

How about:

#include <iostream>
#include <array>
#include <algorithm>

int main ()
{
    std::array<std::string, 3> text = {"Apple", "Banana", "Orange"};
    std::for_each(text.begin(), text.end(), [](std::string &string){ std::cout << string << "\n"; });

    return 0;
}

Compiles and works with C++ 11 and has no 'raw' looping :)

How to disable sort in DataGridView?

Use LINQ:

Datagridview1.Columns.Cast<DataGridViewColumn>().ToList().ForEach(f => f.SortMode = DataGridViewColumnSortMode.NotSortable);

DataGrid get selected rows' column values

After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.

private void selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        facultyData row = (facultyData)facultyDataGrid.SelectedItem;
        facultyID_Textbox.Text = row.facultyID;
        lastName_TextBox.Text = row.lastName;
        firstName_TextBox.Text = row.firstName;
        middleName_TextBox.Text = row.middleName;
        age_TextBox.Text = row.age.ToString();
    }

}

class facultyData
{
    public ObjectId _id { get; set; }
    public string facultyID { get; set; }
    public string acadYear { get; set; }
    public string program { get; set; }   
}

jQuery - Appending a div to body, the body is the object?

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');

Format bytes to kilobytes, megabytes, gigabytes

Here is simplified implementation of the Drupal format_size function:

/**
 * Generates a string representation for the given byte count.
 *
 * @param $size
 *   A size in bytes.
 *
 * @return
 *   A string representation of the size.
 */
function format_size($size) {
  if ($size < 1024) {
    return $size . ' B';
  }
  else {
    $size = $size / 1024;
    $units = ['KB', 'MB', 'GB', 'TB'];
    foreach ($units as $unit) {
      if (round($size, 2) >= 1024) {
        $size = $size / 1024;
      }
      else {
        break;
      }
    }
    return round($size, 2) . ' ' . $unit;
  }
}

How to Create simple drag and Drop in angularjs

I'm a bit late to the party, but I have my own directive that looks like it'll fit your case (You can adapt it yourself). It's a modification of the ng-repeat directive that's specifically built for list re-ordering via DnD. I built it as I don't like JQuery UI (preference for less libraries than anything else) also I wanted mine to work on touch screens too ;).

Code is here: http://codepen.io/SimeonC/pen/AJIyC

Blog post is here: http://sdevgame.wordpress.com/2013/08/27/angularjs-drag-n-drop-re-order-in-ngrepeat/

Java Look and Feel (L&F)

You can also use JTattoo (http://www.jtattoo.net/), it has a couple of cool themes that can be used.

Just download the jar and import it into your classpath, or add it as a maven dependency:

<dependency>
        <groupId>com.jtattoo</groupId>
        <artifactId>JTattoo</artifactId>
        <version>1.6.11</version>
</dependency>

Here is a list of some of the cool themes they have available:

  • com.jtattoo.plaf.acryl.AcrylLookAndFeel
  • com.jtattoo.plaf.aero.AeroLookAndFeel
  • com.jtattoo.plaf.aluminium.AluminiumLookAndFeel
  • com.jtattoo.plaf.bernstein.BernsteinLookAndFeel
  • com.jtattoo.plaf.fast.FastLookAndFeel
  • com.jtattoo.plaf.graphite.GraphiteLookAndFeel
  • com.jtattoo.plaf.hifi.HiFiLookAndFeel
  • com.jtattoo.plaf.luna.LunaLookAndFeel
  • com.jtattoo.plaf.mcwin.McWinLookAndFeel
  • com.jtattoo.plaf.mint.MintLookAndFeel
  • com.jtattoo.plaf.noire.NoireLookAndFeel
  • com.jtattoo.plaf.smart.SmartLookAndFeel
  • com.jtattoo.plaf.texture.TextureLookAndFeel
  • com.jtattoo.plaf.custom.flx.FLXLookAndFeel

Regards

Java Initialize an int array in a constructor

why not simply

public Date(){
    data = new int[]{0,0,0};
}

the reason you got the error is because int[] data = ... declares a new variable and hides the field data

however it should be noted that the contents of the array are already initialized to 0 (the default value of int)

How to remove word wrap from textarea?

textarea {
  white-space: pre;
  overflow-wrap: normal;
  overflow-x: scroll;
}

white-space: nowrap also works if you don't care about whitespace, but of course you don't want that if you're working with code (or indented paragraphs or any content where there might deliberately be multiple spaces) ... so i prefer pre.

overflow-wrap: normal (was word-wrap in older browsers) is needed in case some parent has changed that setting; it can cause wrapping even if pre is set.

also -- contrary to the currently accepted answer -- textareas do often wrap by default. pre-wrap seems to be the default on my browser.

Android - java.lang.SecurityException: Permission Denial: starting Intent

Add android:exported="true" in your 'com.example.lib.MainActivity' activity tag.

From the android:exported documentation,

android:exported Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

From your logcat output, clearly a mismatch in uid is causing the issue. So adding the android:exported="true" should do the trick.

What is String pool in Java?

Let's start with a quote from the virtual machine spec:

Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.

This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:

1: a := "one" 
   --> if(pool[hash("one")] == null)  // true
           pool[hash("one") --> "one"]
       return pool[hash("one")]

2: b := "one" 
  --> if(pool[hash("one")] == null)   // false, "one" already in pool
        pool[hash("one") --> "one"]
      return pool[hash("one")] 

So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.

This is not the case if we use the constructor:

1: a := "one"
2: b := new String("one")

Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false

So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).

As programmers we don't have to care much about the String pool, as long as we keep in mind:

  • (a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
  • Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)

How do I erase an element from std::vector<> by index?

It may seem obvious to some people, but to elaborate on the above answers:

If you are doing removal of std::vector elements using erase in a loop over the whole vector, you should process your vector in reverse order, that is to say using

for (int i = v.size() - 1; i >= 0; i--)

instead of (the classical)

for (int i = 0; i < v.size(); i++)

The reason is that indices are affected by erase so if you remove the 4-th element, then the former 5-th element is now the new 4-th element, and it won't be processed by your loop if you're doing i++.

Below is a simple example illustrating this where I want to remove all the odds element of an int vector;

#include <iostream>
#include <vector>

using namespace std;

void printVector(const vector<int> &v)
{
    for (size_t i = 0; i < v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;
}

int main()
{    
    vector<int> v1, v2;
    for (int i = 0; i < 10; i++)
    {
        v1.push_back(i);
        v2.push_back(i);
    }

    // print v1
    cout << "v1: " << endl;
    printVector(v1);
    
    cout << endl;
    
    // print v2
    cout << "v2: " << endl;
    printVector(v2);
    
    // Erase all odd elements
    cout << "--- Erase odd elements ---" << endl;
    
    // loop with decreasing indices
    cout << "Process v2 with decreasing indices: " << endl;
    for (int i = v2.size() - 1; i >= 0; i--)
    {
        if (v2[i] % 2 != 0)
        {
            cout << "# ";
            v2.erase(v2.begin() + i);
        }
        else
        {
            cout << v2[i] << " ";
        }
    }
    cout << endl;
    cout << endl;
    
    // loop with increasing indices
    cout << "Process v1 with increasing indices: " << endl;
    for (int i = 0; i < v1.size(); i++)
    {
        if (v1[i] % 2 != 0)
        {
            cout << "# ";
            v1.erase(v1.begin() + i);
        }
        else
        {
            cout << v1[i] << " ";
        }
    }
    
    
    return 0;
}

Output:

v1:
0 1 2 3 4 5 6 7 8 9

v2:
0 1 2 3 4 5 6 7 8 9
--- Erase odd elements ---
Process v2 with decreasing indices:
# 8 # 6 # 4 # 2 # 0

Process v1 with increasing indices:
0 # # # # #

Note that on the second version with increasing indices, even numbers are not displayed as they are skipped because of i++

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

Git on Windows: How do you set up a mergetool?

I'm using Portable Git on WinXP (works a treat!), and needed to resolve a conflict that came up in branching. Of all the gui's I checked, KDiff3 proved to be the most transparent to use.

But I found the instructions I needed to get it working in Windows in this blog post, instructions which differ slightly from the other approaches listed here. It basically amounted to adding these lines to my .gitconfig file:

[merge]
    tool = kdiff3

[mergetool "kdiff3"]
    path = C:/YourPathToBinaryHere/KDiff3/kdiff3.exe
    keepBackup = false
    trustExitCode = false

Working nicely now!

How can I share Jupyter notebooks with non-programmers?

One more way to achieve this goal would be using JupyterHub.

With JupyterHub you can create a multi-user Hub which spawns, manages, and proxies multiple instances of the single-user Jupyter notebook server. Due to its flexibility and customization options, JupyterHub can be used to serve notebooks to a class of students, a corporate data science group, or a scientific research group.

enter image description here

What is the best way to call a script from another script?

This process is somewhat un-orthodox, but would work across all python versions,

Suppose you want to execute a script named 'recommend.py' inside an 'if' condition, then use,

if condition:
       import recommend

The technique is different, but works!

Zoom to fit all markers in Mapbox or Leaflet

The 'Answer' didn't work for me some reasons. So here is what I ended up doing:

////var group = new L.featureGroup(markerArray);//getting 'getBounds() not a function error.
////map.fitBounds(group.getBounds());
var bounds = L.latLngBounds(markerArray);
map.fitBounds(bounds);//works!

Delete rows with blank values in one particular column

An easy approach would be making all the blank cells NA and only keeping complete cases. You might also look for na.omit examples. It is a widely discussed topic.

df[df==""]<-NA
df<-df[complete.cases(df),]

ActiveModel::ForbiddenAttributesError when creating new user

If you are on Rails 4 and you get this error, it could happen if you are using enum on the model if you've defined with symbols like this:

class User
  enum preferred_phone: [:home_phone, :mobile_phone, :work_phone]
end

The form will pass say a radio selector as a string param. That's what happened in my case. The simple fix is to change enum to strings instead of symbols

enum preferred_phone: %w[home_phone mobile_phone work_phone]
# or more verbose
enum preferred_phone: ['home_phone', 'mobile_phone', 'work_phone']

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.

\begin{description} 
     <YOUR TEXT HERE> 
\end{description}
  • This only worked on windows latex compiler

How to save a PNG image server-side, from a base64 data string

based on drew010 example I made a working example for easy understanding.

imagesaver("data:image/jpeg;base64,/9j/4AAQSkZJ"); //use full base64 data 

function imagesaver($image_data){

    list($type, $data) = explode(';', $image_data); // exploding data for later checking and validating 

    if (preg_match('/^data:image\/(\w+);base64,/', $image_data, $type)) {
        $data = substr($data, strpos($data, ',') + 1);
        $type = strtolower($type[1]); // jpg, png, gif

        if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
            throw new \Exception('invalid image type');
        }

        $data = base64_decode($data);

        if ($data === false) {
            throw new \Exception('base64_decode failed');
        }
    } else {
        throw new \Exception('did not match data URI with image data');
    }

    $fullname = time().$type;

    if(file_put_contents($fullname, $data)){
        $result = $fullname;
    }else{
        $result =  "error";
    }
    /* it will return image name if image is saved successfully 
    or it will return error on failing to save image. */
    return $result; 
}

jQuery - Disable Form Fields

The jQuery docs say to use prop() for things like disabled, checked, etc. Also the more concise way is to use their selectors engine. So to disable all form elements in a div or form parent.

$myForm.find(':input:not(:disabled)').prop('disabled',true);

And to enable again you could do

$myForm.find(':input:disabled').prop('disabled',false);

How to import a jar in Eclipse

Adding external Jar is not smart in case you want to change the project location in filesystem.

The best way is to add the jar to build path so your project will compile if exported:

  1. Create a folder called lib in your project folder.

  2. copy to this folder all the jar files you need.

  3. Refresh your project in eclipse.

  4. Select all the jar files, then right click on one of them and select Build Path -> Add to Build Path

DateTime.TryParseExact() rejecting valid formats

Try:

 DateTime.TryParseExact(txtStartDate.Text, formats, 
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out startDate)

Generating Random Number In Each Row In Oracle Query

If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:

SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL

Getting realtime output using subprocess

You may use an iterator over each byte in the output of the subprocess. This allows inline update (lines ending with '\r' overwrite previous output line) from the subprocess:

from subprocess import PIPE, Popen

command = ["my_command", "-my_arg"]

# Open pipe to subprocess
subprocess = Popen(command, stdout=PIPE, stderr=PIPE)


# read each byte of subprocess
while subprocess.poll() is None:
    for c in iter(lambda: subprocess.stdout.read(1) if subprocess.poll() is None else {}, b''):
        c = c.decode('ascii')
        sys.stdout.write(c)
sys.stdout.flush()

if subprocess.returncode != 0:
    raise Exception("The subprocess did not terminate correctly.")

Oracle SQL Developer spool output?

Another way simpler than me has worked with SQL Developer 4 in Windows 7

spool "path_to_file\\filename.txt"
query to execute
spool of

You have to execute it as a script, because if not only the query will be saved in the output file In the path name I use the double character "\" as a separator when working with Windows and SQL, The output file will display the query and the result.

How can I extract a number from a string in JavaScript?

Use this one-line code to get the first number in a string without getting errors:

var myInt = parseInt(myString.replace(/^[^0-9]+/, ''), 10);

New features in java 7

New Feature of Java Standard Edition (JSE 7)

  1. Decorate Components with the JLayer Class:

    The JLayer class is a flexible and powerful decorator for Swing components. The JLayer class in Java SE 7 is similar in spirit to the JxLayer project project at java.net. The JLayer class was initially based on the JXLayer project, but its API evolved separately.

  2. Strings in switch Statement:

    In the JDK 7 , we can use a String object in the expression of a switch statement. The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

  3. Type Inference for Generic Instance:

    We can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond. Java SE 7 supports limited type inference for generic instance creation; you can only use type inference if the parameterized type of the constructor is obvious from the context. For example, the following example does not compile:

    List<String> l = new ArrayList<>();
    l.add("A");
    l.addAll(new ArrayList<>());
    

    In comparison, the following example compiles:

    List<? extends String> list2 = new ArrayList<>();
    l.addAll(list2);
    
  4. Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking:

    In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication. Consider the following code, which contains duplicate code in each of the catch blocks:

    catch (IOException e) {
        logger.log(e);
        throw e;
    }
    catch (SQLException e) {
        logger.log(e);
        throw e;
    }
    

    In releases prior to Java SE 7, it is difficult to create a common method to eliminate the duplicated code because the variable e has different types. The following example, which is valid in Java SE 7 and later, eliminates the duplicated code:

    catch (IOException|SQLException e) {
        logger.log(e);
        throw e;
    }
    

    The catch clause specifies the types of exceptions that the block can handle, and each exception type is separated with a vertical bar (|).

  5. The java.nio.file package

    The java.nio.file package and its related package, java.nio.file.attribute, provide comprehensive support for file I/O and for accessing the file system. A zip file system provider is also available in JDK 7.

Source: http://ohmjavaclasses.blogspot.com/

How to make execution pause, sleep, wait for X seconds in R?

See help(Sys.sleep).

For example, from ?Sys.sleep

testit <- function(x)
{
    p1 <- proc.time()
    Sys.sleep(x)
    proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)

Yielding

> testit(3.7)
   user  system elapsed 
  0.000   0.000   3.704 

Python nonlocal statement

@ooboo:

It takes the one "closest" to the point of reference in the source code. This is called "Lexical Scoping" and is standard for >40 years now.

Python's class members are really in a dictionary called __dict__ and will never be reached by lexical scoping.

If you don't specify nonlocal but do x = 7, it will create a new local variable "x". If you do specify nonlocal, it will find the "closest" "x" and assign to that. If you specify nonlocal and there is no "x", it will give you an error message.

The keyword global has always seemed strange to me since it will happily ignore all the other "x" except for the outermost one. Weird.

What is InputStream & Output Stream? Why and when do we use them?

An output stream is generally related to some data destination like a file or a network etc.In java output stream is a destination where data is eventually written and it ends

import java.io.printstream;

class PPrint {
    static PPrintStream oout = new PPrintStream();
}

class PPrintStream {
    void print(String str) { 
        System.out.println(str)
    }
}

class outputstreamDemo {
    public static void main(String args[]) {
        System.out.println("hello world");
        System.out.prinln("this is output stream demo");
    }
}

How to open select file dialog via js?

First Declare a variable to store filenames (to use them later):

var myfiles = [];

Open File Dialog

$('#browseBtn').click(function() {
    $('<input type="file" multiple>').on('change', function () {
        myfiles = this.files; //save selected files to the array
        console.log(myfiles); //show them on console
    }).click();
});

i'm posting it, so it may help someone because there are no clear instructions on the internet to how to store filenames into an array!

How do I create a Linked List Data Structure in Java?

Use java.util.LinkedList. Like this:

list = new java.util.LinkedList()

no sqljdbc_auth in java.library.path

To resolve I did the following:

  1. Copied sqljdbc_auth.dll into dir: C:\Windows\System32
  2. Restarted my application

How to exit an application properly

in this case I start Outlook and then close it

Dim ol 

Set ol = WScript.CreateObject("Outlook.Application") 'Starts Outlook

ol.quit 'Closes Outlook

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

SQL: ... WHERE X IN (SELECT Y FROM ...)

Any mature enough SQL database should be able to execute that just as effectively as the equivalent JOIN. Use whatever is more readable to you.

conversion from infix to prefix

(a–b)/c*(d + e – f / g)

remember scanning the expression from leftmost to right most start on parenthesized terms follow the WHICH COMES FIRST rule... *, /, % are on the same level and higher than + and -.... so (a-b) = -bc prefix (a-b) = bc- for postfix another parenthesized term: (d + e - f / g) = do move the / first then plus '+' comes first before minus sigh '-' (remember they are on the same level..) (d + e - f / g) move / first (d + e - (/fg)) = prefix (d + e - (fg/)) = postfix followed by + then - ((+de) - (/fg)) = prefix ((de+) - (fg/)) = postfix

(-(+de)(/fg)) = prefix so the new expression is now -+de/fg (1) ((de+)(fg/)-) = postfix so the new expression is now de+fg/- (2)

(a–b)/c* hence

  1. (a-b)/c*(d + e – f / g) = -bc prefix [-ab]/c*[-+de/fg] ---> taken from (1) / c * do not move yet so '/' comes first before '*' because they on the same level, move '/' to the rightmost : /[-ab]c * [-+de/fg] then move '*' to the rightmost

    • / [-ab]c[-+de/fg] = remove the grouping symbols = */-abc-+de/fg --> Prefix
  2. (a-b)/c*(d + e – f / g) = bc- for postfix [ab-]/c*[de+fg/-]---> taken from (2) so '/' comes first before '' because they on the same level, move '/' to the leftmost: [ab-]c[de+fg/-]/ then move '' to the leftmost [ab-] c [de+fg/-]/ = remove the grouping symbols= a b - c d e + f g / - / * --> Postfix

How do I parse a HTML page with Node.js

Use Cheerio. It isn't as strict as jsdom and is optimized for scraping. As a bonus, uses the jQuery selectors you already know.

? Familiar syntax: Cheerio implements a subset of core jQuery. Cheerio removes all the DOM inconsistencies and browser cruft from the jQuery library, revealing its truly gorgeous API.

? Blazingly fast: Cheerio works with a very simple, consistent DOM model. As a result parsing, manipulating, and rendering are incredibly efficient. Preliminary end-to-end benchmarks suggest that cheerio is about 8x faster than JSDOM.

? Insanely flexible: Cheerio wraps around @FB55's forgiving htmlparser. Cheerio can parse nearly any HTML or XML document.

Array definition in XML?

As its name is "numbers" it is clear it is a list of number... So an array of number... no need of the attribute type... Although I like the principle of specifying the type of field in a type attribute...

How to remove carriage return and newline from a variable in shell script

Because the file you source ends lines with carriage returns, the contents of $testVar are likely to look like this:

$ printf '%q\n' "$testVar"
$'value123\r'

(The first line's $ is the shell prompt; the second line's $ is from the %q formatting string, indicating $'' quoting.)

To get rid of the carriage return, you can use shell parameter expansion and ANSI-C quoting (requires Bash):

testVar=${testVar//$'\r'}

Which should result in

$ printf '%q\n' "$testVar"
value123

cannot convert data (type interface {}) to type string: need type assertion

According to the Go specification:

For an expression x of interface type and a type T, the primary expression x.(T) asserts that x is not nil and that the value stored in x is of type T.

A "type assertion" allows you to declare an interface value contains a certain concrete type or that its concrete type satisfies another interface.

In your example, you were asserting data (type interface{}) has the concrete type string. If you are wrong, the program will panic at runtime. You do not need to worry about efficiency, checking just requires comparing two pointer values.

If you were unsure if it was a string or not, you could test using the two return syntax.

str, ok := data.(string)

If data is not a string, ok will be false. It is then common to wrap such a statement into an if statement like so:

if str, ok := data.(string); ok {
    /* act on str */
} else {
    /* not string */
}

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

You have to import FormsModule into not only the root AppModule, but also into every subModule that uses any angular forms directives.

// SubModule A

import { CommonModule } from '@angular/common';
import { FormsModule }   from '@angular/forms';

@NgModule({
  imports: [
    CommonModule,
    FormsModule      //<----------make sure you have added this.
  ],
  ....
})

Check if space is in a string

There are a lot of ways to do that :

t = s.split(" ")
if len(t) > 1:
  print "several tokens"

To be sure it matches every kind of space, you can use re module :

import re
if re.search(r"\s", your_string):
  print "several words"

POI setting Cell Background to a Custom Color

You get this error because pallete is full. What you need to do is override preset color. Here is an example of function I'm using:

public HSSFColor setColor(HSSFWorkbook workbook, byte r,byte g, byte b){
    HSSFPalette palette = workbook.getCustomPalette();
    HSSFColor hssfColor = null;
    try {
        hssfColor= palette.findColor(r, g, b); 
        if (hssfColor == null ){
            palette.setColorAtIndex(HSSFColor.LAVENDER.index, r, g,b);
            hssfColor = palette.getColor(HSSFColor.LAVENDER.index);
        }
    } catch (Exception e) {
        logger.error(e);
    }

    return hssfColor;
}

And later use it for background color:

HSSFColor lightGray =  setColor(workbook,(byte) 0xE0, (byte)0xE0,(byte) 0xE0);
style2.setFillForegroundColor(lightGray.getIndex());
style2.setFillPattern(CellStyle.SOLID_FOREGROUND);

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

Socket.IO - how do I get a list of connected sockets/clients?

Here is a quick way to convert the hash of connected sockets from a namespace into an array using ES6 generators (applies to socket.io >= v1.0.0):

io.on('connection', function(socket) {
  var hash = io.of('/').connected
  var list = null

  hash[Symbol.iterator] = function*() {
    // for..of loop to invoke Object.keys() default iterator
    // to get the array values instead of the keys
    for(var id of Object.keys(hash)) yield hash[id]
  }

  list = [...hash]
  console.log(Array.isArray(list)) // true
})

Markdown open a new window link

As suggested by this answer:

[link](url){:target="_blank"}

Works for jekyll or more specifically kramdown, which is a superset of markdown, as part of Jekyll's (default) configuration. But not for plain markdown. ^_^

JSON: why are forward slashes escaped?

PHP escapes forward slashes by default which is probably why this appears so commonly. I'm not sure why, but possibly because embedding the string "</script>" inside a <script> tag is considered unsafe.

This functionality can be disabled by passing in the JSON_UNESCAPED_SLASHES flag but most developers will not use this since the original result is already valid JSON.

Freeze the top row for an html table only (Fixed Table Header Scrolling)

you can use two divs one for the headings and the other for the table. then use

#headings {
  position: fixed;
  top: 0px;
  width: 960px;
}

as @ptriek said this will only work for fixed width columns.

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

Failure [INSTALL_FAILED_INVALID_APK]

I ran into this issue by having mismatched build variants. A Dynamic Delivery module was on the debug variant while the remaining modules were on release. Simply changing the Dynamic Delivery module to release, rebuilding, and installing, fixed the issue.

How to run .NET Core console app from the command line

Using CMD you can run a console .net core project if .net core SDK is installed in your machine :

To run console project using windows command-Line, choose the specific path from your directory and type following below command

dotnet run

SQL Server : error converting data type varchar to numeric

If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:

Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.

Or TRY_CONVERT/TRY_CAST:

Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

Sorting std::map using value

A std::map sorted by it's value is in essence a std::set. By far the easiest way is to copy all entries in the map to a set (taken and adapted from here)

template <typename M, typename S> 
void MapToSet( const  M & m, S & s )
{
    typename M::const_iterator end = m.end();
    for( typename M::const_iterator it = m.begin(); it != end ; ++it )
    {
        s.insert( it->second );
    }
}

One caveat: if the map contains different keys with the same value, they will not be inserted into the set and be lost.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

No one mentioned the following, which in my understanding is the correct solution:

Go the csproj of the project where the nuget is installed, and set the AutoGEneratedBindingRedirects to false.

<AutoGenerateBindingRedirects>false</AutoGenerateBindingRedirects>

Full article in MSDN.

Changing default startup directory for command prompt in Windows 7

In the new Windows Terminal, you can click Settings and edit the line "startingDirectory" to achieve something similar.

Please note, however, that this changes the default startup directory only in Windows Terminal, and not for the command prompt globally.

Convert JSON array to an HTML table in jQuery

A still shorter way

$.makeTable = function (mydata) {
            if (mydata.length <= 0) return "";
           return $('<table border=1>').append("<tr>" + $.map(mydata[0], function (val, key) {
                return "<th>" + key + "</th>";
            }).join("\n") + "</tr>").append($.map(mydata, function (index, value) {
                return "<tr>" + $.map(index, function (val, key) {
                    return "<td>" + val + "</td>";
                }).join("\n") + "</tr>";
            }).join("\n"));
        };

How to grab substring before a specified character jQuery or JavaScript

//split string into an array and grab the first item

var streetaddress = addy.split(',')[0];

Also, I'd recommend naming your variables with camel-case(streetAddress) for better readability.

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

You need to tell Eclipse which JDK/JRE's you have installed and where they are located.

This is somewhat burried in the Eclipse preferences: In the Window-Menu select "Preferences". In the Preferences Tree, open the Node "Java" and select "Installed JRE's". Then click on the "Add"-Button in the Panel and select "Standard VM", "Next" and for "JRE Home" click on the "Directory"-Button and select the top level folder of the JDK you want to add.

Its easier than the description may make it look.

Hibernate JPA Sequence (non-Id)

I fixed the generation of UUID (or sequences) with Hibernate using @PrePersist annotation:

@PrePersist
public void initializeUUID() {
    if (uuid == null) {
        uuid = UUID.randomUUID().toString();
    }
}

What is the difference between Cloud, Grid and Cluster?

my two cents worth ~

Cloud refers to an (imaginary/easily scalable) unlimited space and processing power. The term shields the underlying technologies and highlights solely its unlimited storage-space and power.

Grid is a group of physically close-by machines setup. Term usually imply the processing power (ie:MFLOPS/GFLOPS), referred by engineers

Cluster is a set of logically connected machines/device (like a clusters of harddisk, cluster of database). Term highlights how devices are able to connect together and operate as a unit, referred by engineers

Writing to a TextBox from another thread?

Here is the what I have done to avoid CrossThreadException and writing to the textbox from another thread.

Here is my Button.Click function- I want to generate a random number of threads and then get their IDs by calling the getID() method and the TextBox value while being in that worker thread.

private void btnAppend_Click(object sender, EventArgs e) 
{
    Random n = new Random();

    for (int i = 0; i < n.Next(1,5); i++)
    {
        label2.Text = "UI Id" + ((Thread.CurrentThread.ManagedThreadId).ToString());
        Thread t = new Thread(getId);
        t.Start();
    }
}

Here is getId (workerThread) code:

public void getId()
{
    int id = Thread.CurrentThread.ManagedThreadId;
    //Note that, I have collected threadId just before calling this.Invoke
    //method else it would be same as of UI thread inside the below code block 
    this.Invoke((MethodInvoker)delegate ()
    {
        inpTxt.Text += "My id is" +"--"+id+Environment.NewLine; 
    });
}

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

Javascript window.open pass values using POST

Thank you php-b-grader. I improved the code, it is not necessary to use window.open(), the target is already specified in the form.

// Create a form
var mapForm = document.createElement("form");
mapForm.target = "_blank";    
mapForm.method = "POST";
mapForm.action = "abmCatalogs.ftl";

// Create an input
var mapInput = document.createElement("input");
mapInput.type = "text";
mapInput.name = "variable";
mapInput.value = "lalalalala";

// Add the input to the form
mapForm.appendChild(mapInput);

// Add the form to dom
document.body.appendChild(mapForm);

// Just submit
mapForm.submit();

for target options --> w3schools - Target

The most efficient way to remove first N elements in a list?

l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.

This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.

l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.

XAMPP - MySQL shutdown unexpectedly

If any of the things above do not work, make a back of Xampp directory and reinstall Xampp. That surely works!

How to filter in NaN (pandas)?

This doesn't work because NaN isn't equal to anything, including NaN. Use pd.isnull(df.var2) instead.

Case Insensitive String comp in C

As others have stated, there is no portable function that works on all systems. You can partially circumvent this with simple ifdef:

#include <stdio.h>

#ifdef _WIN32
#include <string.h>
#define strcasecmp _stricmp
#else // assuming POSIX or BSD compliant system
#include <strings.h>
#endif

int main() {
    printf("%d", strcasecmp("teSt", "TEst"));
}

Map vs Object in JavaScript

When to use Maps instead of plain JavaScript Objects ?

The plain JavaScript Object { key: 'value' } holds structured data. But plain JS object has its limitations :

  1. Only strings and symbols can be used as keys of Objects. If we use any other things say, numbers as keys of an object then during accessing those keys we will see those keys will be converted into strings implicitly causing us to lose consistency of types. const names= {1: 'one', 2: 'two'}; Object.keys(names); // ['1', '2']

  2. There are chances of accidentally overwriting inherited properties from prototypes by writing JS identifiers as key names of an object (e.g. toString, constructor etc.)

  3. Another object cannot be used as key of an object, so no extra information can be written for an object by writing that object as key of another object and value of that another object will contain the extra information

  4. Objects are not iterators

  5. The size of an object cannot be determined directly

These limitations of Objects are solved by Maps but we must consider Maps as complement for Objects instead of replacement. Basically Map is just array of arrays but we must pass that array of arrays to the Map object as argument with new keyword otherwise only for array of arrays the useful properties and methods of Map aren't available. And remember key-value pairs inside the array of arrays or the Map must be separated by commas only, no colons like in plain objects.

3 tips to decide whether to use a Map or an Object :

  1. Use maps over objects when keys are unknown until run time because keys formed by user input or unknowingly can break the code which uses the object if those keys overwrite the inherited properties of the object, so map is safer in those cases. Also use maps when all keys are the same type and all maps are the same type.

  2. Use maps if there is a need to store primitive values as keys.

  3. Use objects if we need to operate on individual elements.

Benefits of using Maps are :

1. Map accepts any key type and preserves the type of key :

We know that if the object's key is not a string or symbol then JS implicitly transforms it into a string. On the contrary, Map accepts any type of keys : string, number, boolean, symbol etc. and Map preserves the original key type. Here we will use number as key inside a Map and it will remain a number :

const numbersMap= new Map();

numbersMap.set(1, 'one');

numbersMap.set(2, 'two');

const keysOfMap= [...numbersMap.keys()];

console.log(keysOfMap);                        // [1, 2]

Inside a Map we can even use an entire object as a key. There may be times when we want to store some object related data, without attaching this data inside the object itself so that we can work with lean objects but want to store some information about the object. In those cases we need to use Map so that we can make Object as key and related data of the object as value.

const foo= {name: foo};

const bar= {name: bar};

const kindOfMap= [[foo, 'Foo related data'], [bar, 'Bar related data']];

But the downside of this approach is the complexity of accessing the value by key, as we have to loop through the entire array to get the desired value.

function getBy Key(kindOfMap, key) {
    for (const [k, v]  of kindOfMap) {
        if(key === k) {
            return v;
        }
    }
    return undefined;
}

getByKey(kindOfMap, foo);            // 'Foo related data'

We can solve this problem of not getting direct access to the value by using a proper Map.

const foo= {name: 'foo'};

const bar= {name: 'bar'};

const myMap= new Map();

myMap.set(foo, 'Foo related data');
myMap.set(bar, 'Bar related data');

console.log(myMap.get(foo));            // 'Foo related data'

We could have done this using WeakMap, just have to write, const myMap= new WeakMap( ). The differences between Map and WeakMap are that WeakMap allows for garbage collection of keys (here objects) so it prevents memory leaks, WeakMap accepts only objects as keys, and WeakMap has reduced set of methods.

2. Map has no restriction over key names :

For plain JS objects we can accidentally overwrite property inherited from the prototype and it can be dangerous. Here we will overwrite the toString( ) property of the actor object :

const actor= {
    name: 'Harrison Ford',
    toString: 'Actor: Harrison Ford'
};

Now let's define a fn isPlainObject( ) to determine if the supplied argument is a plain object and this fn uses toString( ) method to check it :

function isPlainObject(value) {
    return value.toString() === '[object Object]';
}

isPlainObject(actor);        // TypeError : value.toString is not a function

// this is because inside actor object toString property is a string instead of inherited method from prototype

The Map does not have any restrictions on the key names, we can use key names like toString, constructor etc. Here although actorMap object has a property named toString but the method toString( ) inherited from prototype of actorMap object works perfectly.

const actorMap= new Map();

actorMap.set('name', 'Harrison Ford');

actorMap.set('toString', 'Actor: Harrison Ford');

function isMap(value) {
  return value.toString() === '[object Map]';
}

console.log(isMap(actorMap));     // true

If we have a situation where user input creates keys then we must take those keys inside a Map instead of a plain object. This is because user may choose a custom field name like, toString, constructor etc. then such key names in a plain object can potentially break the code that later uses this object. So the right solution is to bind the user interface state to a map, there is no way to break the Map :

const userCustomFieldsMap= new Map([['color', 'blue'], ['size', 'medium'], ['toString', 'A blue box']]);

3. Map is iterable :

To iterate a plain object's properties we need Object.entries( ) or Object.keys( ). The Object.entries(plainObject) returns an array of key value pairs extracted from the object, we can then destructure those keys and values and can get normal keys and values output.

const colorHex= {
  'white': '#FFFFFF',
  'black': '#000000'
}

for(const [color, hex] of Object.entries(colorHex)) {
  console.log(color, hex);
}
//
'white' '#FFFFFF'   
'black' '#000000'

As Maps are iterable that's why we do not need entries( ) methods to iterate over a Map and destructuring of key, value array can be done directly on the Map as inside a Map each element lives as an array of key value pairs separated by commas.

const colorHexMap= new Map();
colorHexMap.set('white', '#FFFFFF');
colorHexMap.set('black', '#000000');


for(const [color, hex] of colorHexMap) {
  console.log(color, hex);
}
//'white' '#FFFFFF'   'black' '#000000'

Also map.keys( ) returns an iterator over keys and map.values( ) returns an iterator over values.

4. We can easily know the size of a Map

We cannot directly determine the number of properties in a plain object. We need a helper fn like, Object.keys( ) which returns an array with keys of the object then using length property we can get the number of keys or the size of the plain object.

const exams= {'John Rambo': '80%', 'James Bond': '60%'};

const sizeOfObj= Object.keys(exams).length;

console.log(sizeOfObj);       // 2

But in the case of Maps we can have direct access to the size of the Map using map.size property.

const examsMap= new Map([['John Rambo', '80%'], ['James Bond', '60%']]);

console.log(examsMap.size);

cannot download, $GOPATH not set

This one worked

Setting up Go development environment on Ubuntu, and how to fix $GOPATH / $GOROOT

Steps

mkdir ~/go

Set $GOPATH in .bashrc,

export GOPATH=~/go
export PATH=$PATH:$GOPATH/bin

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Finally got this error to go away on a restore. I moved to SQL2012 out of frustration, but I guess this would probably still work on 2008R2. I had to use the logical names:

RESTORE FILELISTONLY
FROM DISK = ‘location of your.bak file’

And from there I ran a restore statement with MOVE using logical names.

RESTORE DATABASE database1
FROM DISK = '\\database path\database.bak'
WITH
MOVE 'File_Data' TO 'E:\location\database.mdf',
MOVE 'File_DOCS' TO 'E:\location\database_1.ndf',
MOVE 'file' TO 'E:\location\database_2.ndf',
MOVE 'file' TO 'E:\location\database_3.ndf',
MOVE 'file_Log' TO 'E:\location\database.ldf'

When it was done restoring, I almost wept with joy.

Good luck!

Cannot assign requested address - possible causes?

Okay, my problem wasn't the port, but the binding address. My server has an internal address (10.0.0.4) and an external address (52.175.223.XX). When I tried connecting with:

$sock = @stream_socket_server('tcp://52.175.223.XX:123', $errNo, $errStr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN);

It failed because the local socket was 10.0.0.4 and not the external 52.175.223.XX. You can checkout the local available interfaces with sudo ifconfig.

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

How do I remove the old history from a git repository?

Just create a graft of the parent of your new root commit to no parent (or to an empty commit, e.g. the real root commit of your repository). E.g. echo "<NEW-ROOT-SHA1>" > .git/info/grafts

After creating the graft, it takes effect right away; you should be able to look at git log and see that the unwanted old commits have gone away:

$ echo 4a46bc886318679d8b15e05aea40b83ff6c3bd47 > .git/info/grafts
$ git log --decorate | tail --lines=11
commit cb3da2d4d8c3378919844b29e815bfd5fdc0210c
Author: Your Name <[email protected]>
Date:   Fri May 24 14:04:10 2013 +0200

    Another message

commit 4a46bc886318679d8b15e05aea40b83ff6c3bd47 (grafted)
Author: Your Name <[email protected]>
Date:   Thu May 23 22:27:48 2013 +0200

    Some message

If all looks as intended, you can just do a simple git filter-branch -- --all to make it permanent.

BEWARE: after doing the filter-branch step, all commit ids will have changed, so anybody using the old repo must never merge with anyone using the new repo.

Disable future dates in jQuery UI Datepicker

$(function() { $("#datepicker").datepicker({  maxDate: '0'}); });

Page redirect with successful Ajax request

Sure. Just put something at the the end of your success function like:

if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"

where your server returns the response no_errors when there are no errors present.

html text input onchange event

Use the oninput event

<input type="text" oninput="myFunction();" />

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

Invoking Java main method with parameters from Eclipse

This answer is based on Eclipse 3.4, but should work in older versions of Eclipse.

When selecting Run As..., go into the run configurations.

On the Arguments tab of your Java run configuration, configure the variable ${string_prompt} to appear (you can click variables to get it, or copy that to set it directly).

Every time you use that run configuration (name it well so you have it for later), you will be prompted for the command line arguments.

What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

I have tried to make note about these and have collected and written examples from a java perspective.

HTTP for Java Developers

Reverse Ajax - Old style

Async Handling on server side

Reverse Ajax - New style

Server Sent Events

Putting it here for any java developer who is looking into the same subject.

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

What does !important mean in CSS?

It changes the rules for override priority of css cascades. See the CSS2 spec.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

python object() takes no parameters error

I too got this error. Incidentally, i typed __int__ instead of __init__.

I think, in many mistype cases the IDE i am using (IntelliJ) would have changed the color to the default set for Function definition. But, in my case __int__ being another dunder/magic method, color remained same as the one which IDE displays for __init__ (default Predefined item definition color), which took me some time in spotting the missing i.

How to set the authorization header using curl

http://curl.haxx.se/docs/httpscripting.html

See part 6. HTTP Authentication

HTTP Authentication

HTTP Authentication is the ability to tell the server your username and password so that it can verify that you're allowed to do the request you're doing. The Basic authentication used in HTTP (which is the type curl uses by default) is plain text based, which means it sends username and password only slightly obfuscated, but still fully readable by anyone that sniffs on the network between you and the remote server.

To tell curl to use a user and password for authentication:

curl --user name:password http://www.example.com

The site might require a different authentication method (check the headers returned by the server), and then --ntlm, --digest, --negotiate or even --anyauth might be options that suit you.

Sometimes your HTTP access is only available through the use of a HTTP proxy. This seems to be especially common at various companies. A HTTP proxy may require its own user and password to allow the client to get through to the Internet. To specify those with curl, run something like:

curl --proxy-user proxyuser:proxypassword curl.haxx.se

If your proxy requires the authentication to be done using the NTLM method, use --proxy-ntlm, if it requires Digest use --proxy-digest.

If you use any one these user+password options but leave out the password part, curl will prompt for the password interactively.

Do note that when a program is run, its parameters might be possible to see when listing the running processes of the system. Thus, other users may be able to watch your passwords if you pass them as plain command line options. There are ways to circumvent this.

It is worth noting that while this is how HTTP Authentication works, very many web sites will not use this concept when they provide logins etc. See the Web Login chapter further below for more details on that.

Modifying Objects within stream in Java8 while iterating

Yes, you can modify state of objects inside your stream, but most often you should avoid modifying state of source of stream. From non-interference section of stream package documentation we can read that:

For most data sources, preventing interference means ensuring that the data source is not modified at all during the execution of the stream pipeline. The notable exception to this are streams whose sources are concurrent collections, which are specifically designed to handle concurrent modification. Concurrent stream sources are those whose Spliterator reports the CONCURRENT characteristic.

So this is OK

  List<User> users = getUsers();
  users.stream().forEach(u -> u.setProperty(value));
//                       ^    ^^^^^^^^^^^^^

but this in most cases is not

  users.stream().forEach(u -> users.remove(u));
//^^^^^                       ^^^^^^^^^^^^

and may throw ConcurrentModificationException or even other unexpected exceptions like NPE:

List<Integer> list = IntStream.range(0, 10).boxed().collect(Collectors.toList());

list.stream()
    .filter(i -> i > 5)
    .forEach(i -> list.remove(i));  //throws NullPointerException

Determine if JavaScript value is an "integer"?

Use jQuery's IsNumeric method.

http://api.jquery.com/jQuery.isNumeric/

if ($.isNumeric(id)) {
   //it's numeric
}

CORRECTION: that would not ensure an integer. This would:

if ( (id+"").match(/^\d+$/) ) {
   //it's all digits
}

That, of course, doesn't use jQuery, but I assume jQuery isn't actually mandatory as long as the solution works

Run bash script from Windows PowerShell

There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash: Bash on Windows

You can run Bash script like bash ./script.sh, but keep in mind that C drive is located at /mnt/c, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.

Also, even as root, you can still get permission denied when moving files around in /mnt, but you have your full root power in the / file system.

Also make sure your shell script is formatted with Unix style, or there can be errors. Example script

How to quickly and conveniently create a one element arraylist

The other answers all use Arrays.asList(), which returns an unmodifiable list (an UnsupportedOperationException is thrown if you try to add or remove an element). To get a mutable list you can wrap the returned list in a new ArrayList as a couple of answers point out, but a cleaner solution is to use Guava's Lists.newArrayList() (available since at least Guava 10, released in 2011).

For example:

Lists.newArrayList("Blargle!");

for-in statement

TypeScript isn't giving you a gun to shoot yourself in the foot with.

The iterator variable is a string because it is a string, full stop. Observe:

var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';

for(var key in obj) {
    console.log('Type: ' + typeof key);
    console.log(key + ' => ' + obj[key]);
}

How many key/value pairs are in obj now? 6, more or less? No, 3, and all of the keys are strings:

Type: string
0 => zero point zero
Type: string
[object Object] => this obj; 
Type: string
undefined => the literal string "undefined" 

Sockets - How to find out what port and address I'm assigned

The comment in your code is wrong. INADDR_ANY doesn't put server's IP automatically'. It essentially puts 0.0.0.0, for the reasons explained in mark4o's answer.

Left/Right float button inside div

Change display:inline to display:inline-block

.test {
  width:200px;
  display:inline-block;
  overflow: auto;
  white-space: nowrap;
  margin:0px auto;
  border:1px red solid;
}

How do you convert a time.struct_time object into a datetime object?

Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.

from datetime import datetime
from time import mktime

dt = datetime.fromtimestamp(mktime(struct))

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

type in Terminal:

$ mvn --version

then get following result:

Apache Maven 3.0.5 (r01de14724cdef164cd33c7c8c2fe155faf9602da; 2013-02-19 16:51:28+0300)
Maven home: /opt/local/share/java/maven3
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: ru_RU, platform encoding: MacCyrillic
OS name: "mac os x", version: "10.9.4", arch: "x86_64", family: "mac"

here in second line we have:

Maven home: /opt/local/share/java/maven3

type this path into field on configuration dialog. That's all to fix!

Whoops, looks like something went wrong. Laravel 5.0

Simply type in terminal in your command prompt go to laravel directory path and type php artisan key:generate then key will be generated. Paste that key in config/app.php key variable. Your problem will be solved. I also did like that inorder to solve the problem...

How to scanf only integer?

Using fgets() is better.

To solve only using scanf() for input, scan for an int and the following char.

int ReadUntilEOL(void) {
  char ch;
  int count;
  while ((count = scanf("%c", &ch)) == 1 && ch != '\n')
    ; // Consume char until \n or EOF or IO error
  return count;
}

#include<stdio.h>
int main(void) {
  int n;

  for (;;) {
    printf("Please enter an integer: ");
    char NextChar = '\n';
    int count = scanf("%d%c", &n, &NextChar);
    if (count >= 1 && NextChar == '\n') 
      break;
    if (ReadUntilEOL() == EOF) 
      return 1;  // No valid input ever found
  }
  printf("You entered: %d\n", n);
  return 0;
}

This approach does not re-prompt if user only enters white-space such as only Enter.

How can I schedule a job to run a SQL query daily?

  1. Expand the SQL Server Agent node and right click the Jobs node in SQL Server Agent and select 'New Job'

  2. In the 'New Job' window enter the name of the job and a description on the 'General' tab.

  3. Select 'Steps' on the left hand side of the window and click 'New' at the bottom.

  4. In the 'Steps' window enter a step name and select the database you want the query to run against.

  5. Paste in the T-SQL command you want to run into the Command window and click 'OK'.

  6. Click on the 'Schedule' menu on the left of the New Job window and enter the schedule information (e.g. daily and a time).

  7. Click 'OK' - and that should be it.

(There are of course other options you can add - but I would say that is the bare minimum you need to get a job set up and scheduled)

"Default Activity Not Found" on Android Studio upgrade

Nothing above helped me. After some time I found that IDEA changed action names to uppercase. Like:

<intent-filter>
  <action android:name="ANDROID.INTENT.ACTION.MAIN"/>
  <category android:name="ANDROID.INTENT.CATEGORY.LAUNCHER"/>
</intent-filter>

After reverting to normal, IDEA recognizes default activity:

<intent-filter>
  <action android:name="android.intent.action.MAIN" />
  <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

How to open the terminal in Atom?

First, you should install "platformio-ide-terminal": Open "Preferences ?," >> Click "+ Install" >> In "Search packages" type "platformio-ide-terminal" >> Click "Install".

And answering exactly the question. If you have previously installed, just use:

  • Shortcut: ctrl-` or Option+Command+T (??T)
  • by Menu: Go to Packages > platformio-ide-terminal [or other] > New terminal

HTML5 placeholder css padding

I have tested almost all methods given here in this page for my Angular app. Only I found solution via &nbsp; that inserts spaces i.e.

Angular Material

add &nbsp; in the placeholder, like

<input matInput type="text" placeholder="&nbsp;&nbsp;Email">

Non Angular Material

Add padding to your input field, like below. Click Run Code Snippet to see demo

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>

<div class="container m-3 d-flex flex-column align-items-center justify-content-around" style="height:100px;">
<input type="text" class="pl-0" placeholder="Email with no Padding" style="width:240px;">
<input type="text" class="pl-3" placeholder="Email with 1 rem padding" style="width:240px;">
</div>
_x000D_
_x000D_
_x000D_

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

None of the solutions mentioned here worked for me - I am using SQL Server Management Studio 2014.

Instead I had to uncheck the "Take tail-log backup before restore" checkbox in the "Options" screen: in my version it is checked by default and prevents the Restore operation to be completed. After unchecking it, the Restore operation proceeded without issues.

enter image description here

C# generics syntax for multiple type parameter constraints

void foo<TOne, TTwo>() 
   where TOne : BaseOne
   where TTwo : BaseTwo

More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

Declare a dictionary inside a static class

You can use the static/class constructor to initialize your dictionary:

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic;
    public static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

Passing multiple variables to another page in url

Short answer:

This is what you are trying to do but it poses some security and encoding problems so don't do it.

$url = "http://localhost/main.php?email=" . $email_address . "&eventid=" . $event_id;

Long answer:

All variables in querystrings need to be urlencoded to ensure proper transmission. You should never pass a user's personal information in a url because urls are very leaky. Urls end up in log files, browsing histories, referal headers, etc. The list goes on and on.

As for proper url encoding, it can be achieved using either urlencode() or http_build_query(). Either one of these should work:

$url = "http://localhost/main.php?email=" . urlencode($email_address) . "&eventid=" . urlencode($event_id);

or

$vars = array('email' => $email_address, 'event_id' => $event_id);
$querystring = http_build_query($vars);
$url = "http://localhost/main.php?" . $querystring;

Additionally, if $event_id is in your session, you don't actually need to pass it around in order to access it from different pages. Just call session_start() and it should be available.

Split Strings into words with multiple word boundary delimiters

join = lambda x: sum(x,[])  # a.k.a. flatten1([[1],[2,3],[4]]) -> [1,2,3,4]
# ...alternatively...
join = lambda lists: [x for l in lists for x in l]

Then this becomes a three-liner:

fragments = [text]
for token in tokens:
    fragments = join(f.split(token) for f in fragments)

Explanation

This is what in Haskell is known as the List monad. The idea behind the monad is that once "in the monad" you "stay in the monad" until something takes you out. For example in Haskell, say you map the python range(n) -> [1,2,...,n] function over a List. If the result is a List, it will be append to the List in-place, so you'd get something like map(range, [3,4,1]) -> [0,1,2,0,1,2,3,0]. This is known as map-append (or mappend, or maybe something like that). The idea here is that you've got this operation you're applying (splitting on a token), and whenever you do that, you join the result into the list.

You can abstract this into a function and have tokens=string.punctuation by default.

Advantages of this approach:

  • This approach (unlike naive regex-based approaches) can work with arbitrary-length tokens (which regex can also do with more advanced syntax).
  • You are not restricted to mere tokens; you could have arbitrary logic in place of each token, for example one of the "tokens" could be a function which splits according to how nested parentheses are.

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

In JDBC world, the normal practice (according the JDBC API) is that you use Class#forName() to load a JDBC driver. The JDBC driver should namely register itself in DriverManager inside a static block:

package com.dbvendor.jdbc;

import java.sql.Driver;
import java.sql.DriverManager;

public class MyDriver implements Driver {

    static {
        DriverManager.registerDriver(new MyDriver());
    }

    public MyDriver() {
        //
    }

}

Invoking Class#forName() will execute all static initializers. This way the DriverManager can find the associated driver among the registered drivers by connection URL during getConnection() which roughly look like follows:

public static Connection getConnection(String url) throws SQLException {
    for (Driver driver : registeredDrivers) {
        if (driver.acceptsURL(url)) {
            return driver.connect(url);
        }
    }
    throw new SQLException("No suitable driver");
}

But there were also buggy JDBC drivers, starting with the org.gjt.mm.mysql.Driver as well known example, which incorrectly registers itself inside the Constructor instead of a static block:

package com.dbvendor.jdbc;

import java.sql.Driver;
import java.sql.DriverManager;

public class BadDriver implements Driver {

    public BadDriver() {
        DriverManager.registerDriver(this);
    }

}

The only way to get it to work dynamically is to call newInstance() afterwards! Otherwise you will face at first sight unexplainable "SQLException: no suitable driver". Once again, this is a bug in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the newInstance() away.

Retrieve CPU usage and memory usage of a single process on Linux?

Based on @caf's answer, this working nicely for me.

Calculate average for given PID:

measure.sh

times=100
total=0
for i in $(seq 1 $times)
do
   OUTPUT=$(top -b -n 1 -d 0.1 -p $1 | tail -1 | awk '{print $9}')
   echo -n "$i time: ${OUTPUT}"\\r
   total=`echo "$total + $OUTPUT" | bc -l`
done
#echo "Average: $total / $times" | bc

average=`echo "scale=2; $total / $times" | bc`
echo "Average: $average"

Usage:

# send PID as argument
sh measure.sh 3282

AngularJS ngClass conditional

There is a simple method which you could use with html class attribute and shorthand if/else. No need to make it so complex. Just use following method.

<div class="{{expression == true ? 'class_if_expression_true' : 'class_if_expression_false' }}">Your Content</div>

Happy Coding, Nimantha Perera

Set focus to field in dynamically loaded DIV

Yes, this happens when manipulating an element which doesn't exist yet (a few contributors here also made a good point with the unique ID). I ran into a similar issue. I also need to pass an argument to the function manipulating the element soon to be rendered.

The solution checked off here didn't help me. Finally I found one that worked right out of the box. And it's very pretty, too - a callback.

Instead of:

$( '#header' ).focus();
or the tempting:
setTimeout( $( '#header' ).focus(), 500 );

Try this:

setTimeout( function() { $( '#header' ).focus() }, 500 );

In my code, testing passing the argument, this didn't work, the timeout was ignored:

setTimeout( alert( 'Hello, '+name ), 1000 );

This works, the timeout ticks:

setTimeout( function() { alert( 'Hello, '+name ) }, 1000 );

It sucks that w3schools doesn't mention it.

Credits go to: makemineatriple.com.

Hopefully, this helps somebody who comes here.

Android - How to achieve setOnClickListener in Kotlin?

You can use setOnClickListener like this in Kotlin

button.setOnClickListener(View.OnClickListener {        
       //code
})

How to set a hidden value in Razor

There is a Hidden helper alongside HiddenFor which lets you set the value.

@Html.Hidden("RequiredProperty", "default")

EDIT Based on the edit you've made to the question, you could do this, but I believe you're moving into territory where it will be cheaper and more effective, in the long run, to fight for making the code change. As has been said, even by yourself, the controller or view model should be setting the default.

This code:

<ul>
@{
        var stacks = new System.Diagnostics.StackTrace().GetFrames();
        foreach (var frame in stacks)
        {
            <li>@frame.GetMethod().Name - @frame.GetMethod().DeclaringType</li>
        }
}
</ul>

Will give output like this:

Execute - ASP._Page_Views_ViewDirectoryX__SubView_cshtml
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
ExecutePageHierarchy - System.Web.Mvc.WebViewPage
ExecutePageHierarchy - System.Web.WebPages.WebPageBase
RenderView - System.Web.Mvc.RazorView
Render - System.Web.Mvc.BuildManagerCompiledView
RenderPartialInternal - System.Web.Mvc.HtmlHelper
RenderPartial - System.Web.Mvc.Html.RenderPartialExtensions
Execute - ASP._Page_Views_ViewDirectoryY__MainView_cshtml

So assuming the MVC framework will always go through the same stack, you can grab var frame = stacks[8]; and use the declaring type to determine who your parent view is, and then use that determination to set (or not) the default value. You could also walk the stack instead of directly grabbing [8] which would be safer but even less efficient.

Best way to initialize (empty) array in PHP

Try this:

    $arr = (array) null;
    var_dump($arr);

    // will print
    // array(0) { }

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources: