Programs & Examples On #Ora 00934

ORA-00934: group function is not allowed here

MAX(DATE) - SQL ORACLE

Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:

SELECT
  max(MEMBSHIP_ID)
  keep (
      dense_rank first
      order by paym_date desc NULLS LAST
  ) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

What is a clean, Pythonic way to have multiple constructors in Python?

class Cheese:
    def __init__(self, *args, **kwargs):
        """A user-friendly initialiser for the general-purpose constructor.
        """
        ...

    def _init_parmesan(self, *args, **kwargs):
        """A special initialiser for Parmesan cheese.
        """
        ...

    def _init_gauda(self, *args, **kwargs):
        """A special initialiser for Gauda cheese.
        """
        ...

    @classmethod
    def make_parmesan(cls, *args, **kwargs):
        new = cls.__new__(cls)
        new._init_parmesan(*args, **kwargs)
        return new

    @classmethod
    def make_gauda(cls, *args, **kwargs):
        new = cls.__new__(cls)
        new._init_gauda(*args, **kwargs)
        return new

Scheduled run of stored procedure on SQL server

I'll add one thing: where I'm at we used to have a bunch of batch jobs that ran every night. However, we're moving away from that to using a client application scheduled in windows scheduled tasks that kicks off each job. There are (at least) three reasons for this:

  1. We have some console programs that need to run every night as well. This way all scheduled tasks can be in one place. Of course, this creates a single point of failure, but if the console jobs don't run we're gonna lose a day's work the next day anyway.
  2. The program that kicks off the jobs captures print messages and errors from the server and writes them to a common application log for all our batch processes. It makes logging from withing the sql jobs much simpler.
  3. If we ever need to upgrade the server (and we are hoping to do this soon) we don't need to worry about moving the jobs over. Just re-point the application once.

It's a real short VB.Net app: I can post code if any one is interested.

What is an OS kernel ? How does it differ from an operating system?

Simple Answer

The Kernel is the core piece of the operating system. It is not necessarily an operating system in and of itself.

Everything else is built around it.

Ellaborate Definition

Kernel (computing) - Wikipedia

Extracting text OpenCV

I used a gradient based method in the program below. Added the resulting images. Please note that I'm using a scaled down version of the image for processing.

c++ version

The MIT License (MIT)

Copyright (c) 2014 Dhanushka Dangampola

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

#include "stdafx.h"

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

using namespace cv;
using namespace std;

#define INPUT_FILE              "1.jpg"
#define OUTPUT_FOLDER_PATH      string("")

int _tmain(int argc, _TCHAR* argv[])
{
    Mat large = imread(INPUT_FILE);
    Mat rgb;
    // downsample and use it for processing
    pyrDown(large, rgb);
    Mat small;
    cvtColor(rgb, small, CV_BGR2GRAY);
    // morphological gradient
    Mat grad;
    Mat morphKernel = getStructuringElement(MORPH_ELLIPSE, Size(3, 3));
    morphologyEx(small, grad, MORPH_GRADIENT, morphKernel);
    // binarize
    Mat bw;
    threshold(grad, bw, 0.0, 255.0, THRESH_BINARY | THRESH_OTSU);
    // connect horizontally oriented regions
    Mat connected;
    morphKernel = getStructuringElement(MORPH_RECT, Size(9, 1));
    morphologyEx(bw, connected, MORPH_CLOSE, morphKernel);
    // find contours
    Mat mask = Mat::zeros(bw.size(), CV_8UC1);
    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    findContours(connected, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
    // filter contours
    for(int idx = 0; idx >= 0; idx = hierarchy[idx][0])
    {
        Rect rect = boundingRect(contours[idx]);
        Mat maskROI(mask, rect);
        maskROI = Scalar(0, 0, 0);
        // fill the contour
        drawContours(mask, contours, idx, Scalar(255, 255, 255), CV_FILLED);
        // ratio of non-zero pixels in the filled region
        double r = (double)countNonZero(maskROI)/(rect.width*rect.height);

        if (r > .45 /* assume at least 45% of the area is filled if it contains text */
            && 
            (rect.height > 8 && rect.width > 8) /* constraints on region size */
            /* these two conditions alone are not very robust. better to use something 
            like the number of significant peaks in a horizontal projection as a third condition */
            )
        {
            rectangle(rgb, rect, Scalar(0, 255, 0), 2);
        }
    }
    imwrite(OUTPUT_FOLDER_PATH + string("rgb.jpg"), rgb);

    return 0;
}

python version

The MIT License (MIT)

Copyright (c) 2017 Dhanushka Dangampola

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

import cv2
import numpy as np

large = cv2.imread('1.jpg')
rgb = cv2.pyrDown(large)
small = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
grad = cv2.morphologyEx(small, cv2.MORPH_GRADIENT, kernel)

_, bw = cv2.threshold(grad, 0.0, 255.0, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 1))
connected = cv2.morphologyEx(bw, cv2.MORPH_CLOSE, kernel)
# using RETR_EXTERNAL instead of RETR_CCOMP
contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
#For opencv 3+ comment the previous line and uncomment the following line
#_, contours, hierarchy = cv2.findContours(connected.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

mask = np.zeros(bw.shape, dtype=np.uint8)

for idx in range(len(contours)):
    x, y, w, h = cv2.boundingRect(contours[idx])
    mask[y:y+h, x:x+w] = 0
    cv2.drawContours(mask, contours, idx, (255, 255, 255), -1)
    r = float(cv2.countNonZero(mask[y:y+h, x:x+w])) / (w * h)

    if r > 0.45 and w > 8 and h > 8:
        cv2.rectangle(rgb, (x, y), (x+w-1, y+h-1), (0, 255, 0), 2)

cv2.imshow('rects', rgb)

enter image description here enter image description here enter image description here

What does .class mean in Java?

When you write .class after a class name, it references the class literal - java.lang.Class object that represents information about given class.

For example, if your class is Print, then Print.class is an object that represents the class Print on runtime. It is the same object that is returned by the getClass() method of any (direct) instance of Print.

Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());

How to store a command in a variable in a shell script?

First of all there are functions for this. But if you prefer vars then your task can be done like this:

$ cmd=ls

$ $cmd # works
file  file2  test

$ cmd='ls | grep file'

$ $cmd # not works
ls: cannot access '|': No such file or directory
ls: cannot access 'grep': No such file or directory
 file

$ bash -c $cmd # works
file  file2  test

$ bash -c "$cmd" # also works
file
file2

$ bash <<< $cmd
file
file2

$ bash <<< "$cmd"
file
file2

Or via tmp file

$ tmp=$(mktemp)
$ echo "$cmd" > "$tmp"
$ chmod +x "$tmp"
$ "$tmp"
file
file2

$ rm "$tmp"

How to check the Angular version?

I think the answer given by D. Squire was accurate, but possibly only a tad vague. If you change directories to a project and then type ng --version, it will display the angular version in the project. If done from a default directory (not within a project), you will only get the Angular CLI version, which is probably not what you are looking for and will give the output shown by Vik2696.

$ cd my-project
$ ng --version   // done within project directory

Angular CLI: 1.6.8
Node: 8.9.4
OS: win32 x64
Angular: 5.2.5
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

@angular/cli: 1.6.8
@angular-devkit/build-optimizer: 0.0.42
@angular-devkit/core: 0.0.29
@angular-devkit/schematics: 0.0.52
@ngtools/json-schema: 1.1.0
@ngtools/webpack: 1.9.8
@schematics/angular: 0.1.17
typescript: 2.5.3
webpack: 3.10.0

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

I was having similar issues connecting to OpenSUSE 13.1 MySQL database with LibreOffice. Update LibreOffice to latest stable "Still" package, then make sure the database is accessible using a tool such as phpMyAdmin. Make sure your user is linked to localhost and not "%" (any). This worked for me, I am able to add data thru LibreOffice.

Side note - LibreOffice Base will not supply "native connection" via MySQL on first attempt, you will need to use the back button, then try again to see the options.

Hope this helps.

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

Can a main() method of class be invoked from another class in java

If you want to call the main method of another class you can do it this way assuming I understand the question.

public class MyClass {

    public static void main(String[] args) {

        System.out.println("main() method of MyClass");
        OtherClass obj = new OtherClass();
    }
}

class OtherClass {

    public OtherClass() {

        // Call the main() method of MyClass
        String[] arguments = new String[] {"123"};
        MyClass.main(arguments);
    }
}

How to pass data from Javascript to PHP and vice versa?

Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.

An example (using traditional event registration model for simplicity):

<!-- headers etc. omitted -->
<script>
function callPHP(params) {
    var httpc = new XMLHttpRequest(); // simplified for clarity
    var url = "get_data.php";
    httpc.open("POST", url, true); // sending as POST

    httpc.onreadystatechange = function() { //Call a function when the state changes.
        if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
            alert(httpc.responseText); // some processing here, or whatever you want to do with the response
        }
    };
    httpc.send(params);
}
</script>
<a href="#" onclick="callPHP('lorem=ipsum&foo=bar')">call PHP script</a>
<!-- rest of document omitted -->

Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)

See also Mozilla's documentation for further examples

Where to find free public Web Services?

Here you can find some public REST services for encryption and security related things: http://security.jelastic.servint.net

Firestore Getting documents id from collection

Since you are using angularFire, it doesn't make any sense if you are going back to default firebase methods for your implementation. AngularFire itself has the proper mechanisms implemented. Just have to use it.

valueChanges() method of angularFire provides an overload for getting the ID of each document of the collection by simply adding a object as a parameter to the method.

valueChanges({ idField: 'id' })

Here 'idField' must be same as it is. 'id' can be anything that you want your document IDs to be called.

Then the each document object on the returned array will look like this.

{
  field1 = <field1 value>,
  field2 = <field2 value>,
  ..
  id = 'whatEverTheDocumentIdWas'
}

Then you can easily get the document ID by referencing to the field that you named.

AngularFire 5.2.0

Php - Your PHP installation appears to be missing the MySQL extension which is required by WordPress

After nearly seven years this keeps getting different answers.† Many are similar--but none identical--to what worked for me. Here's what worked for me (Ubuntu server).

Moving a site to a new server, forgot to install the PHP MySQL module/extension. I ran a quick

apt-get install php-mysql

and then

apachectl restart

Bada bing. No php5, php7; just plain php-mysql.

Software Design vs. Software Architecture

In My opinion , Architecture is nothing but a vision ,gathering requirements and framing the building blocks in right way

where as design , to construct particular block there are 100 solutions may be available, but to meet exact requirement we need to choose the right method , so choosing right method or algorithm is nothing but design

Showing percentages above bars on Excel column graph

You can do this with a pivot table and add a line with the pourcentage for each category like brettdj showed in his answer. But if you want to keep your data as it is, there is a solution by using some javascript.

Javascript is a powerful language offering a lot of useful data visualization libraries like plotly.js.

Here is a working code I have written for you:

https://www.funfun.io/1/#/edit/5a58c6368dfd67466879ed27

In this example, I use a Json file to get the data from the embedded spreadsheet, so I can use it in my javascript code and create a bar chart.

I calculate the percentage by adding the values of all the category present in the table and using this formula (you can see it in the script.js file): Percentage (%) = 100 x partial value / total value

It automatically calculates the total and pourcentage even if you add more categories.

I used plotly.js to create my chart, it has a good documentation and lots of examples for beginners, this code gets all the option you want to use:

var trace1 = {
    x: xValue, 
    y: data,
    type: 'bar',
    text: yValue,
    textposition: 'auto',
    hoverinfo: 'none',
    marker: {
    color: 'yellow',
    opacity: 0.6,
    line: {
      color: 'yellow',
      width: 1.5
    }
  }
};

It is rather self explanatory, the text is where you put the percentage.

Once you've made your chart you can load it in excel by passing the URL in the Funfun add-in. Here is how it looks like with my example:

final

I know it is an old post but I hope it helps people with the same problem !

Disclosure : I’m a developer of funfun

In what cases do I use malloc and/or new?

Use malloc and free only for allocating memory that is going to be managed by c-centric libraries and APIs. Use new and delete (and the [] variants) for everything that you control.

What is the default access modifier in Java?

Default access modifier is package-private - visible only from the same package

Passing array in GET for a REST call

Collections are a resource so /appointments is fine as the resource.

Collections also typically offer filters via the querystring which is essentially what users=id1,id2... is.

So,

/appointments?users=id1,id2 

is fine as a filtered RESTful resource.

How do I rotate a picture in WinForms

You can easily do it by calling this method :

public static Bitmap RotateImage(Image image, float angle)
{
    if (image == null)
        throw new ArgumentNullException("image");

    PointF offset = new PointF((float)image.Width / 2, (float)image.Height / 2);

    //create a new empty bitmap to hold rotated image
    Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
    rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    //make a graphics object from the empty bitmap
    Graphics g = Graphics.FromImage(rotatedBmp);

    //Put the rotation point in the center of the image
    g.TranslateTransform(offset.X, offset.Y);

    //rotate the image
    g.RotateTransform(angle);

    //move the image back
    g.TranslateTransform(-offset.X, -offset.Y);

    //draw passed in image onto graphics object
    g.DrawImage(image, new PointF(0, 0));

    return rotatedBmp;
}

don't forget to add a reference to System.Drawing.dll on your project

Example of this method call :

Image image = new Bitmap("waves.png");
Image newImage = RotateImage(image, 360);
newImage.Save("newWaves.png");

Operator overloading ==, !=, Equals

public class BOX
{
    double height, length, breadth;

    public static bool operator == (BOX b1, BOX b2)
    {
        if (b1 is null)
            return b2 is null;

        return b1.Equals(b2);
    }

    public static bool operator != (BOX b1, BOX b2)
    {
        return !(b1 == b2);
    }

    public override bool Equals(object obj)
    {
        if (obj == null)
            return false;

        return obj is BOX b2? (length == b2.length && 
                               breadth == b2.breadth && 
                               height == b2.height): false;

    }

    public override int GetHashCode()
    {
        return (height,length,breadth).GetHashCode();
    }
}

Add a new column to existing table in a migration

Although a migration file is best practice as others have mentioned, in a pinch you can also add a column with tinker.

$ php artisan tinker

Here's an example one-liner for the terminal:

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ $table->integer('paid'); })



(Here it is formatted for readability)

Schema::table('users', function(\Illuminate\Database\Schema\Blueprint $table){ 
    $table->integer('paid'); 
});

How to create a new text file using Python

    file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
    any_string = "Hello\nWorld"
    file.write(any_string)
    file.close()

How to unset a JavaScript variable?

ECMAScript 2015 offers Reflect API. It is possible to delete object property with Reflect.deleteProperty():

Reflect.deleteProperty(myObject, 'myProp');
// it is equivalent to:
delete myObject.myProp;
delete myObject['myProp'];

To delete property of global window object:

Reflect.deleteProperty(window, 'some_var');

In some cases properties cannot be deleted (when the property is not configurable) and then this function returns false (as well as delete operator). In other cases returns true:

Object.defineProperty(window, 'some_var', {
    configurable: false,
    writable: true,
    enumerable: true,
    value: 'some_val'
});

var frozen = Object.freeze({ myProperty: 'myValue' });
var regular = { myProperty: 'myValue' };
var blank = {};

console.log(Reflect.deleteProperty(window, 'some_var')); // false
console.log(window.some_var); // some_var

console.log(Reflect.deleteProperty(frozen, 'myProperty')); // false
console.log(frozen.myProperty); // myValue

console.log(Reflect.deleteProperty(regular, 'myProperty')); // true
console.log(regular.myProperty); // undefined

console.log(Reflect.deleteProperty(blank, 'notExistingProperty')); // true
console.log(blank.notExistingProperty); // undefined

There is a difference between deleteProperty function and delete operator when run in strict mode:

'use strict'

var frozen = Object.freeze({ myProperty: 'myValue' });

Reflect.deleteProperty(frozen, 'myProperty'); // false
delete frozen.myProperty;
// TypeError: property "myProperty" is non-configurable and can't be deleted

How do I update the element at a certain position in an ArrayList?

 arrList.set(5,newValue);

and if u want to update it then add this line also

 youradapater.NotifyDataSetChanged();

git rebase fatal: Needed a single revision

The issue is that you branched off a branch off of.... where you are trying to rebase to. You can't rebase to a branch that does not contain the commit your current branch was originally created on.

I got this when I first rebased a local branch X to a pushed one Y, then tried to rebase a branch (first created on X) to the pushed one Y.

Solved for me by rebasing to X.

I have no problem rebasing to remote branches (potentially not even checked out), provided my current branch stems from an ancestor of that branch.

How should the ViewModel close the form?

Another solution is to create property with INotifyPropertyChanged in View Model like DialogResult, and then in Code Behind write this:

public class SomeWindow: ChildWindow
{
    private SomeViewModel _someViewModel;

    public SomeWindow()
    {
        InitializeComponent();

        this.Loaded += SomeWindow_Loaded;
        this.Closed += SomeWindow_Closed;
    }

    void SomeWindow_Loaded(object sender, RoutedEventArgs e)
    {
        _someViewModel = this.DataContext as SomeViewModel;
        _someViewModel.PropertyChanged += _someViewModel_PropertyChanged;
    }

    void SomeWindow_Closed(object sender, System.EventArgs e)
    {
        _someViewModel.PropertyChanged -= _someViewModel_PropertyChanged;
        this.Loaded -= SomeWindow_Loaded;
        this.Closed -= SomeWindow_Closed;
    }

    void _someViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        if (e.PropertyName == SomeViewModel.DialogResultPropertyName)
        {
            this.DialogResult = _someViewModel.DialogResult;
        }
    }
}

The most important fragment is _someViewModel_PropertyChanged. DialogResultPropertyName can be some public const string in SomeViewModel.

I use this kind of trick to make some changes in View Controls in case when this is hard to do in ViewModel. OnPropertyChanged in ViewModel you can do anything you want in View. ViewModel is still 'unit testable' and some small lines of code in code behind makes no difference.

Opening popup windows in HTML

HTML alone does not support this. You need to use some JS.

And also consider nowadays people use popup blocker in browsers.

<a href="javascript:window.open('document.aspx','mypopuptitle','width=600,height=400')">open popup</a>

How to extract code of .apk file which is not working?

Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.


Prerequsites

You will need:

  • A working Java installation
  • A working terminal/command prompt
  • A computer
  • An APK file

Steps

Step 1: Changing the file extension of the APK file

  1. Change the file extension of the .apk file by either adding a .zip extension to the filename, or to change .apk to .zip.

    For example, com.example.apk becomes com.example.zip, or com.example.apk.zip. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:

macOS add extension confirm dialog

Step 2: Extracting Java files from APK

  1. Extract the renamed APK file in a specific folder. For example, let that folder be demofolder.

    • If it didn't work, try opening the file in another application such as WinZip or 7-Zip.

    • For macOS, you can try running unzip in Terminal (available at /Applications/Terminal.app), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip for documentation and arguments.

  2. Download dex2jar (see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.

  3. Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex and press enter. This will generate classes-dex2jar.jar file in the same folder.

    • macOS/Linux users: Replace d2j-dex2jar.bat with d2j-dex2jar.sh. In other words, run d2j-jar2dex.sh classes.dex in the terminal and press enter.
  4. Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.

  5. From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar file into it, or go to File > Open File... and browse for the jar.

  6. Next, in the menu, go to File > Save All Sources (Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)

  7. Extract that zip file (classes-dex2jar.jar.src.zip) and you should get all java files of the application.

Step 3: Getting xml files from APK

  • For more info, see the apktool website for installation instructions and more
  • Windows:

    1. Download the wrapper script (optional) and the apktool jar (required) and place it in the same folder (for example, myxmlfolder).
    2. Change your current directory to the myxmlfolder folder and rename the apktool jar file to apktool.jar.
    3. Place the .apk file in the same folder (i.e myxmlfolder).
    4. Open the command prompt (or terminal) and change your current directory to the folder where apktool is stored (in this case, myxmlfolder). Next, type the command apktool if framework-res.apk.

      What we're doing here is that we are installing a framework. For more info, see the docs.

    5. The above command should result in "Framework installed ..."
    6. In the command prompt, type the command apktool d filename.apk (where filename is the name of apk file). This should decode the file. For more info, see the docs.

      This should result in a folder filename.out being outputted, where filename is the original name of the apk file without the .apk file extension. In this folder are all the XML files such as layout, drawables etc.

Source: How to get source code from APK file - Comptech Blogspot

How to clear the canvas for redrawing

This is 2018 and still there is no native method to completely clear canvas for redrawing. clearRect() does not clear the canvas completely. Non-fill type drawings are not cleared out (eg. rect())

1.To completely clear canvas irrespective of how you draw:

context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.beginPath();

Pros: Preserves strokeStyle, fillStyle etc.; No lag;

Cons: Unnecessary if you are already using beginPath before drawing anything

2.Using the width/height hack:

context.canvas.width = context.canvas.width;

OR

context.canvas.height = context.canvas.height;

Pros: Works with IE Cons: Resets strokeStyle, fillStyle to black; Laggy;

I was wondering why a native solution does not exist. Actually, clearRect() is considered as the single line solution because most users do beginPath() before drawing any new path. Though beginPath is only to be used while drawing lines and not closed path like rect().

This is the reason why the accepted answer did not solve my problem and I ended up wasting hours trying different hacks. Curse you mozilla

ActiveMQ connection refused

Your application is not able to connect to activemq. Check that your activemq is running and listening on localhost 61616.

You can try using: netstat -a to check if the activemq process has started. Or try check if you can access your actvemq using admin page: localhost:8161/admin/queues.jsp

On mac you will start your activemq using:

$ACTMQ_HOME/bin/activemq start 

Or if your config file (activemq.xml ) if located in another location you can use:

$ACTMQ_HOME/bin/activemq start xbean:file:${location_of_your_config_file}

In your case the executable is under: bin/macosx/activemq so you need to use: $ACTMQ_HOME/bin/macosx/activemq start

Environ Function code samples for VBA

Some time when we use Environ() function we may get the Library or property not found error. Use VBA.Environ() or VBA.Environ$() to avoid the error.

RecyclerView - Get view at particular position

You can get a view for a particular position on a recyclerview using the following

int position = 2;
RecyclerView.ViewHolder viewHolder = recyclerview.findViewHolderForItemId(position);
View view = viewHolder.itemView;
ImageView imageView = (ImageView)view.findViewById(R.id.imageView);

How can I take a screenshot/image of a website using Python?

import subprocess

def screenshots(url, name):
    subprocess.run('webkit2png -F -o {} {} -D ./screens'.format(name, url), 
      shell=True)

Sorting an ArrayList of objects using a custom sorting order

In addition to what was already posted you should know that since Java 8 we can shorten our code and write it like:

Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));

or since List now have sort method

yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));

Explanation:

Since Java 8, functional interfaces (interfaces with only one abstract method - they can have more default or static methods) can be easily implemented using:

Since Comparator<T> has only one abstract method int compare(T o1, T o2) it is functional interface.

So instead of (example from @BalusC answer)

Collections.sort(contacts, new Comparator<Contact>() {
    public int compare(Contact one, Contact other) {
        return one.getAddress().compareTo(other.getAddress());
    }
}); 

we can reduce this code to:

Collections.sort(contacts, (Contact one, Contact other) -> {
     return one.getAddress().compareTo(other.getAddress());
});

We can simplify this (or any) lambda by skipping

  • argument types (Java will infer them based on method signature)
  • or {return ... }

So instead of

(Contact one, Contact other) -> {
     return one.getAddress().compareTo(other.getAddress();
}

we can write

(one, other) -> one.getAddress().compareTo(other.getAddress())

Also now Comparator has static methods like comparing(FunctionToComparableValue) or comparing(FunctionToValue, ValueComparator) which we could use to easily create Comparators which should compare some specific values from objects.

In other words we can rewrite above code as

Collections.sort(contacts, Comparator.comparing(Contact::getAddress)); 
//assuming that Address implements Comparable (provides default order).

List<Map<String, String>> vs List<? extends Map<String, String>>

As you mentioned, there could be two below versions of defining a List:

  1. List<? extends Map<String, String>>
  2. List<?>

2 is very open. It can hold any object type. This may not be useful in case you want to have a map of a given type. In case someone accidentally puts a different type of map, for example, Map<String, int>. Your consumer method might break.

In order to ensure that List can hold objects of a given type, Java generics introduced ? extends. So in #1, the List can hold any object which is derived from Map<String, String> type. Adding any other type of data would throw an exception.

How to create local notifications?

iOS 8 users and above, please include this in App delegate to make it work.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
    {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }

    return YES;
}

And then adding this lines of code would help,

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    notification.repeatInterval = NSDayCalendarUnit;
    [notification setAlertBody:@"Hello world"];
    [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
    [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];

}

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

#pragma pack effect

I have seen people use it to make sure that a structure takes a whole cache line to prevent false sharing in a multithreaded context. If you are going to have a large number of objects that are going to be loosely packed by default it could save memory and improve cache performance to pack them tighter, though unaligned memory access will usually slow things down so there might be a downside.

What does %~dp0 mean, and how does it work?

Great example from Strawberry Perl's portable shell launcher:

set drive=%~dp0
set drivep=%drive%
if #%drive:~-1%# == #\# set drivep=%drive:~0,-1%

set PATH=%drivep%\perl\site\bin;%drivep%\perl\bin;%drivep%\c\bin;%PATH%

not sure what the negative 1's doing there myself, but it works a treat!

Generic type conversion FROM string

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

Convert array of strings into a string in Java

I like using Google's Guava Joiner for this, e.g.:

Joiner.on(", ").skipNulls().join("Harry", null, "Ron", "Hermione");

would produce the same String as:

new String("Harry, Ron, Hermione");

ETA: Java 8 has similar support now:

String.join(", ", "Harry", "Ron", "Hermione");

Can't see support for skipping null values, but that's easily worked around.

How do you do dynamic / dependent drop downs in Google Sheets?

Here you have another solution based on the one provided by @tarheel

function onEdit() {
    var sheetWithNestedSelectsName = "Sitemap";
    var columnWithNestedSelectsRoot = 1;
    var sheetWithOptionPossibleValuesSuffix = "TabSections";

    var activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var activeSheet = SpreadsheetApp.getActiveSheet();

    // If we're not in the sheet with nested selects, exit!
    if ( activeSheet.getName() != sheetWithNestedSelectsName ) {
        return;
    }

    var activeCell = SpreadsheetApp.getActiveRange();

    // If we're not in the root column or a content row, exit!
    if ( activeCell.getColumn() != columnWithNestedSelectsRoot || activeCell.getRow() < 2 ) {
        return;
    }

    var sheetWithActiveOptionPossibleValues = activeSpreadsheet.getSheetByName( activeCell.getValue() + sheetWithOptionPossibleValuesSuffix );

    // Get all possible values
    var activeOptionPossibleValues = sheetWithActiveOptionPossibleValues.getSheetValues( 1, 1, -1, 1 );

    var possibleValuesValidation = SpreadsheetApp.newDataValidation();
    possibleValuesValidation.setAllowInvalid( false );
    possibleValuesValidation.requireValueInList( activeOptionPossibleValues, true );

    activeSheet.getRange( activeCell.getRow(), activeCell.getColumn() + 1 ).setDataValidation( possibleValuesValidation.build() );
}

It has some benefits over the other approach:

  • You don't need to edit the script every time you add a "root option". You only have to create a new sheet with the nested options of this root option.
  • I've refactored the script providing more semantic names for the variables and so on. Furthermore, I've extracted some parameters to variables in order to make it easier to adapt to your specific case. You only have to set the first 3 values.
  • There's no limit of nested option values (I've used the getSheetValues method with the -1 value).

So, how to use it:

  1. Create the sheet where you'll have the nested selectors
  2. Go to the "Tools" > "Script Editor…" and select the "Blank project" option
  3. Paste the code attached to this answer
  4. Modify the first 3 variables of the script setting up your values and save it
  5. Create one sheet within this same document for each possible value of the "root selector". They must be named as the value + the specified suffix.

Enjoy!

Create a zip file and download it

$zip = new ZipArchive;
$tmp_file = 'assets/myzip.zip';
    if ($zip->open($tmp_file,  ZipArchive::CREATE)) {
        $zip->addFile('folder/bootstrap.js', 'bootstrap.js');
        $zip->addFile('folder/bootstrap.min.js', 'bootstrap.min.js');
        $zip->close();
        echo 'Archive created!';
        header('Content-disposition: attachment; filename=files.zip');
        header('Content-type: application/zip');
        readfile($tmp_file);
   } else {
       echo 'Failed!';
   }

How do I autoindent in Netbeans?

To format all the code in NetBeans, press Alt + Shift + F. If you want to indent lines, select the lines and press Alt + Shift + right arrow key, and to unindent, press Alt + Shift + left arrow key.

Add a link to an image in a css style sheet

You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.

Based only on your style you would have:

<a href="home.com" id="logo"></a>

Get HTML source of WebElement in Selenium WebDriver using Python

Using the attribute method is, in fact, easier and more straightforward.

Using Ruby with the Selenium and PageObject gems, to get the class associated with a certain element, the line would be element.attribute(Class).

The same concept applies if you wanted to get other attributes tied to the element. For example, if I wanted the string of an element, element.attribute(String).

How to use the TextWatcher class in Android?

Supplemental answer

Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.

  • Red: text about to be deleted (replaced)
  • Green: text that was just added (replacing the old red text)

enter image description here

Adding Jar files to IntellijIdea classpath

On the Mac version I was getting the error when trying to run JSON-Clojure.json.clj, which is the script to export a database table to JSON. To get it to work I had to download the latest Clojure JAR from http://clojure.org/ and then right-click on PHPStorm app in the Finder and "Show Package Contents". Then go to Contents in there. Then open the lib folder, and see a bunch of .jar files. Copy the clojure-1.8.0.jar file from the unzipped archive I downloaded from clojure.org into the aforementioned lib folder inside the PHPStorm.app/Contents/lib. Restart the app. Now it freaking works.

EDIT: You also have to put the JSR-223 script engine into PHPStorm.app/Contents/lib. It can be built from https://github.com/ato/clojure-jsr223 or downloaded from https://www.dropbox.com/s/jg7s0c41t5ceu7o/clojure-jsr223-1.5.1.jar?dl=0 .

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

For me I do this to find,

let url = URL(string: urlString)
URLSession.shared.dataTask(with: url!) { (data, response, error) in ...}

Can't use

"let url = NSURL(string: urlString)

How to write string literals in python without having to escape them?

(Assuming you are not required to input the string from directly within Python code)

to get around the Issue Andrew Dalke pointed out, simply type the literal string into a text file and then use this;

input_ = '/directory_of_text_file/your_text_file.txt' 
input_open   = open(input_,'r+')
input_string = input_open.read()

print input_string

This will print the literal text of whatever is in the text file, even if it is;

 '   ''' """  “ \

Not fun or optimal, but can be useful, especially if you have 3 pages of code that would’ve needed character escaping.

How to read a text file from server using JavaScript?

You need to use Ajax, which is basically sending a request to the server, then getting a JSON object, which you convert to a JavaScript object.

Check this:

http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first

If you are using jQuery library, it can be even easier:

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

Having said this, I highly recommend you don't download a file of 3.5MB into JS! It is not a good idea. Do the processing on your server, then return the data after processing. Then if you want to get a new data, send a new Ajax request, process the request on server, then return the new data.

Hope that helps.

How to rename JSON key

JSON.parse has two parameters. The second parameter, reviver, is a transform function that can be formatted output format we want. See ECMA specification here.

In reviver function:

  • if we return undefined, the original property will be deleted.
  • this is the object containing the property being processed as this function, and the property name as a string, the property value as arguments of this function.
const json = '[{"_id":"5078c3a803ff4197dc81fbfb","email":"[email protected]","image":"some_image_url","name":"Name 1"},{"_id":"5078c3a803ff4197dc81fbfc","email":"[email protected]","image":"some_image_url","name":"Name 2"}]';

const obj = JSON.parse(json, function(k, v) {
    if (k === "_id") {
        this.id = v;
        return; # if return  undefined, orignal property will be removed
    }
    return v;
});

const res = JSON.stringify(obj);
console.log(res)

output:

[{"email":"[email protected]","image":"some_image_url","name":"Name 1","id":"5078c3a803ff4197dc81fbfb"},{"email":"[email protected]","image":"some_image_url","name":"Name 2","id":"5078c3a803ff4197dc81fbfc"}]

MVC4 DataType.Date EditorFor won't display date value in Chrome, fine in Internet Explorer

If you remove [DataType(DataType.Date)] from your model, the input field in Chrome is rendered as type="datetime" and won't show the datepicker either.

Append text with .bat

Any line starting with a "REM" is treated as a comment, nothing is executed including the redirection.

Also, the %date% variable may contain "/" characters which are treated as path separator characters, leading to the system being unable to create the desired log file.

Find rows that have the same value on a column in MySQL

This works best

Screenshot enter image description here

SELECT RollId, count(*) AS c 
    FROM `tblstudents` 
    GROUP BY RollId 
    HAVING c > 1 
    ORDER BY c DESC

Count words in a string method?

Taking the chosen answer as a starting point the following deals with a few English language issues including hyphenated words, apostrophes for possessives and shortenings, numbers and also any characters outside of UTF-16:

public static int countWords(final String s) {
    int wordCount = 0;
    boolean word = false;
    final int endOfLine = s.length() - 1;

    for (int i = 0; i < s.length(); i++) {
        // if the char is a letter, word = true.
        if (isWordCharacter(s, i) && i != endOfLine) {
            word = true;
            // if char isn't a letter and there have been letters before,
            // counter goes up.
        } else if (!isWordCharacter(s, i) && word) {
            wordCount++;
            word = false;
            // last word of String; if it doesn't end with a non letter, it
            // wouldn't count without this.
        } else if (isWordCharacter(s, i) && i == endOfLine) {
            wordCount++;
        }
    }
    return wordCount;
}

private static boolean isWordCharacter(final String s, final int i) {
    final char ch = s.charAt(i);
    return Character.isLetterOrDigit(ch)
            || ch == '\''
            || Character.getType(ch) == Character.DASH_PUNCTUATION
            || Character.isSurrogate(ch);
}

Setting the default active profile in Spring-boot

First of all, with the solution below, is necessary to understand that always the spring boot will read the application.properties file. So the other's profile files only will complement and replace the properties defined before.

Considering the follow files:

application.properties
application-qa.properties
application-prod.properties

1) Very important. The application.properties, and just this file, must have the follow line:

[email protected]@

2) Change what you want in the QA and PROD configuration files to see the difference between the environments.

3) By command line, start the spring boot app with any of this options:

It will start the app with the default application.properties file:

mvn spring-boot:run

It will load the default application.properties file and after the application-qa.properties file, replacing and/or complementing the default configuration:

mvn spring-boot:run -Dspring.profiles.active=qa

The same here but with the production environment instead of QA:

mvn spring-boot:run -Dspring.profiles.active=prod

Best lightweight web server (only static content) for Windows

Have a look at mongoose:

  • single executable
  • very small memory footprint
  • allows multiple worker threads
  • easy to install as service
  • configurable with a configuration file if required

How does one target IE7 and IE8 with valid CSS?

Well you don't really have to worry about IE7 code not working in IE8 because IE8 has compatibility mode (it can render pages the same as IE7). But if you still want to target different versions of IE, a way that's been done for a while now is to either use conditional comments or begin your css rule with a * to target IE7 and below. Or you could pay attention to user agent on the servers and dish up a different CSS file based on that information.

WindowsError: [Error 126] The specified module could not be found

There is a promising answer at Problem updating bokeh: [WinError 126] The specified module could not be found.

It hints at https://github.com/conda/conda/issues/9313.

There, you find:

It's a library load issue. More details at github.com/conda/conda/issues/8836 You probably have a broken conda right now. You can use a standalone conda from repo.anaconda.com/pkgs/misc/conda-execs to repair it: standalone-conda.exe update -p C:\ProgramData\Anaconda3 conda-package-handling You should get version 1.6.0, and the problems should go away.

Thus, it might simply be a conda issue. Reinstalling standalone conda might repair the error. Please comment whoever can confirm this.

jackson deserialization json to java-objects

You have to change the line

product userFromJSON = mapper.readValue(userDataJSON, product.class);

to

product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);

since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.

Edit: You can also go with Steven Schlansker's suggestion and use

List<product> userFromJSON =
        mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});

instead if you want to avoid arrays.

Double value to round up in Java

Note the comma in your string: "1,07". DecimalFormat uses a locale-specific separator string, while Double.parseDouble() does not. As you happen to live in a country where the decimal separator is ",", you can't parse your number back.

However, you can use the same DecimalFormat to parse it back:

DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

But you really should do this instead:

double finalValue = Math.round( value * 100.0 ) / 100.0;

Note: As has been pointed out, you should only use floating point if you don't need a precise control over accuracy. (Financial calculations being the main example of when not to use them.)

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

enter image description here

I solved this error like this... The craziness of android. I had the package name as Adapter and the I refactor the name to adapter with an "a" instead of "A" and solved the error.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

Eclipse gives “Java was started but returned exit code 13”

enter image description hereI got this fixed by doing the below steps,

  1. The eclipse finds the JAVA executables from 'C:\ProgramData\Oracle\Java\javapath'

    2.The folder structure will contain shortcuts to the below executables, i. java.exe
    ii. javaw.exe
    iii. javaws.exe 3.For me the executable paths were pointing to my (ProgramFiles(x84)) folder location

  2. I corrected it to Program Files path(64 bit) and the issue got resolved

Please find the screenshot for the same.

How to insert default values in SQL table?

Just don't include the columns that you want to use the default value for in your insert statement. For instance:

INSERT INTO table1 (field1, field3) VALUES (5, 10);

...will take the default values for field2 and field4, and assign 5 to field1 and 10 to field3.

How to redirect page after click on Ok button on sweet alert?

To specify a callback function, you have to use an object as the first argument, and the callback function as the second argument.

echo '<script>
    setTimeout(function() {
        swal({
            title: "Wow!",
            text: "Message!",
            type: "success"
        }, function() {
            window.location = "redirectURL";
        });
    }, 1000);
</script>';

Should a RESTful 'PUT' operation return something

Ideally it would return a success/fail response.

How to get the mobile number of current sim card in real device?

Well, all could be temporary hacks, but there is no way to get mobile number of a user. It is against ethical policy.

For eg, one of the answers above suggests getting all accounts and extracting from there. And it doesn't work anymore! All of these are hacks only.

Only way to get user's mobile number is going through operator. If you have a tie-up with mobile operators like Aitel, Vodafone, etc, you can get user's mobile number in header of request from mobile handset when connected via mobile network internet.

Not sure if any manufacturer tie ups to get specific permissions can help - not explored this area, but nothing documented atleast.

show icon in actionbar/toolbar with AppCompat-v7 21

In modern Android UIs developers should lean more on a visually distinct color scheme for toolbars than on their application icon. The use of application icon plus title as a standard layout is discouraged on API 21 devices and newer.

If you disagree you can try with:

To create the toolbar in XML:

<android.support.v7.widget.Toolbar  
    android:id="@+id/my_awesome_toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary" />

In your activity:

@Override
public void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_layout);

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
}

Use the setLogo() method to set the icon. Code source.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0) you are less likely to to see a difference between the two approaches.

ImportError: DLL load failed: The specified module could not be found

For Windows 10 x64 and Python:

Open a Visual Studio x64 command prompt, and use dumpbin:

dumpbin /dependents [Python Module DLL or PYD file]

If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.

Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.

Case study 1

  1. I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.

  2. It was giving this error: ImportError: DLL load failed: The specified module could not be found

  3. Opened a Visual Studio x64 command prompt.

  4. Under Windows, a .pyd file is a .dll file in disguise, so we want to run dumpbin on this file.

  5. cd MyLibrary\build\lib.win-amd64-3.7\Debug

  6. dumpbin /dependents MyLibrary.cp37-win_amd64.pyd which prints this:

    Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
    Copyright (C) Microsoft Corporation.  All rights reserved.
    
    
    Dump of file MyLibrary.cp37-win_amd64.pyd
    
    File Type: DLL
    
      Image has the following dependencies:
    
        clang_rt.asan_dbg_dynamic-x86_64.dll
        gtestd.dll
        tbb_debug.dll
        python37.dll
        KERNEL32.dll
        MSVCP140D.dll
        VCOMP140D.DLL
        VCRUNTIME140D.dll
        VCRUNTIME140_1D.dll
        ucrtbased.dll
    
      Summary
    
         1000 .00cfg
        D6000 .data
         7000 .idata
        46000 .pdata
       341000 .rdata
        23000 .reloc
         1000 .rsrc
       856000 .text
    
  7. Searched for clang_rt.asan_dbg_dynamic-x86_64.dll, copied it into the same directory, problem solved.

  8. Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.

Please feel free to add your own case studies here! I've made it a community wiki answer.

How to re-enable right click so that I can inspect HTML elements in Chrome?

This bookmarlet works in Google sites/Youtube as of Aug 2019 (tested in Chrome and Firefox):

javascript: function enableContextMenu(aggressive = false) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll("body"); removeContextMenuOnAll("img"); removeContextMenuOnAll("td"); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); el.addEventListener("dragstart", bringBackDefault, true); el.addEventListener("selectstart", bringBackDefault, true); el.addEventListener("click", bringBackDefault, true); el.addEventListener("mousedown", bringBackDefault, true); el.addEventListener("mouseup", bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener("contextmenu", bringBackDefault, true); el.removeEventListener("dragstart", bringBackDefault, true); el.removeEventListener("selectstart", bringBackDefault, true); el.removeEventListener("click", bringBackDefault, true); el.removeEventListener("mousedown", bringBackDefault, true); el.removeEventListener("mouseup", bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } enableContextMenu();

For peskier sites, set/pass aggressive to true (this will disable most event handlers and hence disable interaction with the page):

javascript: function enableContextMenu(aggressive = true) { void(document.ondragstart=null); void(document.onselectstart=null); void(document.onclick=null); void(document.onmousedown=null); void(document.onmouseup=null); void(document.body.oncontextmenu=null); enableRightClickLight(document); if (aggressive) { enableRightClick(document); removeContextMenuOnAll("body"); removeContextMenuOnAll("img"); removeContextMenuOnAll("td"); } } function removeContextMenuOnAll(tagName) { var elements = document.getElementsByTagName(tagName); for (var i = 0; i < elements.length; i++) { enableRightClick(elements[i]); } } function enableRightClickLight(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); } function enableRightClick(el) { el || (el = document); el.addEventListener("contextmenu", bringBackDefault, true); el.addEventListener("dragstart", bringBackDefault, true); el.addEventListener("selectstart", bringBackDefault, true); el.addEventListener("click", bringBackDefault, true); el.addEventListener("mousedown", bringBackDefault, true); el.addEventListener("mouseup", bringBackDefault, true); } function restoreRightClick(el) { el || (el = document); el.removeEventListener("contextmenu", bringBackDefault, true); el.removeEventListener("dragstart", bringBackDefault, true); el.removeEventListener("selectstart", bringBackDefault, true); el.removeEventListener("click", bringBackDefault, true); el.removeEventListener("mousedown", bringBackDefault, true); el.removeEventListener("mouseup", bringBackDefault, true); } function bringBackDefault(event) { event.returnValue = true; (typeof event.stopPropagation === 'function') && event.stopPropagation(); (typeof event.cancelBubble === 'function') && event.cancelBubble(); } enableContextMenu();

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Try this jobber

String stringy =null;
 byte[] buffer =  new byte[100000];
            for (int i = 0; i < buffer.length; i++) {
            buffer[i] =0;

        }
            stringy =StringUtils.toAsciiString(buffer);

C char array initialization

  1. These are equivalent

    char buf[10] = "";
    char buf[10] = {0};
    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. These are equivalent

    char buf[10] = " ";
    char buf[10] = {' '};
    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. These are equivalent

    char buf[10] = "a";
    char buf[10] = {'a'};
    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

Rerender view on browser resize with React

For this reason better is if you use this data from CSS or JSON file data, and then with this data setting new state with this.state({width: "some value",height:"some value" }); or writing code who use data of width screen data in self work if you wish responsive show images

Run PHP function on html button click

Use an AJAX Request on your PHP file, then display the result on your page, without any reloading.

http://api.jquery.com/load/ This is a simple solution if you don't need any POST data.

How can I check the system version of Android?

use this class

import android.os.Build;

/**
 * Created by MOMANI on 2016/04/14.
 */
public class AndroidVersionUtil {
    public static int getApiVersion() {
        return android.os.Build.VERSION.SDK_INT;
    }

    public static boolean isApiVersionGraterOrEqual(int thisVersion) {
        return android.os.Build.VERSION.SDK_INT >= thisVersion;
    }
}

How to find current transaction level?

just run DBCC useroptions and you'll get something like this:

Set Option                  Value
--------------------------- --------------
textsize                    2147483647
language                    us_english
dateformat                  mdy
datefirst                   7
lock_timeout                -1
quoted_identifier           SET
arithabort                  SET
ansi_null_dflt_on           SET
ansi_warnings               SET
ansi_padding                SET
ansi_nulls                  SET
concat_null_yields_null     SET
isolation level             read committed

Import CSV file with mixed data types

If your input file has a fixed amount of columns separated by commas and you know in which columns are the strings it might be best to use the function

textscan()

Note that you can specify a format where you read up to a maximum number of characters in the string or until a delimiter (comma) is found.

Get the name of an object's type

A little trick I use:

function Square(){
    this.className = "Square";
    this.corners = 4;
}

var MySquare = new Square();
console.log(MySquare.className); // "Square"

Laravel Eloquent compare date from datetime field

Laravel 4+ offers you these methods: whereDay(), whereMonth(), whereYear() (#3946) and whereDate() (#6879).

They do the SQL DATE() work for you, and manage the differences of SQLite.

Your result can be achieved as so:

->whereDate('date', '<=', '2014-07-10')

For more examples, see first message of #3946 and this Laravel Daily article.


Update: Though the above method is convenient, as noted by Arth it is inefficient on large datasets, because the DATE() SQL function has to be applied on each record, thus discarding the possible index.

Here are some ways to make the comparison (but please read notes below):

->where('date', '<=', '2014-07-10 23:59:59')

->where('date', '<', '2014-07-11')

// '2014-07-11'
$dayAfter = (new DateTime('2014-07-10'))->modify('+1 day')->format('Y-m-d');

->where('date', '<', $dayAfter)

Notes:

  • 23:59:59 is okay (for now) because of the 1-second precision, but have a look at this article: 23:59:59 is not the end of the day. No, really!
  • Keep in mind the "zero date" case ("0000-00-00 00:00:00"). Though, these "zero dates" should be avoided, they are source of so many problems. Better make the field nullable if needed.

The tilde operator in Python

Besides being a bitwise complement operator, ~ can also help revert a boolean value, though it is not the conventional bool type here, rather you should use numpy.bool_.


This is explained in,

import numpy as np
assert ~np.True_ == np.False_

Reversing logical value can be useful sometimes, e.g., below ~ operator is used to cleanse your dataset and return you a column without NaN.

from numpy import NaN
import pandas as pd

matrix = pd.DataFrame([1,2,3,4,NaN], columns=['Number'], dtype='float64')
# Remove NaN in column 'Number'
matrix['Number'][~matrix['Number'].isnull()]

How do I fix a .NET windows application crashing at startup with Exception code: 0xE0434352?

So.. I had noticed in event viewer that this crash corresponded to a "System.IO.FileNotFoundException" error.

So I fired ProcMon and noticed that one of the program dlls was failing to load vcruntime140. So I simply installed vs15 redist and it worked.

Not equal string

It should be this:

if (myString!="-1")
{
//Do things
}

Your equals and exclamation are the wrong way round.

What's the difference between SortedList and SortedDictionary?

I cracked open Reflector to have a look at this as there seems to be a bit of confusion about SortedList. It is in fact not a binary search tree, it is a sorted (by key) array of key-value pairs. There is also a TKey[] keys variable which is sorted in sync with the key-value pairs and used to binary search.

Here is some source (targeting .NET 4.5) to backup my claims.

Private members

// Fields
private const int _defaultCapacity = 4;
private int _size;
[NonSerialized]
private object _syncRoot;
private IComparer<TKey> comparer;
private static TKey[] emptyKeys;
private static TValue[] emptyValues;
private KeyList<TKey, TValue> keyList;
private TKey[] keys;
private const int MaxArrayLength = 0x7fefffff;
private ValueList<TKey, TValue> valueList;
private TValue[] values;
private int version;

SortedList.ctor(IDictionary, IComparer)

public SortedList(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) : this((dictionary != null) ? dictionary.Count : 0, comparer)
{
    if (dictionary == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.dictionary);
    }
    dictionary.Keys.CopyTo(this.keys, 0);
    dictionary.Values.CopyTo(this.values, 0);
    Array.Sort<TKey, TValue>(this.keys, this.values, comparer);
    this._size = dictionary.Count;
}

SortedList.Add(TKey, TValue) : void

public void Add(TKey key, TValue value)
{
    if (key == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key);
    }
    int num = Array.BinarySearch<TKey>(this.keys, 0, this._size, key, this.comparer);
    if (num >= 0)
    {
        ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate);
    }
    this.Insert(~num, key, value);
}

SortedList.RemoveAt(int) : void

public void RemoveAt(int index)
{
    if ((index < 0) || (index >= this._size))
    {
        ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index);
    }
    this._size--;
    if (index < this._size)
    {
        Array.Copy(this.keys, index + 1, this.keys, index, this._size - index);
        Array.Copy(this.values, index + 1, this.values, index, this._size - index);
    }
    this.keys[this._size] = default(TKey);
    this.values[this._size] = default(TValue);
    this.version++;
}

How can I get the ID of an element using jQuery?

$('tagname').attr('id');

Using above code you can get id.

Dynamically add child components in React

Sharing my solution here, based on Chris' answer. Hope it can help others.

I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:

export class Settings extends React.PureComponent {
  render() {
    const loading = (<div>I'm Loading</div>);
    let content = [];
    let pushMessages = null;
    let emailMessages = null;

    if (this.props.pushPreferences) {
       pushMessages = (<div>Push Content Here</div>);
    }
    if (this.props.emailPreferences) {
      emailMessages = (<div>Email Content Here</div>);
    }

    // Push the components in the order I want
    if (emailMessages) content.push(emailMessages);
    if (pushMessages) content.push(pushMessages);

    return (
      <div>
        {content.length ? content : loading}
      </div>
    )
}

Now, I do realize I could also just put {pushMessages} and {emailMessages} directly in my return() below, but assuming I had even more conditional content, my return() would just look cluttered.

What is the reason for a red exclamation mark next to my project in Eclipse?

It means the jar files are missing from the path that you have given while configuring Build Path/adding jars to the project.

Just once again configure the jars.

Difference between "git add -A" and "git add ."

Both git add . and git add -A will stage all new, modified and deleted files in the newer versions of Git.

The difference is that git add -A stages files in "higher, current and subdirectories" that belong to your working Git repository. But doing a git add . only stages files in the current directory and subdirectories following it (not the files lying outside, i.e., higher directories).

Here's an example:

/my-repo
  .git/
  subfolder/
    nested-file.txt
  rootfile.txt

If your current working directory is /my-repo, and you do rm rootfile.txt, then cd subfolder, followed by git add ., then it will not stage the deleted file. But doing git add -A will certainly stage this change no matter where you perform the command from.

The imported project "C:\Microsoft.CSharp.targets" was not found

This error can also occur when opening a Silverlight project that was built in SL 4, while you have SL 5 installed.

Here is an example error message: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\Silverlight\v4.0\Microsoft.Silverlight.CSharp.targets" was not found.

Note the v4.0.

To resolve, edit the project and find:

<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>

And change it to v5.0.

Then reload project and it will open (unless you do not have SL 5 installed).

Sorting string array in C#

Actually I don't see any nulls:

given:

static void Main()
        {
            string[] testArray = new string[]
            {
                "aa",
                "ab",
                "ac",
                "ad",
                "ab",
                "af"
            };

            Array.Sort(testArray, StringComparer.InvariantCulture);

            Array.ForEach(testArray, x => Console.WriteLine(x));
        }

I obtained:

enter image description here

mysql_config not found when installing mysqldb python interface

You need to install the python-dev package:

sudo apt-get install python-dev

How to bind a List to a ComboBox?

Try something like this:

yourControl.DataSource = countryInstance.Cities;

And if you are using WebForms you will need to add this line:

yourControl.DataBind();

Check if two unordered lists are equal

If elements are always nearly sorted as in your example then builtin .sort() (timsort) should be fast:

>>> a = [1,1,2]
>>> b = [1,2,2]
>>> a.sort()
>>> b.sort()
>>> a == b
False

If you don't want to sort inplace you could use sorted().

In practice it might always be faster then collections.Counter() (despite asymptotically O(n) time being better then O(n*log(n)) for .sort()). Measure it; If it is important.

HTML display result in text (input) field?

innerHTML sets the text (including html elements) inside an element. Normally we use it for elements like div, span etc to insert other html elements inside it.

For your case you want to set the value of an input element. So you should use the value attribute.

Change innerHTML to value

document.getElementById('add').value = sum;

Fatal error: unexpectedly found nil while unwrapping an Optional values

I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view section set the table view cell to the corresponding identifier name you are using in the program, make sure they match.

python paramiko ssh

The code of @ThePracticalOne is great for showing the usage except for one thing: Somtimes the output would be incomplete.(session.recv_ready() turns true after the if session.recv_ready(): while session.recv_stderr_ready() and session.exit_status_ready() turned true before entering next loop)

so my thinking is to retrieving the data when it is ready to exit the session.

while True:
if session.exit_status_ready():
while True:
    while True:
        print "try to recv stdout..."
        ret = session.recv(nbytes)
        if len(ret) == 0:
            break
        stdout_data.append(ret)

    while True:
        print "try to recv stderr..."
        ret = session.recv_stderr(nbytes)
        if len(ret) == 0:
            break
        stderr_data.append(ret)
    break

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

The problem is WHEN the event is added and EXECUTED via triggering (the document onload property modification can be verified by examining the properties list).

When does this execute and modify onload relative to the onload event trigger:

document.addEventListener('load', ... );

before, during or after the load and/or render of the page's HTML?
This simple scURIple (cut & paste to URL) "works" w/o alerting as naively expected:

data:text/html;charset=utf-8,
    <html content editable><head>
          <script>
                document.addEventListener('load', function(){ alert(42) } );
          </script>
          </head><body>goodbye universe - hello muiltiverse</body>
    </html>

Does loading imply script contents have been executed?

A little out of this world expansion ...
Consider a slight modification:

data:text/html;charset=utf-8,
    <html content editable><head>
          <script>
              if(confirm("expand mind?"))document.addEventListener('load', function(){ alert(42) } );
          </script>
        </head><body>goodbye universe - hello muiltiverse</body>
    </html>

and whether the HTML has been loaded or not.

Rendering is certainly pending since goodbye universe - hello muiltiverse is not seen on screen but, does not the confirm( ... ) have to be already loaded to be executed? ... and so document.addEventListener('load', ... ) ... ?

In other words, can you execute code to check for self-loading when the code itself is not yet loaded?

Or, another way of looking at the situation, if the code is executable and executed then it has ALREADY been loaded as a done deal and to retroactively check when the transition occurred between not yet loaded and loaded is a priori fait accompli.

So which comes first: loading and executing the code or using the code's functionality though not loaded?

onload as a window property works because it is subordinate to the object and not self-referential as in the document case, ie. it's the window's contents, via document, that determine the loaded question err situation.

PS.: When do the following fail to alert(...)? (personally experienced gotcha's):

caveat: unless loading to the same window is really fast ... clobbering is the order of the day
so what is really needed below when using the same named window:

window.open(URIstr1,"w") .
   addEventListener('load', 
      function(){ alert(42); 
         window.open(URIstr2,"w") .
            addEventListener('load', 
               function(){ alert(43); 
                  window.open(URIstr3,"w") .
                     addEventListener('load', 
                        function(){ alert(44); 
                 /*  ...  */
                        } )
               } )
      } ) 

alternatively, proceed each successive window.open with:
alert("press Ok either after # alert shows pending load is done or inspired via divine intervention" );

data:text/html;charset=utf-8,
    <html content editable><head><!-- tagging fluff --><script>

        window.open(
            "data:text/plain, has no DOM or" ,"Window"
         ) . addEventListener('load', function(){ alert(42) } )

        window.open(
            "data:text/plain, has no DOM but" ,"Window"
         ) . addEventListener('load', function(){ alert(4) } )

        window.open(
            "data:text/html,<html><body>has DOM and", "Window"
         ) . addEventListener('load', function(){ alert(2) } )

        window.open(
            "data:text/html,<html><body>has DOM and", "noWindow"
         ) . addEventListener('load', function(){ alert(1) } )

        /* etc. including where body has onload=... in each appropriate open */

    </script><!-- terminating fluff --></head></html>

which emphasize onload differences as a document or window property.

Another caveat concerns preserving XSS, Cross Site Scripting, and SOP, Same Origin Policy rules which may allow loading an HTML URI but not modifying it's content to check for same. If a scURIple is run as a bookmarklet/scriplet from the same origin/site then there maybe success.

ie. From an arbitrary page, this link will do the load but not likely do alert('done'):

    <a href="javascript:window.open('view-source:http://google.ca') . 
                   addEventListener( 'load',  function(){ alert('done') }  )"> src. vu </a>

but if the link is bookmarked and then clicked when viewing a google.ca page, it does both.

test environment:

 window.navigator.userAgent = 
   Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 (Splashtop-v1.2.17.0)

Determine the process pid listening on a certain port

I wanted to programmatically -- using only Bash -- kill the process listening on a given port.

Let's say the port is 8089, then here is how I did it:

badPid=$(netstat --listening --program --numeric --tcp | grep "::8089" | awk '{print $7}' | awk -F/ '{print $1}' | head -1)
kill -9 $badPid

I hope this helps someone else! I know it is going to help my team.

TensorFlow: "Attempting to use uninitialized value" in variable initialization

run both:

sess.run(tf.global_variables_initializer())

sess.run(tf.local_variables_initializer())

Plot logarithmic axes with matplotlib in python

I know this is slightly off-topic, since some comments mentioned the ax.set_yscale('log') to be "nicest" solution I thought a rebuttal could be due. I would not recommend using ax.set_yscale('log') for histograms and bar plots. In my version (0.99.1.1) i run into some rendering problems - not sure how general this issue is. However both bar and hist has optional arguments to set the y-scale to log, which work fine.

references: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.hist

CSS: Fix row height

_x000D_
_x000D_
    _x000D_
    table tbody_x000D_
    {_x000D_
        border:1px solid red;_x000D_
    }_x000D_
    table td_x000D_
    {_x000D_
        background:yellow;_x000D_
        _x000D_
        border-bottom:1px solid green;_x000D_
        _x000D_
        _x000D_
    }_x000D_
    .tr0{_x000D_
        line-height:0;_x000D_
     }_x000D_
     .tr0 td{_x000D_
        background:red;_x000D_
     }
_x000D_
<table>_x000D_
<tbody>_x000D_
    <tr><td>test</td></tr>_x000D_
    <tr><td>test</td></tr>    _x000D_
    <tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I create a basic UIButton programmatically?

UIButton *custombutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[custombutton addTarget:self
                 action:@selector(aMethod:)
       forControlEvents:UIControlEventTouchUpInside];
[custombutton setTitle:@"Click" forState:UIControlStateNormal];
custombutton.frame = CGRectMake(80.0, 110.0, 160.0, 40.0);
custombutton.titleLabel.textColor = [UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f  alpha:1];
 [custombutton setImage:[UIImage imageNamed:@"hh.png"] forState:UIControlStateNormal];
 [view addSubview:custombutton];

How to generate classes from wsdl using Maven and wsimport?

The key here is keep option of wsimport. And it is configured using element in About keep from the wsimport documentation :

-keep                     keep generated files

How to round up integer division and have int result in Java?

(message.length() + 152) / 153

This will give a "rounded up" integer.

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Use .gitattributes instead, with the following setting:

# Ignore all differences in line endings
*        -crlf

.gitattributes would be found in the same directory as your global .gitconfig. If .gitattributes doesn't exist, add it to that directory. After adding/changing .gitattributes you will have to do a hard reset of the repository in order to successfully apply the changes to existing files.

Eclipse error "ADB server didn't ACK, failed to start daemon"

Check for the path of the Android directory. It should not contain spaces, etc.

Also check if the plugin has been properly configured in Eclipse ? Preferences.

In my case I had everything checked multiple times, but it was still not working. I was about to reinstall everything, but I came upon an answer on this site (some other post).

Do check your antivirus. It may be blocking the ports of adb.exe or emulator programs, etc. That solved the problem in my case.

PHP Create and Save a txt file to root directory

fopen() will open a resource in the same directory as the file executing the command. In other words, if you're just running the file ~/test.php, your script will create ~/myText.txt.

This can get a little confusing if you're using any URL rewriting (such as in an MVC framework) as it will likely create the new file in whatever the directory contains the root index.php file.

Also, you must have correct permissions set and may want to test before writing to the file. The following would help you debug:

$fp = fopen("myText.txt","wb");
if( $fp == false ){
    //do debugging or logging here
}else{
    fwrite($fp,$content);
    fclose($fp);
}

'cl' is not recognized as an internal or external command,

I had the same issue for a long time and I spent God knows how much on it until I accidentally figured what to do. This solution worked on windows 10. All you need to do is to add C:\WINDOWS\System32 to Path variable under User Variables in Environmental Variables... Note that if you add this to the system variables, it may also work. But, that didn't work for me.

m2e lifecycle-mapping not found

I was having the same issue, where:

No marketplace entries found to handle build-helper-maven-plugin:1.8:add-source in Eclipse. Please see Help for more information.

and clicking the Window > Preferences > Maven > Discovery > open catalog button would report no connection.

Updating from 7u40 to 7u45 on Centos 6.4 and OSX fixes the issue.

Pretty-print a Map in Java

You should be able to do what you want by doing:

System.out.println(map) for example

As long as ALL your objects in the map have overiden the toString method you would see:
{key1=value1, key2=value2} in a meaningfull manner

If this is for your code, then overiding toString is a good habit and I suggest you go for that instead.

For your example where your objects are Strings you should be fine without anything else.
I.e. System.out.println(map) would print exactly what you need without any extra code

How to fix "unable to open stdio.h in Turbo C" error?

Well, I've been working backshift just spent about 6 hours trying to figure this out.

All of the above information led to this conclusion along with a single line in dos prompt screen, when I exited the editor, go to the dos prompt my C: drive is mounted.

I did a dir search and what I found was: the way in which I had mounted the C drive initially looked like this

mount c: /

and my dir did not list all files on the C drive only files within the turboc++ folder. From that I had drawn the conclusion that my directories should look like:

c:\include

not

c:\turboc++\tc\include

or

c:\tc\include

The real problem was the nature in which I had mounted the drive.

Hope this helps someone.

b.mac

fatal: bad default revision 'HEAD'

just do an initial commit and the error will go away:

git commit -m "initial commit"

Generic htaccess redirect www to non-www

I used the above rule to fwd www to no www and it works fine for the homepage, however on the internal pages they are forwarding to /index.php

I found this other rule in my .htaccess file which is causing this but not sure what to do about it. Any suggestions would be great:

############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]

Job for mysqld.service failed See "systemctl status mysqld.service"

I met this problem today, and fix it with bellowed steps.

1, Check the log file /var/log/mysqld.log

tail -f /var/log/mysqld.log

 2017-03-14T07:06:53.374603Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 2 - No such file or directory)
 2017-03-14T07:06:53.374614Z 0 [ERROR] Can't start server: can't create PID file: No such file or directory

The log says that there isn't a file or directory /var/run/mysqld/mysqld.pid

2, Create the directory /var/run/mysqld

mkdir -p /var/run/mysqld/

3, Start the mysqld again service mysqld start, but still fail, check the log again /var/log/mysqld.log

2017-03-14T07:14:22.967667Z 0 [ERROR] /usr/sbin/mysqld: Can't create/write to file '/var/run/mysqld/mysqld.pid' (Errcode: 13 - Permission denied)
2017-03-14T07:14:22.967678Z 0 [ERROR] Can't start server: can't create PID file: Permission denied

It saids permission denied.

4, Grant the permission to mysql chown mysql.mysql /var/run/mysqld/

5, Restart the mysqld

# service mysqld restart
Restarting mysqld (via systemctl):                         [  OK  ]

Postgresql - select something where date = "01/01/11"

I think you want to cast your dt to a date and fix the format of your date literal:

SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

Or the standard version:

SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD

The extract function doesn't understand "date" and it returns a number.

How to use If Statement in Where Clause in SQL?

Nto sure which RDBMS you are using, but if it is SQL Server you could look at rather using a CASE statement

Evaluates a list of conditions and returns one of multiple possible result expressions.

The CASE expression has two formats:

The simple CASE expression compares an expression to a set of simple expressions to determine the result.

The searched CASE expression evaluates a set of Boolean expressions to determine the result.

Both formats support an optional ELSE argument.

How do I get a list of all the duplicate items using pandas in python?

Method #1: print all rows where the ID is one of the IDs in duplicated:

>>> import pandas as pd
>>> df = pd.read_csv("dup.csv")
>>> ids = df["ID"]
>>> df[ids.isin(ids[ids.duplicated()])].sort("ID")
       ID ENROLLMENT_DATE        TRAINER_MANAGING        TRAINER_OPERATOR FIRST_VISIT_DATE
24  11795       27-Feb-12      0643D38-Hanover NH      0643D38-Hanover NH        19-Jun-12
6   11795        3-Jul-12  0649597-White River VT  0649597-White River VT        30-Mar-12
18   8096       19-Dec-11  0649597-White River VT  0649597-White River VT         9-Apr-12
2    8096        8-Aug-12      0643D38-Hanover NH      0643D38-Hanover NH        25-Jun-12
12   A036       30-Nov-11     063B208-Randolph VT     063B208-Randolph VT              NaN
3    A036        1-Apr-12      06CB8CF-Hanover NH      06CB8CF-Hanover NH         9-Aug-12
26   A036       11-Aug-12      06D3206-Hanover NH                     NaN        19-Jun-12

but I couldn't think of a nice way to prevent repeating ids so many times. I prefer method #2: groupby on the ID.

>>> pd.concat(g for _, g in df.groupby("ID") if len(g) > 1)
       ID ENROLLMENT_DATE        TRAINER_MANAGING        TRAINER_OPERATOR FIRST_VISIT_DATE
6   11795        3-Jul-12  0649597-White River VT  0649597-White River VT        30-Mar-12
24  11795       27-Feb-12      0643D38-Hanover NH      0643D38-Hanover NH        19-Jun-12
2    8096        8-Aug-12      0643D38-Hanover NH      0643D38-Hanover NH        25-Jun-12
18   8096       19-Dec-11  0649597-White River VT  0649597-White River VT         9-Apr-12
3    A036        1-Apr-12      06CB8CF-Hanover NH      06CB8CF-Hanover NH         9-Aug-12
12   A036       30-Nov-11     063B208-Randolph VT     063B208-Randolph VT              NaN
26   A036       11-Aug-12      06D3206-Hanover NH                     NaN        19-Jun-12

How to deserialize a list using GSON or another JSON library in Java?

Another way is to use an array as a type, e.g.:

Video[] videoArray = gson.fromJson(json, Video[].class);

This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list, e.g.:

List<Video> videoList = Arrays.asList(videoArray);

IMHO this is much more readable.


In Kotlin this looks like this:

Gson().fromJson(jsonString, Array<Video>::class.java)

To convert this array into List, just use .toList() method

Pass parameter to EventHandler

If I understand your problem correctly, you are calling a method instead of passing it as a parameter. Try the following:

myTimer.Elapsed += PlayMusicEvent;

where

public void PlayMusicEvent(object sender, ElapsedEventArgs e)
{
    music.player.Stop();
    System.Timers.Timer myTimer = (System.Timers.Timer)sender;
    myTimer.Stop();
}

But you need to think about where to store your note.

This declaration has no storage class or type specifier in C++

Calling m.check(side), meaning you are running actual code, but you can't run code outside main() - you can only define variables. In C++, code can only appear inside function bodies or in variable initializes.

How to get MD5 sum of a string using python?

You can use b character in front of a string literal:

import hashlib
print(hashlib.md5(b"Hello MD5").hexdigest())
print(hashlib.md5("Hello MD5".encode('utf-8')).hexdigest())

Out:

e5dadf6524624f79c3127e247f04b548
e5dadf6524624f79c3127e247f04b548

No module named setuptools

Install setuptools and try again.

try command:

sudo apt-get install -y python-setuptools

Error in plot.new() : figure margins too large, Scatter plot

Just clear the plots and try executing the code again...It worked for me

PHP form send email to multiple recipients

If you need to add emails as CC or BCC, add the following part in the variable you use as for your header :

$headers .= "CC: [email protected]".PHP_EOL;
$headers .= "BCC: [email protected]".PHP_EOL;

Regards

Difference between INNER JOIN and LEFT SEMI JOIN

An INNER JOIN can return data from the columns from both tables, and can duplicate values of records on either side have more than one match. A LEFT SEMI JOIN can only return columns from the left-hand table, and yields one of each record from the left-hand table where there is one or more matches in the right-hand table (regardless of the number of matches). It's equivalent to (in standard SQL):

SELECT name
FROM table_1 a
WHERE EXISTS(
    SELECT * FROM table_2 b WHERE (a.name=b.name))

If there are multiple matching rows in the right-hand column, an INNER JOIN will return one row for each match on the right table, while a LEFT SEMI JOIN only returns the rows from the left table, regardless of the number of matching rows on the right side. That's why you're seeing a different number of rows in your result.

I am trying to get the names within table_1 that only appear in table_2.

Then a LEFT SEMI JOIN is the appropriate query to use.

How can I remove the extension of a filename in a shell script?

Answers provided previously have problems with paths containing dots. Some examples:

/xyz.dir/file.ext
./file.ext
/a.b.c/x.ddd.txt

I prefer to use |sed -e 's/\.[^./]*$//'. For example:

$ echo "/xyz.dir/file.ext" | sed -e 's/\.[^./]*$//'
/xyz.dir/file
$ echo "./file.ext" | sed -e 's/\.[^./]*$//'
./file
$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^./]*$//'
/a.b.c/x.ddd

Note: If you want to remove multiple extensions (as in the last example), use |sed -e 's/\.[^/]*$//':

$ echo "/a.b.c/x.ddd.txt" | sed -e 's/\.[^/]*$//'
/a.b.c/x

However, this method will fail in "dot-files" with no extension:

$ echo "/a.b.c/.profile" | sed -e 's/\.[^./]*$//'
/a.b.c/

To cover also such cases, you can use:

$ echo "/a.b.c/.profile" | sed -re 's/(^.*[^/])\.[^./]*$/\1/'
/a.b.c/.profile

How to find the operating system version using JavaScript?

I've created a library for parsing User Agent strings called Voodoo. But be aware that this should not be used instead of feature detection.

What Voodoo does, is that it parses the userAgent string, which is found in the Navigator object (window.navigator). It's not all browsers that passes a reliable userAgent string, so even though it's the normal way to do it, the userAgent can not always be trusted.

JSON library for C#

To answer your first question, Microsoft does ship a DataContractJsonSerializer: see msdn How to: Serialize and Deserialize JSON Data

How to finish Activity when starting other activity in Android?

The best - and simplest - solution might be this:

Intent intent = new Intent(this, OtherActivity.class);
startActivity(intent);
finishAndRemoveTask();

Documentation for finishAndRemoveTask():

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Is that what you're looking for?

How to read string from keyboard using C?

When reading input from any file (stdin included) where you do not know the length, it is often better to use getline rather than scanf or fgets because getline will handle memory allocation for your string automatically so long as you provide a null pointer to receive the string entered. This example will illustrate:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {

    char *line = NULL;  /* forces getline to allocate with malloc */
    size_t len = 0;     /* ignored when line = NULL */
    ssize_t read;

    printf ("\nEnter string below [ctrl + d] to quit\n");

    while ((read = getline(&line, &len, stdin)) != -1) {

        if (read > 0)
            printf ("\n  read %zd chars from stdin, allocated %zd bytes for line : %s\n", read, len, line);

        printf ("Enter string below [ctrl + d] to quit\n");
    }

    free (line);  /* free memory allocated by getline */

    return 0;
}

The relevant parts being:

char *line = NULL;  /* forces getline to allocate with malloc */
size_t len = 0;     /* ignored when line = NULL */
/* snip */
read = getline (&line, &len, stdin);

Setting line to NULL causes getline to allocate memory automatically. Example output:

$ ./getline_example

Enter string below [ctrl + d] to quit
A short string to test getline!

  read 32 chars from stdin, allocated 120 bytes for line : A short string to test getline!

Enter string below [ctrl + d] to quit
A little bit longer string to show that getline will allocated again without resetting line = NULL

  read 99 chars from stdin, allocated 120 bytes for line : A little bit longer string to show that getline will allocated again without resetting line = NULL

Enter string below [ctrl + d] to quit

So with getline you do not need to guess how long your user's string will be.

"Parser Error Message: Could not load type" in Global.asax

cant load errors with your project firstly Fix your errors and after rebuild project its working

Python calling method in class

Let's say you have a shiny Foo class. Well you have 3 options:

1) You want to use the method (or attribute) of a class inside the definition of that class:

class Foo(object):
    attribute1 = 1                   # class attribute (those don't use 'self' in declaration)
    def __init__(self):
        self.attribute2 = 2          # instance attribute (those are accessible via first
                                     # parameter of the method, usually called 'self'
                                     # which will contain nothing but the instance itself)
    def set_attribute3(self, value): 
        self.attribute3 = value

    def sum_1and2(self):
        return self.attribute1 + self.attribute2

2) You want to use the method (or attribute) of a class outside the definition of that class

def get_legendary_attribute1():
    return Foo.attribute1

def get_legendary_attribute2():
    return Foo.attribute2

def get_legendary_attribute1_from(cls):
    return cls.attribute1

get_legendary_attribute1()           # >>> 1
get_legendary_attribute2()           # >>> AttributeError: type object 'Foo' has no attribute 'attribute2'
get_legendary_attribute1_from(Foo)   # >>> 1

3) You want to use the method (or attribute) of an instantiated class:

f = Foo()
f.attribute1                         # >>> 1
f.attribute2                         # >>> 2
f.attribute3                         # >>> AttributeError: 'Foo' object has no attribute 'attribute3'
f.set_attribute3(3)
f.attribute3                         # >>> 3

How to clear textarea on click?

Did you mean like this for textfield?

<input type="text" onblur="if(this.value == '') this.value='SEARCH';" onfocus="if(this.value == 'SEARCH') this.value='';" size="15" value="SEARCH" name="xSearch" id="xSearch">

Or this for textarea?

<textarea id="usermsg" rows="2" cols="70" onfocus="if(this.value == 'enter your text here') this.value='';" onblur="if(this.value == '') this.value='enter your text here';" >enter your text here</textarea>

Can Mockito capture arguments of a method called multiple times?

I think it should be

verify(mockBar, times(2)).doSomething(...)

Sample from mockito javadoc:

ArgumentCaptor<Person> peopleCaptor = ArgumentCaptor.forClass(Person.class);
verify(mock, times(2)).doSomething(peopleCaptor.capture());

List<Person> capturedPeople = peopleCaptor.getAllValues();
assertEquals("John", capturedPeople.get(0).getName());
assertEquals("Jane", capturedPeople.get(1).getName());

Setting DIV width and height in JavaScript

If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox

Condensed example:

<html>
    <head>
        <script type="text/javascript">
            function show_update_profile() {
               document.getElementById('div_register').style.height= "500px";
               document.getElementById('div_register').style.width= "500px";
               document.getElementById('div_register').style.display='block';
               return true;
           }
        </script>
        <style>
           /* just to show dimensions of div */
           #div_register
           {
                background-color: #cfc;
           }
        </style>
    </head>
    <body>
        <div id="main">
            <input type="button" onclick="show_update_profile();" value="show"/>
        </div>
        <div id="div_register">
            <table>
                <tr>
                   <td>
                     welcome 
                   </td>
                </tr>
            </table>
        </div>
    </body>
</html>

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

If you are using arrow functions:

it('should do something', async () => {
  // do your testing
}).timeout(15000)

c# Image resizing to different size while preserving aspect ratio

This should do it.

private void resizeImage(string path, string originalFilename, 
                     /* note changed names */
                     int canvasWidth, int canvasHeight, 
                     /* new */
                     int originalWidth, int originalHeight)
{
    Image image = Image.FromFile(path + originalFilename);

    System.Drawing.Image thumbnail = 
        new Bitmap(canvasWidth, canvasHeight); // changed parm names
    System.Drawing.Graphics graphic = 
                 System.Drawing.Graphics.FromImage(thumbnail);

    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = SmoothingMode.HighQuality;
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphic.CompositingQuality = CompositingQuality.HighQuality;

    /* ------------------ new code --------------- */

    // Figure out the ratio
    double ratioX = (double) canvasWidth / (double) originalWidth;
    double ratioY = (double) canvasHeight / (double) originalHeight;
    // use whichever multiplier is smaller
    double ratio = ratioX < ratioY ? ratioX : ratioY;

    // now we can get the new height and width
    int newHeight = Convert.ToInt32(originalHeight * ratio);
    int newWidth = Convert.ToInt32(originalWidth * ratio);

    // Now calculate the X,Y position of the upper-left corner 
    // (one of these will always be zero)
    int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2);
    int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2);

    graphic.Clear(Color.White); // white padding
    graphic.DrawImage(image, posX, posY, newWidth, newHeight);

    /* ------------- end new code ---------------- */

    System.Drawing.Imaging.ImageCodecInfo[] info =
                     ImageCodecInfo.GetImageEncoders();
    EncoderParameters encoderParameters;
    encoderParameters = new EncoderParameters(1);
    encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality,
                     100L);            
    thumbnail.Save(path + newWidth + "." + originalFilename, info[1], 
                     encoderParameters);
}

Edited to add:

Those who want to improve this code should put it in the comments, or a new answer. Don't edit this code directly.

Stick button to right side of div

<div>
    <h1> Ok </h1>
    <button type='button'>Button</button>
    <div style="clear:both;"></div>
</div>

css

div {
    background: purple;
}

div h1 {
    text-align: center;
}

div button {
    float: right;
    margin-right:10px;

}

fatal: early EOF fatal: index-pack failed

In my case this was quite helpful:

git clone --depth 1 --branch $BRANCH $URL

This will limit the checkout to mentioned branch only, hence will speed up the process.

Hope this will help.

Spring Could not Resolve placeholder

in my case, the war file generated didn't pick up the properties file so had to clean install again in IntelliJ editor.

How can the default node version be set using NVM?

Lets say to want to make default version as 10.19.0.

nvm alias default v10.19.0

But it will give following error

! WARNING: Version 'v10.19.0' does not exist.
default -> v10.19.0 (-> N/A)

In That case you need to run two commands in the following order

# Install the version that you would like 
nvm install 10.19.0

# Set 10.19.0 (or another version) as default
nvm alias default 10.19.0

get selected value in datePicker and format it

$('#scheduleDate').datepicker({ dateFormat : 'dd, MM, yy'});

var dateFormat = $('#scheduleDate').datepicker('option', 'dd, MM, yy');

$('#scheduleDate').datepicker('option', 'dateFormat', 'dd, MM, yy');

var result = $('#scheduleDate').val();

alert('result: ' + result);

result: 20, April, 2012

the getSource() and getActionCommand()

I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").

I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:

public class SeleccionListener implements ActionListener, FocusListener {}

So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:

public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
        System.out.println("Aceptar pressed");
    }

In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).

public void focusGained(FocusEvent focusEvent) {
    if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
        System.out.println("Data radio button");
    }

In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)

Serializing class instance to JSON

The basic problem is that the JSON encoder json.dumps() only knows how to serialize a limited set of object types by default, all built-in types. List here: https://docs.python.org/3.3/library/json.html#encoders-and-decoders

One good solution would be to make your class inherit from JSONEncoder and then implement the JSONEncoder.default() function, and make that function emit the correct JSON for your class.

A simple solution would be to call json.dumps() on the .__dict__ member of that instance. That is a standard Python dict and if your class is simple it will be JSON serializable.

class Foo(object):
    def __init__(self):
        self.x = 1
        self.y = 2

foo = Foo()
s = json.dumps(foo) # raises TypeError with "is not JSON serializable"

s = json.dumps(foo.__dict__) # s set to: {"x":1, "y":2}

The above approach is discussed in this blog posting:

    Serializing arbitrary Python objects to JSON using __dict__

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

First, install the URL Rewrite from a download or from the Web Platform Installer. Second, restart IIS. And, finally, close IIS and open again. The last step worked for me.

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

C - gettimeofday for computing time?

If you want to measure code efficiency, or in any other way measure time intervals, the following will be easier:

#include <time.h>

int main()
{
   clock_t start = clock();
   //... do work here
   clock_t end = clock();
   double time_elapsed_in_seconds = (end - start)/(double)CLOCKS_PER_SEC;
   return 0;
}

hth

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

For those that are passing both a port and a host, keep in mind that Heroku will not bind to localhost.

You must pass 0.0.0.0 for host.

Even if you're using the correct port. We had to make this adjustment:

# port (as described above) and host are both wrong
const host = 'localhost';
const port = 3000;

# use alternate localhost and the port Heroku assigns to $PORT
const host = '0.0.0.0';
const port = process.env.PORT || 3000;

Then you can start the server, as usual:

app.listen(port, host, function() {
  console.log("Server started.......");
});

You can see more details here: https://help.heroku.com/P1AVPANS/why-is-my-node-js-app-crashing-with-an-r10-error

Sort Pandas Dataframe by Date

@JAB's answer is fast and concise. But it changes the DataFrame you are trying to sort, which you may or may not want.

(Note: You almost certainly will want it, because your date columns should be dates, not strings!)

In the unlikely event that you don't want to change the dates into dates, you can also do it a different way.

First, get the index from your sorted Date column:

In [25]: pd.to_datetime(df.Date).order().index
Out[25]: Int64Index([0, 2, 1], dtype='int64')

Then use it to index your original DataFrame, leaving it untouched:

In [26]: df.ix[pd.to_datetime(df.Date).order().index]
Out[26]: 
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

Magic!

Note: for Pandas versions 0.20.0 and later, use loc instead of ix, which is now deprecated.

Load jQuery with Javascript and use jQuery

From the DevTools console, you can run:

document.getElementsByTagName("head")[0].innerHTML += '<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"><\/script>';

Check the available jQuery version at https://code.jquery.com/jquery/.

To check whether it's loaded, see: Checking if jquery is loaded using Javascript.

jQuery UI: Datepicker set year range dropdown to 100 years

You can set the year range using this option per documentation here http://api.jqueryui.com/datepicker/#option-yearRange

yearRange: '1950:2013', // specifying a hard coded year range

or this way

yearRange: "-100:+0", // last hundred years

From the Docs

Default: "c-10:c+10"

The range of years displayed in the year drop-down: either relative to today's year ("-nn:+nn"), relative to the currently selected year ("c-nn:c+nn"), absolute ("nnnn:nnnn"), or combinations of these formats ("nnnn:-nn"). Note that this option only affects what appears in the drop-down, to restrict which dates may be selected use the minDate and/or maxDate options.

CSS3 equivalent to jQuery slideUp and slideDown?

why not to take advantage of modern browsers css transition and make things simpler and fast using more css and less jquery

Here is the code for sliding up and down

Here is the code for sliding left to right

Similarly we can change the sliding from top to bottom or right to left by changing transform-origin and transform: scaleX(0) or transform: scaleY(0) appropriately.

Detecting EOF in C

as a starting point you could try replacing

while(!EOF)

with

while(!feof(stdin))

How can I select from list of values in Oracle

If you are seeking to convert a comma delimited list of values:

select column_value 
from table(sys.dbms_debug_vc2coll('One', 'Two', 'Three', 'Four'));

-- Or

select column_value 
from table(sys.dbms_debug_vc2coll(1,2,3,4));

If you wish to convert a string of comma delimited values then I would recommend Justin Cave's regular expression SQL solution.

How to specify table's height such that a vertical scroll bar appears?

This CSS also shows a fixed height HTML table. It sets the height of the HTML tbody to 400 pixels and the HTML tbody scrolls when the it is larger, retaining the HTML thead as a non-scrolling element.

In addition, each th cell in the heading and each td cell the body should be styled for the desired fixed width.

#the-table {
  display: block;
  background: white; /* optional */
}

#the-table thead {
  text-align: left; /* optional */
}

#the-table tbody {
  display: block;
  max-height: 400px;
  overflow-y: scroll;
}

How can I detect when an Android application is running in the emulator?

use this function :

 public static final boolean isEmulator() {

    int rating = 0;

    if ((Build.PRODUCT.equals("sdk")) || (Build.PRODUCT.equals("google_sdk"))
            || (Build.PRODUCT.equals("sdk_x86")) || (Build.PRODUCT.equals("vbox86p"))) {
        rating++;
    }
    if ((Build.MANUFACTURER.equals("unknown")) || (Build.MANUFACTURER.equals("Genymotion"))) {
        rating++;
    }
    if ((Build.BRAND.equals("generic")) || (Build.BRAND.equals("generic_x86"))) {
        rating++;
    }
    if ((Build.DEVICE.equals("generic")) || (Build.DEVICE.equals("generic_x86")) || (Build.DEVICE.equals("vbox86p"))) {
        rating++;
    }
    if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))
            || (Build.MODEL.equals("Android SDK built for x86"))) {
        rating++;
    }
    if ((Build.HARDWARE.equals("goldfish")) || (Build.HARDWARE.equals("vbox86"))) {
        rating++;
    }
    if ((Build.FINGERPRINT.contains("generic/sdk/generic"))
            || (Build.FINGERPRINT.contains("generic_x86/sdk_x86/generic_x86"))
            || (Build.FINGERPRINT.contains("generic/google_sdk/generic"))
            || (Build.FINGERPRINT.contains("generic/vbox86p/vbox86p"))) {
        rating++;
    }

    return rating > 4;

    }

jQuery changing style of HTML element

Use this:

$('#navigation ul li').css('display', 'inline-block');

Also, as others have stated, if you want to make multiple css changes at once, that's when you would add the curly braces (for object notation), and it would look something like this (if you wanted to change, say, 'background-color' and 'position' in addition to 'display'):

$('#navigation ul li').css({'display': 'inline-block', 'background-color': '#fff', 'position': 'relative'}); //The specific CSS changes after the first one, are, of course, just examples.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Command CompileSwift failed with a nonzero exit code in Xcode 10

Here is the solution: - Go to build settings - Search SWIFT_COMPILATION_MODE - If this is "Whole Module" for Release configuration then change it to "Incremental". - Archive now.

When you change the setting to "Incremental" the process succeeds.

How do you connect to a MySQL database using Oracle SQL Developer?

You may find the following relevant as well:

Oracle SQL Developer connection to Microsoft SQL Server

In my case I had to place the ntlmauth.dll in the sql-developer application directory itself (i.e. sql-developer\jdk\jre\bin). Why this location over the system jre/bin I have no idea. But it worked.

bitwise XOR of hex numbers in python

If the two hex strings are the same length and you want a hex string output then you might try this.

def hexxor(a, b):    # xor two hex strings of the same length
    return "".join(["%x" % (int(x,16) ^ int(y,16)) for (x, y) in zip(a, b)])

Icons missing in jQuery UI

I have put the images in a convenient zip file: http://zlab.co.za/lib_help/jquery-ui.css.images.zip

As the readme.txt file in the zip file reads: Place the "images" folder in the same folder where your "jquery-ui.css" file is located.

I hope this helps :)

What is the idiomatic Go equivalent of C's ternary operator?

The map ternary is easy to read without parentheses:

c := map[bool]int{true: 1, false: 0} [5 > 4]

MSSQL Regular expression

Thank you all for your help.

This is what I have used in the end:

SELECT *, 
  CASE WHEN [url] NOT LIKE '%[^-A-Za-z0-9/.+$]%' 
    THEN 'Valid' 
    ELSE 'No valid' 
  END [Validate]
FROM 
  *table*
  ORDER BY [Validate]

Tensorflow installation error: not a supported wheel on this platform

Make sure that the wheel is, well, supported by your platform. Pip uses the wheel's filename to determine compatibility. The format is:

tensorflow-{version}-{python version}-none-{your platform}.whl

I didn't realize that x86_64 refers to x64, I thought it meant either x86 or x64, so I banged my head against this futilely for some time. Tensorflow is not available for 32 bit systems, unless you want to compile it yourself.

Looping through a hash, or using an array in PowerShell

About looping through a hash:

$Q = @{"ONE"="1";"TWO"="2";"THREE"="3"}
$Q.GETENUMERATOR() | % { $_.VALUE }
1
3
2

$Q.GETENUMERATOR() | % { $_.key }
ONE
THREE
TWO

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Running a command through /usr/bin/env has the benefit of looking for whatever the default version of the program is in your current environment.

This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it.

One downside is that you will be unable to pass more than one argument (e.g. you will be unable to write /usr/bin/env awk -f) if you wish to support Linux, as POSIX is vague on how the line is to be interpreted, and Linux interprets everything after the first space to denote a single argument. You can use /usr/bin/env -S on some versions of env to get around this, but then the script will become even less portable and break on fairly recent systems (e.g. even Ubuntu 16.04 if not later).

Another downside is that since you aren't calling an explicit executable, it's got the potential for mistakes, and on multiuser systems security problems (if someone managed to get their executable called bash in your path, for example).

#!/usr/bin/env bash #lends you some flexibility on different systems
#!/usr/bin/bash     #gives you explicit control on a given system of what executable is called

In some situations, the first may be preferred (like running python scripts with multiple versions of python, without having to rework the executable line). But in situations where security is the focus, the latter would be preferred, as it limits code injection possibilities.

What's the best way to select the minimum value from several columns?

I know that question is old, but I was still in the need of the answer and was not happy with other answers so I had to devise my own which is a twist on @paxdiablo´s answer.


I came from land of SAP ASE 16.0, and I only needed a peek at statistics of certain data which are IMHO validly stored in different columns of a single row (they represent different times - when arrival of something was planned, what it was expected when the action started and finally what was the actual time). Thus I had transposed columns into the rows of temporary table and preformed my query over this as usually.

N.B. Not the one-size-fits-all solution ahead!

CREATE TABLE #tempTable (ID int, columnName varchar(20), dataValue int)

INSERT INTO #tempTable 
  SELECT ID, 'Col1', Col1
    FROM sourceTable
   WHERE Col1 IS NOT NULL
INSERT INTO #tempTable 
  SELECT ID, 'Col2', Col2
    FROM sourceTable
   WHERE Col2 IS NOT NULL
INSERT INTO #tempTable 
  SELECT ID, 'Col3', Col3
    FROM sourceTable
   WHERE Col3 IS NOT NULL

SELECT ID
     , min(dataValue) AS 'Min'
     , max(dataValue) AS 'Max'
     , max(dataValue) - min(dataValue) AS 'Diff' 
  FROM #tempTable 
  GROUP BY ID

This took some 30 seconds on source set of 630000 rows and used only index-data, so not the thing to run in time-critical process but for things like one-time data inspection or end-of-the-day report you might be fine (but verify this with your peers or superiors, please!). Main bonus of this style for me was that I could readily use more/less columns and change grouping, filtering, etc., especially once data was copyied over.

The additional data (columnName, maxes, ...) were to aid me in my search, so you might not need them; I left them here to maybe spark some ideas :-).

What is the inclusive range of float and double in Java?

From Primitives Data Types:

  • float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in section 4.2.3 of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

For the range of values, see the section 4.2.3 Floating-Point Types, Formats, and Values of the JLS.

How to add item to the beginning of List<T>?

Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

Powershell: count members of a AD group

The Get-ADGroupMember cmdlet would solve this in a much more efficient way than you're tying.

As an example:

$users = Get-ADGroupMember -Identity 'Group Name'
$users.count
132

EDIT:

In order to clarify things, and to make your script simpler. Here's a generic script that will work for your environment that outputs the user count for each group matching your filters.

$groups = Get-ADGroup -filter {(name -like "WA*") -or (name -like "workstation*")}
foreach($group in $groups){
  $countUser = (Get-ADGroupMember $group.DistinguishedName).count
  Write-Host "The group $($group.Name) has $countUser user(s)."
}

vba: get unique values from array

Update (6/15/16)

I have created much more thorough benchmarks. First of all, as @ChaimG pointed out, early binding makes a big difference (I originally used @eksortso's code above verbatim which uses late binding). Secondly, my original benchmarks only included the time to create the unique object, however, it did not test the efficiency of using the object. My point in doing this is, it doesn't really matter if I can create an object really fast if the object I create is clunky and slows me down moving forward.

Old Remark: It turns out, that looping over a collection object is highly inefficient

It turns out that looping over a collection can be quite efficient if you know how to do it (I didn't). As @ChaimG (yet again), pointed out in the comments, using a For Each construct is ridiculously superior to simply using a For loop. To give you an idea, before changing the loop construct, the time for Collection2 for the Test Case Size = 10^6 was over 1400s (i.e. ~23 minutes). It is now a meager 0.195s (over 7000x faster).

For the Collection method there are two times. The first (my original benchmark Collection1) show the time to create the unique object. The second part (Collection2) shows the time to loop over the object (which is very natural) to create a returnable array as the other functions do.

In the chart below, a yellow background indicates that it was the fastest for that test case, and red indicates the slowest ("Not Tested" algorithms are excluded). The total time for the Collection method is the sum of Collection1 and Collection2. Turquoise indicates that is was the fastest regardless of original order.

Benchmarks5

Below is the original algorithm I created (I have modified it slightly e.g. I no longer instantiate my own data type). It returns the unique values of an array with the original order in a very respectable time and it can be modified to take on any data type. Outside of the IndexMethod, it is the fastest algorithm for very large arrays.

Here are the main ideas behind this algorithm:

  1. Index the array
  2. Sort by values
  3. Place identical values at the end of the array and subsequently "chop" them off.
  4. Finally, sort by index.

Below is an example:

Let myArray = (86, 100, 33, 19, 33, 703, 19, 100, 703, 19)

    1.  (86, 100, 33, 19, 33, 703, 19, 100, 703, 19)
        (1 ,   2,  3,  4,  5,   6,  7,   8,   9, 10)   <<-- Indexing

    2.  (19, 19, 19, 33, 33, 86, 100, 100, 703, 703)   <<-- sort by values     
        (4,   7, 10,  3,  5,  1,   2,   8,   6,   9)

    3.  (19, 33,  86, 100, 703)   <<-- remove duplicates    
        (4,   3,   1,   2,   6)

    4.  (86, 100,  33, 19, 703)   
        ( 1,   2,   3,  4,   6)   <<-- sort by index

Here is the code:

Function SortingUniqueTest(ByRef myArray() As Long, bOrigIndex As Boolean) As Variant
    Dim MyUniqueArr() As Long, i As Long, intInd As Integer
    Dim StrtTime As Double, Endtime As Double, HighB As Long, LowB As Long

    LowB = LBound(myArray): HighB = UBound(myArray)

    ReDim MyUniqueArr(1 To 2, LowB To HighB)
    intInd = 1 - LowB  'Guarantees the indices span 1 to Lim

    For i = LowB To HighB
        MyUniqueArr(1, i) = myArray(i)
        MyUniqueArr(2, i) = i + intInd
    Next i

    QSLong2D MyUniqueArr, 1, LBound(MyUniqueArr, 2), UBound(MyUniqueArr, 2), 2
    Call UniqueArray2D(MyUniqueArr)
    If bOrigIndex Then QSLong2D MyUniqueArr, 2, LBound(MyUniqueArr, 2), UBound(MyUniqueArr, 2), 2

    SortingUniqueTest = MyUniqueArr()
End Function

Public Sub UniqueArray2D(ByRef myArray() As Long)
    Dim i As Long, j As Long, Count As Long, Count1 As Long, DuplicateArr() As Long
    Dim lngTemp As Long, HighB As Long, LowB As Long
    LowB = LBound(myArray, 2): Count = LowB: i = LowB: HighB = UBound(myArray, 2)

    Do While i < HighB
        j = i + 1
        If myArray(1, i) = myArray(1, j) Then
            Do While myArray(1, i) = myArray(1, j)
                ReDim Preserve DuplicateArr(1 To Count)
                DuplicateArr(Count) = j
                Count = Count + 1
                j = j + 1
                If j > HighB Then Exit Do
            Loop

            QSLong2D myArray, 2, i, j - 1, 2
        End If
        i = j
    Loop

    Count1 = HighB

    If Count > 1 Then
        For i = UBound(DuplicateArr) To LBound(DuplicateArr) Step -1
            myArray(1, DuplicateArr(i)) = myArray(1, Count1)
            myArray(2, DuplicateArr(i)) = myArray(2, Count1)
            Count1 = Count1 - 1
            ReDim Preserve myArray(1 To 2, LowB To Count1)
        Next i
    End If
End Sub

Here is the sorting algorithm I use (more about this algo here).

Sub QSLong2D(ByRef saArray() As Long, bytDim As Byte, lLow1 As Long, lHigh1 As Long, bytNum As Byte)
    Dim lLow2 As Long, lHigh2 As Long
    Dim sKey As Long, sSwap As Long, i As Byte

On Error GoTo ErrorExit

    If IsMissing(lLow1) Then lLow1 = LBound(saArray, bytDim)
    If IsMissing(lHigh1) Then lHigh1 = UBound(saArray, bytDim)
    lLow2 = lLow1
    lHigh2 = lHigh1

    sKey = saArray(bytDim, (lLow1 + lHigh1) \ 2)

    Do While lLow2 < lHigh2
        Do While saArray(bytDim, lLow2) < sKey And lLow2 < lHigh1: lLow2 = lLow2 + 1: Loop
        Do While saArray(bytDim, lHigh2) > sKey And lHigh2 > lLow1: lHigh2 = lHigh2 - 1: Loop

        If lLow2 < lHigh2 Then
            For i = 1 To bytNum
                sSwap = saArray(i, lLow2)
                saArray(i, lLow2) = saArray(i, lHigh2)
                saArray(i, lHigh2) = sSwap
            Next i
        End If

        If lLow2 <= lHigh2 Then
            lLow2 = lLow2 + 1
            lHigh2 = lHigh2 - 1
        End If
    Loop

    If lHigh2 > lLow1 Then QSLong2D saArray(), bytDim, lLow1, lHigh2, bytNum
    If lLow2 < lHigh1 Then QSLong2D saArray(), bytDim, lLow2, lHigh1, bytNum

ErrorExit:

End Sub

Below is a special algorithm that is blazing fast if your data contains integers. It makes use of indexing and the Boolean data type.

Function IndexSort(ByRef myArray() As Long, bOrigIndex As Boolean) As Variant
'' Modified to take both positive and negative integers
    Dim arrVals() As Long, arrSort() As Long, arrBool() As Boolean
    Dim i As Long, HighB As Long, myMax As Long, myMin As Long, OffSet As Long
    Dim LowB As Long, myIndex As Long, count As Long, myRange As Long

    HighB = UBound(myArray)
    LowB = LBound(myArray)

    For i = LowB To HighB
        If myArray(i) > myMax Then myMax = myArray(i)
        If myArray(i) < myMin Then myMin = myArray(i)
    Next i

    OffSet = Abs(myMin)  '' Number that will be added to every element
                         '' to guarantee every index is non-negative

    If myMax > 0 Then
        myRange = myMax + OffSet  '' E.g. if myMax = 10 & myMin = -2, then myRange = 12
    Else
        myRange = OffSet
    End If

    If bOrigIndex Then
        ReDim arrSort(1 To 2, 1 To HighB)
        ReDim arrVals(1 To 2, 0 To myRange)
        ReDim arrBool(0 To myRange)

        For i = LowB To HighB
            myIndex = myArray(i) + OffSet
            arrBool(myIndex) = True
            arrVals(1, myIndex) = myArray(i)
            If arrVals(2, myIndex) = 0 Then arrVals(2, myIndex) = i
        Next i

        For i = 0 To myRange
            If arrBool(i) Then
                count = count + 1
                arrSort(1, count) = arrVals(1, i)
                arrSort(2, count) = arrVals(2, i)
            End If
        Next i

        QSLong2D arrSort, 2, 1, count, 2
        ReDim Preserve arrSort(1 To 2, 1 To count)
    Else
        ReDim arrSort(1 To HighB)
        ReDim arrVals(0 To myRange)
        ReDim arrBool(0 To myRange)

        For i = LowB To HighB
            myIndex = myArray(i) + OffSet
            arrBool(myIndex) = True
            arrVals(myIndex) = myArray(i)
        Next i

        For i = 0 To myRange
            If arrBool(i) Then
                count = count + 1
                arrSort(count) = arrVals(i)
            End If
        Next i

        ReDim Preserve arrSort(1 To count)
    End If

    ReDim arrVals(0)
    ReDim arrBool(0)

    IndexSort = arrSort
End Function

Here are the Collection (by @DocBrown) and Dictionary (by @eksortso) Functions.

Function CollectionTest(ByRef arrIn() As Long, Lim As Long) As Variant
    Dim arr As New Collection, a, i As Long, arrOut() As Variant, aFirstArray As Variant
    Dim StrtTime As Double, EndTime1 As Double, EndTime2 As Double, count As Long
On Error Resume Next

    ReDim arrOut(1 To UBound(arrIn))
    ReDim aFirstArray(1 To UBound(arrIn))

    StrtTime = Timer
    For i = 1 To UBound(arrIn): aFirstArray(i) = CStr(arrIn(i)): Next i '' Convert to string
    For Each a In aFirstArray               ''' This part is actually creating the unique set
        arr.Add a, a
    Next
    EndTime1 = Timer - StrtTime

    StrtTime = Timer         ''' This part is writing back to an array for return
    For Each a In arr: count = count + 1: arrOut(count) = a: Next a
    EndTime2 = Timer - StrtTime
    CollectionTest = Array(arrOut, EndTime1, EndTime2)
End Function

Function DictionaryTest(ByRef myArray() As Long, Lim As Long) As Variant
    Dim StrtTime As Double, Endtime As Double
    Dim d As Scripting.Dictionary, i As Long  '' Early Binding
    Set d = New Scripting.Dictionary
    For i = LBound(myArray) To UBound(myArray): d(myArray(i)) = 1: Next i
    DictionaryTest = d.Keys()
End Function

Here is the Direct approach provided by @IsraelHoletz.

Function ArrayUnique(ByRef aArrayIn() As Long) As Variant
    Dim aArrayOut() As Variant, bFlag As Boolean, vIn As Variant, vOut As Variant
    Dim i As Long, j As Long, k As Long
    ReDim aArrayOut(LBound(aArrayIn) To UBound(aArrayIn))
    i = LBound(aArrayIn)
    j = i

    For Each vIn In aArrayIn
        For k = j To i - 1
            If vIn = aArrayOut(k) Then bFlag = True: Exit For
        Next
        If Not bFlag Then aArrayOut(i) = vIn: i = i + 1
        bFlag = False
    Next

    If i <> UBound(aArrayIn) Then ReDim Preserve aArrayOut(LBound(aArrayIn) To i - 1)
    ArrayUnique = aArrayOut
End Function

Function DirectTest(ByRef aArray() As Long, Lim As Long) As Variant
    Dim aReturn() As Variant
    Dim StrtTime As Long, Endtime As Long, i As Long
    aReturn = ArrayUnique(aArray)
    DirectTest = aReturn
End Function

Here is the benchmark function that compares all of the functions. You should note that the last two cases are handled a little bit different because of memory issues. Also note, that I didn't test the Collection method for the Test Case Size = 10,000,000. For some reason, it was returning incorrect results and behaving unusual (I'm guessing the collection object has a limit on how many things you can put in it. I searched and I couldn't find any literature on this).

Function UltimateTest(Lim As Long, bTestDirect As Boolean, bTestDictionary, bytCase As Byte) As Variant

    Dim dictionTest, collectTest, sortingTest1, indexTest1, directT '' all variants
    Dim arrTest() As Long, i As Long, bEquality As Boolean, SizeUnique As Long
    Dim myArray() As Long, StrtTime As Double, EndTime1 As Variant
    Dim EndTime2 As Double, EndTime3 As Variant, EndTime4 As Double
    Dim EndTime5 As Double, EndTime6 As Double, sortingTest2, indexTest2

    ReDim myArray(1 To Lim): Rnd (-2)   '' If you want to test negative numbers, 
    '' insert this to the left of CLng(Int(Lim... : (-1) ^ (Int(2 * Rnd())) *
    For i = LBound(myArray) To UBound(myArray): myArray(i) = CLng(Int(Lim * Rnd() + 1)): Next i
    arrTest = myArray

    If bytCase = 1 Then
        If bTestDictionary Then
            StrtTime = Timer: dictionTest = DictionaryTest(arrTest, Lim): EndTime1 = Timer - StrtTime
        Else
            EndTime1 = "Not Tested"
        End If

        arrTest = myArray
        collectTest = CollectionTest(arrTest, Lim)

        arrTest = myArray
        StrtTime = Timer: sortingTest1 = SortingUniqueTest(arrTest, True): EndTime2 = Timer - StrtTime
        SizeUnique = UBound(sortingTest1, 2)

        If bTestDirect Then
            arrTest = myArray: StrtTime = Timer: directT = DirectTest(arrTest, Lim): EndTime3 = Timer - StrtTime
        Else
            EndTime3 = "Not Tested"
        End If

        arrTest = myArray
        StrtTime = Timer: indexTest1 = IndexSort(arrTest, True): EndTime4 = Timer - StrtTime

        arrTest = myArray
        StrtTime = Timer: sortingTest2 = SortingUniqueTest(arrTest, False): EndTime5 = Timer - StrtTime

        arrTest = myArray
        StrtTime = Timer: indexTest2 = IndexSort(arrTest, False): EndTime6 = Timer - StrtTime

        bEquality = True
        For i = LBound(sortingTest1, 2) To UBound(sortingTest1, 2)
            If Not CLng(collectTest(0)(i)) = sortingTest1(1, i) Then
                bEquality = False
                Exit For
            End If
        Next i

        For i = LBound(dictionTest) To UBound(dictionTest)
            If Not dictionTest(i) = sortingTest1(1, i + 1) Then
                bEquality = False
                Exit For
            End If
        Next i

        For i = LBound(dictionTest) To UBound(dictionTest)
            If Not dictionTest(i) = indexTest1(1, i + 1) Then
                bEquality = False
                Exit For
            End If
        Next i

        If bTestDirect Then
            For i = LBound(dictionTest) To UBound(dictionTest)
                If Not dictionTest(i) = directT(i + 1) Then
                    bEquality = False
                    Exit For
                End If
            Next i
        End If

        UltimateTest = Array(bEquality, EndTime1, EndTime2, EndTime3, EndTime4, _
                        EndTime5, EndTime6, collectTest(1), collectTest(2), SizeUnique)
    ElseIf bytCase = 2 Then
        arrTest = myArray
        collectTest = CollectionTest(arrTest, Lim)
        UltimateTest = Array(collectTest(1), collectTest(2))
    ElseIf bytCase = 3 Then
        arrTest = myArray
        StrtTime = Timer: sortingTest1 = SortingUniqueTest(arrTest, True): EndTime2 = Timer - StrtTime
        SizeUnique = UBound(sortingTest1, 2)
        UltimateTest = Array(EndTime2, SizeUnique)
    ElseIf bytCase = 4 Then
        arrTest = myArray
        StrtTime = Timer: indexTest1 = IndexSort(arrTest, True): EndTime4 = Timer - StrtTime
        UltimateTest = EndTime4
    ElseIf bytCase = 5 Then
        arrTest = myArray
        StrtTime = Timer: sortingTest2 = SortingUniqueTest(arrTest, False): EndTime5 = Timer - StrtTime
        UltimateTest = EndTime5
    ElseIf bytCase = 6 Then
        arrTest = myArray
        StrtTime = Timer: indexTest2 = IndexSort(arrTest, False): EndTime6 = Timer - StrtTime
        UltimateTest = EndTime6
    End If

End Function

And finally, here is the sub that produces the table above.

Sub GetBenchmarks()
    Dim myVar, i As Long, TestCases As Variant, j As Long, temp

    TestCases = Array(1000, 5000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000, 2000000, 5000000, 10000000)

    For j = 0 To 11
        If j < 6 Then
            myVar = UltimateTest(CLng(TestCases(j)), True, True, 1)
        ElseIf j < 10 Then
            myVar = UltimateTest(CLng(TestCases(j)), False, True, 1)
        ElseIf j < 11 Then
            myVar = Array("Not Tested", "Not Tested", 0.1, "Not Tested", 0.1, 0.1, 0.1, 0, 0, 0)
            temp = UltimateTest(CLng(TestCases(j)), False, False, 2)
            myVar(7) = temp(0): myVar(8) = temp(1)
            temp = UltimateTest(CLng(TestCases(j)), False, False, 3)
            myVar(2) = temp(0): myVar(9) = temp(1)
            myVar(4) = UltimateTest(CLng(TestCases(j)), False, False, 4)
            myVar(5) = UltimateTest(CLng(TestCases(j)), False, False, 5)
            myVar(6) = UltimateTest(CLng(TestCases(j)), False, False, 6)
        Else
            myVar = Array("Not Tested", "Not Tested", 0.1, "Not Tested", 0.1, 0.1, 0.1, "Not Tested", "Not Tested", 0)
            temp = UltimateTest(CLng(TestCases(j)), False, False, 3)
            myVar(2) = temp(0): myVar(9) = temp(1)
            myVar(4) = UltimateTest(CLng(TestCases(j)), False, False, 4)
            myVar(5) = UltimateTest(CLng(TestCases(j)), False, False, 5)
            myVar(6) = UltimateTest(CLng(TestCases(j)), False, False, 6)
        End If

        Cells(4 + j, 6) = TestCases(j)
        For i = 1 To 9: Cells(4 + j, 6 + i) = myVar(i - 1): Next i
        Cells(4 + j, 17) = myVar(9)
    Next j
End Sub

Summary
From the table of results, we can see that the Dictionary method works really well for cases less than about 500,000, however, after that, the IndexMethod really starts to dominate. You will notice that when order doesn't matter and your data is made up of positive integers, there is no comparison to the IndexMethod algorithm (it returns the unique values from an array containing 10 million elements in less than 1 sec!!! Incredible!). Below I have a breakdown of which algorithm is preferred in various cases.

Case 1
Your Data contains integers (i.e. whole numbers, both positive and negative): IndexMethod

Case 2
Your Data contains non-integers (i.e. variant, double, string, etc.) with less than 200000 elements: Dictionary Method

Case 3
Your Data contains non-integers (i.e. variant, double, string, etc.) with more than 200000 elements: Collection Method

If you had to choose one algorithm, in my opinion, the Collection method is still the best as it only requires a few lines of code, it's super general, and it's fast enough.

Simple way to query connected USB devices info in Python?

For a system with legacy usb coming back and libusb-1.0, this approach will work to retrieve the various actual strings. I show the vendor and product as examples. It can cause some I/O, because it actually reads the info from the device (at least the first time, anyway.) Some devices don't provide this information, so the presumption that they do will throw an exception in that case; that's ok, so we pass.

import usb.core
import usb.backend.libusb1

busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        if dev != None:
            try:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                stx = '%6d %6d: '+str(xdev._manufacturer).strip()+' = '+str(xdev._product).strip()
                print stx % (dev.idVendor,dev.idProduct)
            except:
                pass

Where IN clause in LINQ

This expression should do what you want to achieve.

dataSource.StateList.Where(s => countryCodes.Contains(s.CountryCode))

Call Jquery function

Try this code:

$(document).ready(function(){
    $('#YourControlID').click(function(){
        if() { //your condition
            $.messager.show({  
                title:'My Title',  
                msg:'The message content',  
                showType:'fade',  
                style:{  
                    right:'',  
                    bottom:''  
                }  
            });  
        }
    });
});

How can I print out all possible letter combinations a given phone number can represent?

I rewrote the latest answer to this (referred above) , from C to Java. I also included the support for 0 and 1 (as 0 and 1) because numbers such as 555-5055 weren't working at all with the above code.

Here it is. Some comments are preserved.

public static void printPhoneWords(int[] number) {
    char[] output = new char[number.length];
    printWordsUtil(number,0,output);
}

static String[] phoneKeys= new String[]{"0", "1", "ABC", "DEF", "GHI", "JKL",
               "MNO", "PQRS", "TUV", "WXYZ"};
private static void printWordsUtil(int[] number, int curDigIndex, char[] output) {
    // Base case, if current output word is done
    if (curDigIndex == output.length) {
        System.out.print(String.valueOf(output) + " "); 
        return;
    }

      // Try all 3-4 possible characters for the current digit in number[]
      // and recurse for the remaining digits

    char curPhoneKey[] = phoneKeys[number[curDigIndex]].toCharArray();
    for (int i = 0; i< curPhoneKey.length ; i++) {
        output[curDigIndex] = curPhoneKey[i];
        printWordsUtil(number, curDigIndex+1, output);
        if (number[curDigIndex] <= 1) // for 0 or 1
            return;
    }
}

public static void main(String[] args) {
    int number[] = {2, 3, 4};
    printPhoneWords(number);
    System.out.println();
}

PHP - remove <img> tag from string

$this->load->helper('security');
$h=mysql_real_escape_string(strip_image_tags($comment));

If user inputs

<img src="#">

In the database table just insert character this #

Works for me

MySQL - count total number of rows in php

Either use COUNT in your MySQL query or do a SELECT * FROM table and do:

$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";

How do I get the path of the Python script I am running in?

os.path.realpath(__file__) will give you the path of the current file, resolving any symlinks in the path. This works fine on my mac.

Can I install/update WordPress plugins without providing FTP access?

The only reason by which WordPress won't allow you to upload any plugin via WordPress admin dashboard when you don't got permission to write on the /wp-content directory. Remember that your wordpress directory /wp-content requires 0755 permission level. There are various ways to change a folder's permission level.

Changing file permissions using cPanel:

Go to File Manager at open the public HTML folder where your wordpress website is supposed to be, or open the site root directory if your website is in some other folder. In your WordPress root directory navigate towards wp-content folder; at the end of wp-content folder row the very last box carries file permissions for this folder. Make sure to edit the folder permission level to 0755, and you are done.

Changing file permissions using SSH terminal:

In your terminal locate the root of WordPress site which in my case was /var/www/html so to move into WordPress root directory enter the following command:

cd /var/www/html 

Now you are in WordPress root directory where the required folder /wp-content is located. So to change the file permissions type the following command:

sudo chmod wp-content 755 

This will change your /wp-content directory file permission to 0755.

Now you won't get error message of uploading wordpress plugins via FTP.

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

How can I add some small utility functions to my AngularJS application?

Here is a simple, compact and easy to understand method I use.
First, add a service in your js.

app.factory('Helpers', [ function() {
      // Helper service body

        var o = {
        Helpers: []

        };

        // Dummy function with parameter being passed
        o.getFooBar = function(para) {

            var valueIneed = para + " " + "World!";

            return valueIneed;

          };

        // Other helper functions can be added here ...

        // And we return the helper object ...
        return o;

    }]);

Then, in your controller, inject your helper object and use any available function with something like the following:

app.controller('MainCtrl', [

'$scope',
'Helpers',

function($scope, Helpers){

    $scope.sayIt = Helpers.getFooBar("Hello");
    console.log($scope.sayIt);

}]);

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

Make 2 functions run at the same time

I think what you are trying to convey can be achieved through multiprocessing. However if you want to do it through threads you can do this. This might help

from threading import Thread
import time

def func1():
    print 'Working'
    time.sleep(2)

def func2():
    print 'Working'
    time.sleep(2)

th = Thread(target=func1)
th.start()
th1=Thread(target=func2)
th1.start()

How to parse a CSV in a Bash script?

In a CSV file, each field is separated by a comma. The problem is, a field itself might have an embedded comma:

Name,Phone
"Woo, John",425-555-1212

You really need a library package that offer robust CSV support instead of relying on using comma as a field separator. I know that scripting languages such as Python has such support. However, I am comfortable with the Tcl scripting language so that is what I use. Here is a simple Tcl script which does what you are asking for:

#!/usr/bin/env tclsh

package require csv 
package require Tclx

# Parse the command line parameters
lassign $argv fileName columnNumber expectedValue

# Subtract 1 from columnNumber because Tcl's list index starts with a
# zero instead of a one
incr columnNumber -1

for_file line $fileName {
    set columns [csv::split $line]
    set columnValue [lindex $columns $columnNumber]
    if {$columnValue == $expectedValue} {
        puts $line
    }   
}

Save this script to a file called csv.tcl and invoke it as:

$ tclsh csv.tcl filename indexNumber expectedValue

Explanation

The script reads the CSV file line by line and store the line in the variable $line, then it split each line into a list of columns (variable $columns). Next, it picks out the specified column and assigned it to the $columnValue variable. If there is a match, print out the original line.

Moment Js UTC to Local Time

To convert UTC time to Local you have to use moment.local().

For more info see docs

Example:

var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');

console.log(date); // 2015-09-13 03:39:27

var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');

console.log(local); // 2015-09-13 09:39:27

Demo:

_x000D_
_x000D_
var date = moment.utc().format();_x000D_
console.log(date, "- now in UTC"); _x000D_
_x000D_
var local = moment.utc(date).local().format();_x000D_
console.log(local, "- UTC now to local"); 
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How to show grep result with complete path or file name

Use:

grep somethingtosearch *.log

and the filenames will be printed out along with the matches.