Programs & Examples On #Jbpm

jBPM is a light-weight business process suite written in Java. Use this tag for questions related to jBPM usage and workflows.

Lightweight workflow engine for Java

You can look @ Apache Ant to build a workflow engine.Its much more robust and is a pure state-machine with most of the requirements needed already built in.

Apart from that you can also embed different dynamic code/scripts in Java/Groovy/JS language and hence that makes it very powerful. Also it allows tasks extension.

There is some fair amount of tooling around it or you can build on top of it if a IDE is needed.

Update : Spring state machine is also available which is relatuvely light weight and not bloated : https://projects.spring.io/spring-statemachine/

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

try staring jboss with ./standalone.sh -c standalone-full.xml or any other alternative that allows you to start with the full profile

What is the best way to dump entire objects to a log in C#?

What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.

How do I get the current GPS location programmatically in Android?

class MyLocation {
    Timer timer1;
    LocationManager lm;
    LocationResult locationResult;
    boolean gps_enabled = false;
    boolean network_enabled = false;

    public boolean getLocation(Context context, LocationResult result) {
        // I use LocationResult callback class to pass location value from
        // MyLocation to user code.
        locationResult = result;
        if (lm == null)
            lm = (LocationManager) context
                    .getSystemService(Context.LOCATION_SERVICE);

        // Exceptions will be thrown if the provider is not permitted.
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        }
        catch (Exception ex) {
        }
        try {
            network_enabled = lm
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        }
        catch (Exception ex) {
        }

        // Don't start listeners if no provider is enabled.
        if (!gps_enabled && !network_enabled)
            return false;

        if (gps_enabled)
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                    locationListenerGps);
        if (network_enabled)
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
                    locationListenerNetwork);
        timer1 = new Timer();
        timer1.schedule(new GetLastLocation(), 5000);
        return true;
    }

    LocationListener locationListenerGps = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerNetwork);
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    LocationListener locationListenerNetwork = new LocationListener() {
        public void onLocationChanged(Location location) {
            timer1.cancel();
            locationResult.gotLocation(location);
            lm.removeUpdates(this);
            lm.removeUpdates(locationListenerGps);
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    };

    class GetLastLocation extends TimerTask {
        @Override
        public void run() {
            lm.removeUpdates(locationListenerGps);
            lm.removeUpdates(locationListenerNetwork);

            Location net_loc = null, gps_loc = null;
            if (gps_enabled)
                gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (network_enabled)
                net_loc = lm
                        .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            // If there are both values, use the latest one.
            if (gps_loc != null && net_loc != null) {
                if (gps_loc.getTime() > net_loc.getTime())
                    locationResult.gotLocation(gps_loc);
                else
                    locationResult.gotLocation(net_loc);
                return;
            }

            if (gps_loc != null) {
                locationResult.gotLocation(gps_loc);
                return;
            }
            if (net_loc != null) {
                locationResult.gotLocation(net_loc);
                return;
            }
            locationResult.gotLocation(null);
        }
    }

    public static abstract class LocationResult {
        public abstract void gotLocation(Location location);
    }
}

I hope this will help you...

How do I get the picture size with PIL?

Note that PIL will not apply the EXIF rotation information (at least up to v7.1.1; used in many jpgs). A quick fix to accomodate this:

def get_image_dims(file_path):
    from PIL import Image as pilim
    im = pilim.open(file_path)
    # returns (w,h) after rotation-correction
    return im.size if im._getexif().get(274,0) < 5 else im.size[::-1]

Deep copy an array in Angular 2 + TypeScript

Alternatively, you can use the GitHub project ts-deepcopy, which is also available on npm, to clone your object, or just include the code snippet below.

/**
 * Deep copy function for TypeScript.
 * @param T Generic type of target/copied value.
 * @param target Target value to be copied.
 * @see Source project, ts-deepcopy https://github.com/ykdr2017/ts-deepcopy
 * @see Code pen https://codepen.io/erikvullings/pen/ejyBYg
 */
export const deepCopy = <T>(target: T): T => {
  if (target === null) {
    return target;
  }
  if (target instanceof Date) {
    return new Date(target.getTime()) as any;
  }
  if (target instanceof Array) {
    const cp = [] as any[];
    (target as any[]).forEach((v) => { cp.push(v); });
    return cp.map((n: any) => deepCopy<any>(n)) as any;
  }
  if (typeof target === 'object' && target !== {}) {
    const cp = { ...(target as { [key: string]: any }) } as { [key: string]: any };
    Object.keys(cp).forEach(k => {
      cp[k] = deepCopy<any>(cp[k]);
    });
    return cp as T;
  }
  return target;
};

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren't really very thorough as to why your current code doesn't work.

Your code, for reference:

function funcName() {
    alert("test");
}

var func = funcName();
var run = setInterval("func",10000)

Let's break this up into chunks. Your function funcName is fine. Note that when you call funcName (in other words, you run it) you will be alerting "test". But notice that funcName() -- the parentheses mean to "call" or "run" the function -- doesn't actually return a value. When a function doesn't have a return value, it defaults to a value known as undefined.

When you call a function, you append its argument list to the end in parentheses. When you don't have any arguments to pass the function, you just add empty parentheses, like funcName(). But when you want to refer to the function itself, and not call it, you don't need the parentheses because the parentheses indicate to run it.

So, when you say:

var func = funcName();

You are actually declaring a variable func that has a value of funcName(). But notice the parentheses. funcName() is actually the return value of funcName. As I said above, since funcName doesn't actually return any value, it defaults to undefined. So, in other words, your variable func actually will have the value undefined.

Then you have this line:

var run = setInterval("func",10000)

The function setInterval takes two arguments. The first is the function to be ran every so often, and the second is the number of milliseconds between each time the function is ran.

However, the first argument really should be a function, not a string. If it is a string, then the JavaScript engine will use eval on that string instead. So, in other words, your setInterval is running the following JavaScript code:

func
// 10 seconds later....
func
// and so on

However, func is just a variable (with the value undefined, but that's sort of irrelevant). So every ten seconds, the JS engine evaluates the variable func and returns undefined. But this doesn't really do anything. I mean, it technically is being evaluated every 10 seconds, but you're not going to see any effects from that.

The solution is to give setInterval a function to run instead of a string. So, in this case:

var run = setInterval(funcName, 10000);

Notice that I didn't give it func. This is because func is not a function in your code; it's the value undefined, because you assigned it funcName(). Like I said above, funcName() will call the function funcName and return the return value of the function. Since funcName doesn't return anything, this defaults to undefined. I know I've said that several times now, but it really is a very important concept: when you see funcName(), you should think "the return value of funcName". When you want to refer to a function itself, like a separate entity, you should leave off the parentheses so you don't call it: funcName.

So, another solution for your code would be:

var func = funcName;
var run = setInterval(func, 10000);

However, that's a bit redundant: why use func instead of funcName?

Or you can stay as true as possible to the original code by modifying two bits:

var func = funcName;
var run = setInterval("func()", 10000);

In this case, the JS engine will evaluate func() every ten seconds. In other words, it will alert "test" every ten seconds. However, as the famous phrase goes, eval is evil, so you should try to avoid it whenever possible.

Another twist on this code is to use an anonymous function. In other words, a function that doesn't have a name -- you just drop it in the code because you don't care what it's called.

setInterval(function () {
    alert("test");
}, 10000);

In this case, since I don't care what the function is called, I just leave a generic, unnamed (anonymous) function there.

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

Fast check for NaN in NumPy

Even there exist an accepted answer, I'll like to demonstrate the following (with Python 2.7.2 and Numpy 1.6.0 on Vista):

In []: x= rand(1e5)
In []: %timeit isnan(x.min())
10000 loops, best of 3: 200 us per loop
In []: %timeit isnan(x.sum())
10000 loops, best of 3: 169 us per loop
In []: %timeit isnan(dot(x, x))
10000 loops, best of 3: 134 us per loop

In []: x[5e4]= NaN
In []: %timeit isnan(x.min())
100 loops, best of 3: 4.47 ms per loop
In []: %timeit isnan(x.sum())
100 loops, best of 3: 6.44 ms per loop
In []: %timeit isnan(dot(x, x))
10000 loops, best of 3: 138 us per loop

Thus, the really efficient way might be heavily dependent on the operating system. Anyway dot(.) based seems to be the most stable one.

The maximum value for an int type in Go

I originally used the code taken from the discussion thread that @nmichaels used in his answer. I now use a slightly different calculation. I've included some comments in case anyone else has the same query as @Arijoon

const (
    MinUint uint = 0                 // binary: all zeroes

    // Perform a bitwise NOT to change every bit from 0 to 1
    MaxUint      = ^MinUint          // binary: all ones

    // Shift the binary number to the right (i.e. divide by two)
    // to change the high bit to 0
    MaxInt       = int(MaxUint >> 1) // binary: all ones except high bit

    // Perform another bitwise NOT to change the high bit to 1 and
    // all other bits to 0
    MinInt       = ^MaxInt           // binary: all zeroes except high bit
)

The last two steps work because of how positive and negative numbers are represented in two's complement arithmetic. The Go language specification section on Numeric types refers the reader to the relevant Wikipedia article. I haven't read that, but I did learn about two's complement from the book Code by Charles Petzold, which is a very accessible intro to the fundamentals of computers and coding.

I put the code above (minus most of the comments) in to a little integer math package.

Register DLL file on Windows Server 2008 R2

That's the error you get when the DLL itself requires another COM server to be registered first or has a dependency on another DLL that's not available. The Regsvr32.exe tool does very little, it calls LoadLibrary() to load the DLL that's passed in the command line argument. Then GetProcAddress() to find the DllRegisterServer() entry point in the DLL. And calls it to leave it up to the COM server to register itself.

What that code does is fairly unguessable. The diagnostic you got is however pretty self-evident from the error code, for some reason this COM server needs another one to be registered first. The error message is crappy, it doesn't tell you what other server it needs. A sad side-effect of the way COM error handling works.

To troubleshoot this, use SysInternals' ProcMon tool. It shows you what registry keys Regsvr32.exe (actually: the COM server) is opening to find the server. Look for accesses to the CLSID key. That gives you a hint what {guid} it is looking for. That still doesn't quite tell you the server DLL, you should compare the trace with one you get from a machine that works. The InprocServer32 key has the DLL path.

How to upgrade Python version to 3.7?

Try this if you are on ubuntu:

sudo apt-get update
sudo apt-get install build-essential libpq-dev libssl-dev openssl libffi-dev zlib1g-dev
sudo apt-get install python3-pip python3.7-dev
sudo apt-get install python3.7

In case you don't have the repository and so it fires a not-found package you first have to install this:

sudo apt-get install -y software-properties-common
sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update

more info here: http://devopspy.com/python/install-python-3-6-ubuntu-lts/

Convert negative data into positive data in SQL Server

The best solution is: from positive to negative or from negative to positive

For negative:

SELECT ABS(a) * -1 AS AbsoluteA, ABS(b) * -1 AS AbsoluteB
FROM YourTable

For positive:

SELECT ABS(a) AS AbsoluteA, ABS(b)  AS AbsoluteB
FROM YourTable

How to start nginx via different port(other than 80)

Follow this: Open your config file

vi /etc/nginx/conf.d/default.conf

Change port number on which you are listening;

listen       81;
server_name  localhost;

Add a rule to iptables

 vi /etc/sysconfig/iptables 
-A INPUT -m state --state NEW -m tcp -p tcp --dport 81 -j ACCEPT

Restart IPtables

 service iptables restart;

Restart the nginx server

service nginx restart

Access yr nginx server files on port 81

Javascript window.open pass values using POST

I used a variation of the above but instead of printing html I built a form and submitted it to the 3rd party url:

    var mapForm = document.createElement("form");
    mapForm.target = "Map";
    mapForm.method = "POST"; // or "post" if appropriate
    mapForm.action = "http://www.url.com/map.php";

    var mapInput = document.createElement("input");
    mapInput.type = "text";
    mapInput.name = "addrs";
    mapInput.value = data;
    mapForm.appendChild(mapInput);

    document.body.appendChild(mapForm);

    map = window.open("", "Map", "status=0,title=0,height=600,width=800,scrollbars=1");

if (map) {
    mapForm.submit();
} else {
    alert('You must allow popups for this map to work.');
}

show/hide html table columns using css

No, that's pretty much it. In theory you could use visibility: collapse on some <col>?s to do it, but browser support isn't all there.

To improve what you've got slightly, you could use table-layout: fixed on the <table> to allow the browser to use the simpler, faster and more predictable fixed-table-layout algorithm. You could also drop the .show rules as when a cell isn't made display: none by a .hide rule it will automatically be display: table-cell. Allowing table display to revert to default rather than setting it explicitly avoids problems in IE<8, where the table display values are not supported.

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

How to hide close button in WPF window?

So, pretty much here is your problem. The close button on the upper right of a window frame is not part of the WPF window, but it belongs to the part of the window frame that is controled by your OS. This means you will have to use Win32 interop to do it.

alternativly, you can use the noframe and either provide your own "frame" or have no frame at all.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

This is a problem for users who live in a country that is banned by Google (like Iran). for this reason we need to remove these restrictions by a proxy. follow me :

file->settings->Appearance&Behavior->System Setting-> Http Proxy-> Manual proxy configuration ->HTTP -> Host name : fodev.org ->Port : 8118 .

and click Ok Button. then go to file-> Invalidate Caches/Restart . . . Use and enjoy the correct execution without error ;)

Difference between Role and GrantedAuthority in Spring Security

Another way to understand the relationship between these concepts is to interpret a ROLE as a container of Authorities.

Authorities are fine-grained permissions targeting a specific action coupled sometimes with specific data scope or context. For instance, Read, Write, Manage, can represent various levels of permissions to a given scope of information.

Also, authorities are enforced deep in the processing flow of a request while ROLE are filtered by request filter way before reaching the Controller. Best practices prescribe implementing the authorities enforcement past the Controller in the business layer.

On the other hand, ROLES are coarse grained representation of an set of permissions. A ROLE_READER would only have Read or View authority while a ROLE_EDITOR would have both Read and Write. Roles are mainly used for a first screening at the outskirt of the request processing such as http. ... .antMatcher(...).hasRole(ROLE_MANAGER)

The Authorities being enforced deep in the request's process flow allows a finer grained application of the permission. For instance, a user may have Read Write permission to first level a resource but only Read to a sub-resource. Having a ROLE_READER would restrain his right to edit the first level resource as he needs the Write permission to edit this resource but a @PreAuthorize interceptor could block his tentative to edit the sub-resource.

Jake

Multiple contexts with the same path error running web service in Eclipse using Tomcat

If you are using Tomcat 7 and Eclipse, click on the Tomcat server and then goto the modules tab. There you will find the duplicate entry. Remove both the entry and redeploy the application. You are good to go now.

How to create a List with a dynamic object type

Just use dynamic as the argument:

var list = new List<dynamic>();

How to get DateTime.Now() in YYYY-MM-DDThh:mm:ssTZD format using C#

use zzz instead of TZD

Example:

DateTime.Now.ToString("yyyy-MM-ddThh:mm:sszzz");

Response:

2011-08-09T11:50:00:02+02:00

git add, commit and push commands in one?

I like to run the following:

git commit -am "message";git push

Regex to split a CSV

,?\s*'.+?'|,?\s*".+?"|[^"']+?(?=,)|[^"']+  

This regex works with single and double quotes and also for one quote inside another!

Check if list contains element that contains a string and get that element

You should be able to use something like this, it has worked okay for me:

var valuesToMatch = yourList.Where(stringCheck => stringCheck.Contains(myString));

or something like this, if you need to look where it doesn't match.

 var valuesToMatch = yourList.Where(stringCheck => !stringCheck.Contains(myString));

Conditionally hide CommandField or ButtonField in Gridview

If this was based on roles you could use the multiview panel but not sure if you could do the same against a property of the record.

However, you could do this via code. In your rowdatabound event you can hide or show the button in it.

RuntimeError: module compiled against API version a but this version of numpy is 9

I ran into the same issue tonight. It turned out to be a problem where I had multiple numpy packages installed. An older version was installed in /usr/lib/python2.7 and the correct version was installed in /usr/local/lib/python2.7.

Additionally, I had PYTHONPATH=/usr/lib/python2.7/dist-packages:/usr/local/lib/python2.7/dist-packages. PYTHONPATH was finding the older version of numpy before the correct version, so when inside the Python interpreter, it would import the older version of numpy.

One thing which helped was opening a python session an executing the following code:

import numpy as np 
print np.__version__ 
print np.__path__

That should tell you exactly which version Python is using, and where it's installed.

To fix the issue, I changed PYTHONPATH=/usr/local/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages. And I also setup a virtual Python environment using the Hitchiker's Guide to Python, specifically the section titled "Lower level: virtualenv" . I know I should have setup a virtual environment in the first place, but I was tired and being lazy. Oh well, lesson learned!

(Update)

Just in case the docs are moved again, here are the relevant bits on...

Creating a Python Virtual Environment

Install virtualenv via pip:

$ install virtualenv

Test the installation:

$ virtualenv --version

Optionally, et the environment variable VIRTUALENVWRAPPER_PYTHON to change the default version of python used by virtual environments, for example to use Python 3:

$ export VIRTUALENVWRAPPER_PYTHON=$(which python3)

Optionally, set the environment variable WORKON_HOME to change the default directory your Python virtual environments are created in, for example to use /opt/python_envs:

$ export WORKON_HOME=/opt/python_envs

Create a virtual environment for a project:

$ cd my_project_folder
$ virtualenv my_virtual_env_name

Activate the virtual environment, you just created. Assuming you also set WORKON_HOME=/opt/python_envs:

$ source $WORKON_HOME/my_virtual_env_name/bin/activate

Install whatever Python packages your project requires, using either of the following two methods.

Method 1 - Install using pip from command line:

$ pip install python_package_name1
$ pip install python_package_name2

Method 2 - Install using a requests.txt file:

$ echo "python_package_name1" >> requests.txt
$ echo "python_package_name2" >> requests.txt
$ pip install -r ./requests.txt

Optionally, but highly recommended, install virtualenvwrapper. It contains useful commands to make working with virtual Python environments easier:

$ pip install virtualenvwrapper
$ source /usr/local/bin/virtualenvwrapper.sh

On Windows, install virtualenvwrapper using:

$ pip install virtualenvwrapper-win

Basic usage of virtualenvwrapper Create a new virtual environment:

$ mkvirtualenv my_virtual_env_name

List all virtual environments:

$ lsvirtualenv

Activate a virtual environment:

$ workon my_virtual_env_name

Delete a virtual environment (caution! this is irreversible!):

$ rmvirtualenv my_virtual_env_name

I hope this help!

Java: how do I check if a Date is within a certain range?

This was clearer to me,

// declare calendar outside the scope of isWithinRange() so that we initialize it only once
private Calendar calendar = Calendar.getInstance();

public boolean isWithinRange(Date date, Date startDate, Date endDate) {

    calendar.setTime(startDate);
    int startDayOfYear = calendar.get(Calendar.DAY_OF_YEAR); // first day is 1, last day is 365
    int startYear = calendar.get(Calendar.YEAR);

    calendar.setTime(endDate);
    int endDayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
    int endYear = calendar.get(Calendar.YEAR);

    calendar.setTime(date);
    int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
    int year = calendar.get(Calendar.YEAR);

    return (year > startYear && year < endYear) // year is within the range
            || (year == startYear && dayOfYear >= startDayOfYear) // year is same as start year, check day as well
            || (year == endYear && dayOfYear < endDayOfYear); // year is same as end year, check day as well

}

How to enable named/bind/DNS full logging?

I usually expand each log out into it's own channel and then to a separate log file, certainly makes things easier when you are trying to debug specific issues. So my logging section looks like the following:

logging {
    channel default_file {
        file "/var/log/named/default.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel general_file {
        file "/var/log/named/general.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel database_file {
        file "/var/log/named/database.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel security_file {
        file "/var/log/named/security.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel config_file {
        file "/var/log/named/config.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel resolver_file {
        file "/var/log/named/resolver.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-in_file {
        file "/var/log/named/xfer-in.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel xfer-out_file {
        file "/var/log/named/xfer-out.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel notify_file {
        file "/var/log/named/notify.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel client_file {
        file "/var/log/named/client.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel unmatched_file {
        file "/var/log/named/unmatched.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel queries_file {
        file "/var/log/named/queries.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel network_file {
        file "/var/log/named/network.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel update_file {
        file "/var/log/named/update.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dispatch_file {
        file "/var/log/named/dispatch.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel dnssec_file {
        file "/var/log/named/dnssec.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };
    channel lame-servers_file {
        file "/var/log/named/lame-servers.log" versions 3 size 5m;
        severity dynamic;
        print-time yes;
    };

    category default { default_file; };
    category general { general_file; };
    category database { database_file; };
    category security { security_file; };
    category config { config_file; };
    category resolver { resolver_file; };
    category xfer-in { xfer-in_file; };
    category xfer-out { xfer-out_file; };
    category notify { notify_file; };
    category client { client_file; };
    category unmatched { unmatched_file; };
    category queries { queries_file; };
    category network { network_file; };
    category update { update_file; };
    category dispatch { dispatch_file; };
    category dnssec { dnssec_file; };
    category lame-servers { lame-servers_file; };
};

Hope this helps.

ECMAScript 6 class destructor

I just came across this question in a search about destructors and I thought there was an unanswered part of your question in your comments, so I thought I would address that.

thank you guys. But what would be a good convention if ECMAScript doesn't have destructors? Should I create a method called destructor and call it manually when I'm done with the object? Any other idea?

If you want to tell your object that you are now done with it and it should specifically release any event listeners it has, then you can just create an ordinary method for doing that. You can call the method something like release() or deregister() or unhook() or anything of that ilk. The idea is that you're telling the object to disconnect itself from anything else it is hooked up to (deregister event listeners, clear external object references, etc...). You will have to call it manually at the appropriate time.

If, at the same time you also make sure there are no other references to that object, then your object will become eligible for garbage collection at that point.

ES6 does have weakMap and weakSet which are ways of keeping track of a set of objects that are still alive without affecting when they can be garbage collected, but it does not provide any sort of notification when they are garbage collected. They just disappear from the weakMap or weakSet at some point (when they are GCed).


FYI, the issue with this type of destructor you ask for (and probably why there isn't much of a call for it) is that because of garbage collection, an item is not eligible for garbage collection when it has an open event handler against a live object so even if there was such a destructor, it would never get called in your circumstance until you actually removed the event listeners. And, once you've removed the event listeners, there's no need for the destructor for this purpose.

I suppose there's a possible weakListener() that would not prevent garbage collection, but such a thing does not exist either.


FYI, here's another relevant question Why is the object destructor paradigm in garbage collected languages pervasively absent?. This discussion covers finalizer, destructor and disposer design patterns. I found it useful to see the distinction between the three.


Edit in 2020 - proposal for object finalizer

There is a Stage 3 EMCAScript proposal to add a user-defined finalizer function after an object is garbage collected.

A canonical example of something that would benefit from a feature like this is an object that contains a handle to an open file. If the object is garbage collected (because no other code still has a reference to it), then this finalizer scheme allows one to at least put a message to the console that an external resource has just been leaked and code elsewhere should be fixed to prevent this leak.

If you read the proposal thoroughly, you will see that it's nothing like a full-blown destructor in a language like C++. This finalizer is called after the object has already been destroyed and you have to predetermine what part of the instance data needs to be passed to the finalizer for it to do its work. Further, this feature is not meant to be relied upon for normal operation, but rather as a debugging aid and as a backstop against certain types of bugs. You can read the full explanation for these limitations in the proposal.

Converting String array to java.util.List

As of Java 8 and Stream API you can use Arrays.stream and Collectors.toList:

String[] array = new String[]{"a", "b", "c"};
List<String> list = Arrays.stream(array).collect(Collectors.toList());

This is practical especially if you intend to perform further operations on the list.

String[] array = new String[]{"a", "bb", "ccc"};
List<String> list = Arrays.stream(array)
                          .filter(str -> str.length() > 1)
                          .map(str -> str + "!")
                          .collect(Collectors.toList());

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens at server end and not visible to client, but in case of sendRedirect(), redirection happens at client end and it's visible to client.

enter image description here

How can I get the executing assembly version?

using System.Reflection;
{
    string version = Assembly.GetEntryAssembly().GetName().Version.ToString();
}

Remarks from MSDN http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly%28v=vs.110%29.aspx:

The GetEntryAssembly method can return null when a managed assembly has been loaded from an unmanaged application. For example, if an unmanaged application creates an instance of a COM component written in C#, a call to the GetEntryAssembly method from the C# component returns null, because the entry point for the process was unmanaged code rather than a managed assembly.

MySQL Select all columns from one table and some from another table

select a.* , b.Aa , b.Ab, b.Ac from table1 a left join table2 b on a.id=b.id

this should select all columns from table 1 and only the listed columns from table 2 joined by id.

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

Fastest way to Remove Duplicate Value from a list<> by lambda

If you want to stick with the original List instead of creating a new one, you can something similar to what the Distinct() extension method does internally, i.e. use a HashSet to check for uniqueness:

HashSet<long> set = new HashSet<long>(longs.Count);
longs.RemoveAll(x => !set.Add(x));

The List class provides this convenient RemoveAll(predicate) method that drops all elements not satisfying the condition specified by the predicate. The predicate is a delegate taking a parameter of the list's element type and returning a bool value. The HashSet's Add() method returns true only if the set doesn't contain the item yet. Thus by removing any items from the list that can't be added to the set you effectively remove all duplicates.

Javascript to convert UTC to local time

To format your date try the following function:

var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");

But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).

Chris

Retrieve version from maven pom.xml in code

The accepted answer may be the best and most stable way to get a version number into an application statically, but does not actually answer the original question: How to retrieve the artifact's version number from pom.xml? Thus, I want to offer an alternative showing how to do it dynamically during runtime:

You can use Maven itself. To be more exact, you can use a Maven library.

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-model</artifactId>
  <version>3.3.9</version>
</dependency>

And then do something like this in Java:

package de.scrum_master.app;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.FileReader;
import java.io.IOException;

public class Application {
    public static void main(String[] args) throws IOException, XmlPullParserException {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        Model model = reader.read(new FileReader("pom.xml"));
        System.out.println(model.getId());
        System.out.println(model.getGroupId());
        System.out.println(model.getArtifactId());
        System.out.println(model.getVersion());
    }
}

The console log is as follows:

de.scrum-master.stackoverflow:my-artifact:jar:1.0-SNAPSHOT
de.scrum-master.stackoverflow
my-artifact
1.0-SNAPSHOT

Update 2017-10-31: In order to answer Simon Sobisch's follow-up question I modified the example like this:

package de.scrum_master.app;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Application {
  public static void main(String[] args) throws IOException, XmlPullParserException {
    MavenXpp3Reader reader = new MavenXpp3Reader();
    Model model;
    if ((new File("pom.xml")).exists())
      model = reader.read(new FileReader("pom.xml"));
    else
      model = reader.read(
        new InputStreamReader(
          Application.class.getResourceAsStream(
            "/META-INF/maven/de.scrum-master.stackoverflow/aspectj-introduce-method/pom.xml"
          )
        )
      );
    System.out.println(model.getId());
    System.out.println(model.getGroupId());
    System.out.println(model.getArtifactId());
    System.out.println(model.getVersion());
  }
}

How do you see the entire command history in interactive Python?

Rehash of Doogle's answer that doesn't printline numbers, but does allow specifying the number of lines to print.

def history(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(readline.get_history_item(r))
    else:
        for r in range(1, -lastn + 1):
            print(readline.get_history_item(r))

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I solved just by: given correct host and port so:

  1. Open oracle net manager
  2. Local
  3. Listener

in Listener on address 2 then copy host to Oracle Developer

finally connect to oracle

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I also faced the same issue you just need to add the library , Junit Library is already provided along with Eclipse so you just need to follow below

Build Path > Configure Build Path > library > Add library > JUnit > Next > finish

It works for me

Responsive bootstrap 3 timepicker?

Above of all, I found this library right here. Works out of the box perfectly on a Bootstrap-3 environment.

Bootstrap-3 Clock-Picker

CSS

<link rel="stylesheet" type="text/css" href="dist/bootstrap-clockpicker.min.css">

HTML

<div class="input-group clockpicker">
    <input type="text" class="form-control" value="09:30">
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-time"></span>
    </span>
</div>

JAVASCRIPT

<script type="text/javascript" src="dist/bootstrap-clockpicker.min.js"></script>
<script type="text/javascript">
    $('.clockpicker').clockpicker();
</script>

As simple as that! Find more examples on the link above.

Update 18/04/2018

If you are using Bootstrap-4, the most popular time/date picker library available right now is Tempus Dominus. It is not fancy looking, but much responsive and modern.

Bootstrap-4 Tempus Dominus

Getting first and last day of the current month

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

Format a JavaScript string using placeholders and an object of substitutions?

You can use JQuery(jquery.validate.js) to make it work easily.

$.validator.format("My name is {0}, I'm {1} years old",["Bob","23"]);

Or if you want to use just that feature you can define that function and just use it like

function format(source, params) {
    $.each(params,function (i, n) {
        source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
    })
    return source;
}
alert(format("{0} is a {1}", ["Michael", "Guy"]));

credit to jquery.validate.js team

Why Anaconda does not recognize conda command?

Try restarting the terminal, I had the same issue, worked after restarting the terminal.

Object spread vs. Object.assign

NOTE: Spread is NOT just syntactic sugar around Object.assign. They operate much differently behind the scenes.

Object.assign applies setters to a new object, Spread does not. In addition, the object must be iterable.

Copy Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object.

Use it for creating a shallow copy of the object good practice to always set immutable properties to copy - because mutable versions can be passed into immutable properties, copy will ensure that you'll always be dealing with an immutable object

Assign Assign is somewhat the opposite to copy. Assign will generate a setter which assigns the value to the instance variable directly, rather than copying or retaining it. When calling the getter of an assign property, it returns a reference to the actual data.

How do I remove newlines from a text file?

Use sed with POSIX classes

This will remove all lines containing only whitespace (spaces & tabs)

sed '/^[[:space:]]*$/d'

Just take whatever you are working with and pipe it to that

Example

cat filename | sed '/^[[:space:]]*$/d'

HTML form submit to PHP script

For your actual form, if you were to just post the results to your same page, it should probably work out all right. Try something like:

<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="POST>

What is your most productive shortcut with Vim?

You are talking about text selecting and copying, I think that you should give a look to the Vim Visual Mode.

In the visual mode, you are able to select text using Vim commands, then you can do whatever you want with the selection.

Consider the following common scenarios:

You need to select to the next matching parenthesis.

You could do:

  • v% if the cursor is on the starting/ending parenthesis
  • vib if the cursor is inside the parenthesis block

You want to select text between quotes:

  • vi" for double quotes
  • vi' for single quotes

You want to select a curly brace block (very common on C-style languages):

  • viB
  • vi{

You want to select the entire file:

  • ggVG

Visual block selection is another really useful feature, it allows you to select a rectangular area of text, you just have to press Ctrl-V to start it, and then select the text block you want and perform any type of operation such as yank, delete, paste, edit, etc. It's great to edit column oriented text.

How to override application.properties during production in Spring-Boot?

You can also use @PropertySources

@PropertySources({
        @PropertySource(value = "classpath:application.properties"),
        @PropertySource(value = "file:/user/home/external.properties", ignoreResourceNotFound = true)
})
public class Application {
    public static void main(String[] args) throws Exception {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);

    }


}

Fastest JavaScript summation

Improvements


Your looping structure could be made faster:


   var count = 0;
   for(var i=0, n=array.length; i < n; i++) 
   { 
      count += array[i]; 
   }

This retrieves array.length once, rather than with each iteration. The optimization is made by caching the value.


If you really want to speed it up:


   var count=0;
   for (var i=array.length; i--;) {
     count+=array[i];
   }

This is equivalent to a while reverse loop. It caches the value and is compared to 0, thus faster iteration.

For a more complete comparison list, see my JSFiddle.
Note: array.reduce is horrible there, but in Firebug Console it is fastest.


Compare Structures

I started a JSPerf for array summations. It was quickly constructed and not guaranteed to be complete or accurate, but that's what edit is for :)

How do I expand the output display to see more columns of a pandas DataFrame?

Only using these 3 lines worked for me:

pd.set_option('display.max_columns', None)  
pd.set_option('display.expand_frame_repr', False)
pd.set_option('max_colwidth', -1)

Anaconda / Python 3.6.5 / pandas: 0.23.0 / Visual Studio Code 1.26

Limit text length to n lines using CSS

following CSS class helped me in getting two line ellipsis.

  .two-line-ellipsis {
        padding-left:2vw;
        text-overflow: ellipsis;
        overflow: hidden;
        width: 325px;
        line-height: 25px;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        padding-top: 15px;
    }

Show MySQL host via SQL Command

To get current host name :-

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

To get hosts for all incoming requests :-

select host from information_schema.processlist;

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

However, mysql document mention this :-

resolveip google.com.sg

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

How Do I Insert a Byte[] Into an SQL Server VARBINARY Column

No problem if all the arrays you are about to use in this scenario are small like in your example.

If you will use this for large blobs (e.g. storing large binary files many Mbs or even Gbs in size into a VARBINARY) then you'd probably be much better off using specific support in SQL Server for reading/writing subsections of such large blobs. Things like READTEXT and UPDATETEXT, or in current versions of SQL Server SUBSTRING.

For more information and examples see either my 2006 article in .NET Magazine ("BLOB + Stream = BlobStream", in Dutch, with complete source code), or an English translation and generalization of this on CodeProject by Peter de Jonghe. Both of these are linked from my weblog.

Virtualhost For Wildcard Subdomain and Static Subdomain

This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.

<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com

SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"

VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"

DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

Babel 6 regeneratorRuntime is not defined

My simple solution:

npm install --save-dev babel-plugin-transform-runtime
npm install --save-dev babel-plugin-transform-async-to-generator

.babelrc

{
  "presets": [
    ["latest", {
      "es2015": {
        "loose": true
      }
    }],
    "react",
    "stage-0"
  ],
  "plugins": [
    "transform-runtime",
    "transform-async-to-generator"
  ]
}

Send Post Request with params using Retrofit

This is a simple solution where we do not need to use JSON

public interface RegisterAPI {
@FormUrlEncoded
@POST("/RetrofitExample/insert.php")
public void insertUser(
        @Field("name") String name,
        @Field("username") String username,
        @Field("password") String password,
        @Field("email") String email,
        Callback<Response> callback);
}

method to send data

private void insertUser(){
    //Here we will handle the http request to insert user to mysql db
    //Creating a RestAdapter
    RestAdapter adapter = new RestAdapter.Builder()
            .setEndpoint(ROOT_URL) //Setting the Root URL
            .build(); //Finally building the adapter

    //Creating object for our interface
    RegisterAPI api = adapter.create(RegisterAPI.class);

    //Defining the method insertuser of our interface
    api.insertUser(

            //Passing the values by getting it from editTexts
            editTextName.getText().toString(),
            editTextUsername.getText().toString(),
            editTextPassword.getText().toString(),
            editTextEmail.getText().toString(),

            //Creating an anonymous callback
            new Callback<Response>() {
                @Override
                public void success(Response result, Response response) {
                    //On success we will read the server's output using bufferedreader
                    //Creating a bufferedreader object
                    BufferedReader reader = null;

                    //An string to store output from the server
                    String output = "";

                    try {
                        //Initializing buffered reader
                        reader = new BufferedReader(new InputStreamReader(result.getBody().in()));

                        //Reading the output in the string
                        output = reader.readLine();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    //Displaying the output as a toast
                    Toast.makeText(MainActivity.this, output, Toast.LENGTH_LONG).show();
                }

                @Override
                public void failure(RetrofitError error) {
                    //If any error occured displaying the error as toast
                    Toast.makeText(MainActivity.this, error.toString(),Toast.LENGTH_LONG).show();
                }
            }
    );
}

Now we can get the post request using php aur any other server side scripting.

Source Android Retrofit Tutorial

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

If the cookie is generated from script, then you can send the cookie manually along with the cookie from the file(using cookie-file option). For example:

# sending manually set cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Cookie: test=cookie"));

# sending cookies from file
curl_setopt($ch, CURLOPT_COOKIEFILE, $ckfile);

In this case curl will send your defined cookie along with the cookies from the file.

If the cookie is generated through javascrript, then you have to trace it out how its generated and then you can send it using the above method(through http-header).

The utma utmc, utmz are seen when cookies are sent from Mozilla. You shouldn't bet worry about these things anymore.

Finally, the way you are doing is alright. Just make sure you are using absolute path for the file names(i.e. /var/dir/cookie.txt) instead of relative one.

Always enable the verbose mode when working with curl. It will help you a lot on tracing the requests. Also it will save lot of your times.

curl_setopt($ch, CURLOPT_VERBOSE, true);

Soft keyboard open and close listener in an activity in Android

This is not working as desired...

... have seen many use size calculations to check ...

I wanted to determine if it was open or not and I found isAcceptingText()

so this really does not answer the question as it does not address opening or closing rather more like is open or closed so it is related code that may help others in various scenarios...

in an activity

    if (((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).isAcceptingText()) {
        Log.d(TAG,"Software Keyboard was shown");
    } else {
        Log.d(TAG,"Software Keyboard was not shown");
    }

in a fragment

    if (((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).isAcceptingText()) {
        Log.d(TAG,"Software Keyboard was shown");
    } else {
        Log.d(TAG,"Software Keyboard was not shown");

    }

Abort trap 6 error in C

You are writing to memory you do not own:

int board[2][50]; //make an array with 3 columns  (wrong)
                  //(actually makes an array with only two 'columns')
...
for (i=0; i<num3+1; i++)
    board[2][i] = 'O';
          ^

Change this line:

int board[2][50]; //array with 2 columns (legal indices [0-1][0-49])
          ^

To:

int board[3][50]; //array with 3 columns (legal indices [0-2][0-49])
          ^

When creating an array, the value used to initialize: [3] indicates array size.
However, when accessing existing array elements, index values are zero based.

For an array created: int board[3][50];
Legal indices are board[0][0]...board[2][49]

EDIT To address bad output comment and initialization comment

add an additional "\n" for formatting output:

Change:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
 }

       ...

To:

  ...
  for (k=0; k<50;k++) {
     printf("%d",board[j][k]);
  }
  printf("\n");//at the end of every row, print a new line
}
...  

Initialize board variable:

int board[3][50] = {0};//initialize all elements to zero

( array initialization discussion... )

Write objects into file with Node.js

obj is an array in your example.

fs.writeFileSync(filename, data, [options]) requires either String or Buffer in the data parameter. see docs.

Try to write the array in a string format:

// writes 'https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks'
fs.writeFileSync('./data.json', obj.join(',') , 'utf-8'); 

Or:

// writes ['https://twitter.com/#!/101Cookbooks', 'http://www.facebook.com/101cookbooks']
var util = require('util');
fs.writeFileSync('./data.json', util.inspect(obj) , 'utf-8');

edit: The reason you see the array in your example is because node's implementation of console.log doesn't just call toString, it calls util.format see console.js source

What is the "right" JSON date format?

JSON does not know anything about dates. What .NET does is a non-standard hack/extension.

I would use a format that can be easily converted to a Date object in JavaScript, i.e. one that can be passed to new Date(...). The easiest and probably most portable format is the timestamp containing milliseconds since 1970.

Convert Unix timestamp to a date string

As @TomMcKenzie says in a comment to another answer, date -r 123456789 is arguably a more common (i.e. more widely implemented) simple solution for times given as seconds since the Unix Epoch, but unfortunately there's no universal guaranteed portable solution.

The -d option on many types of systems means something entirely different than GNU Date's --date extension. Sadly GNU Date doesn't interpret -r the same as these other implementations. So unfortunately you have to know which version of date you're using, and many older Unix date commands don't support either option.

Even worse, POSIX date recognizes neither -d nor -r and provides no standard way in any command at all (that I know of) to format a Unix time from the command line (since POSIX Awk also lacks strftime()). (You can't use touch -t and ls because the former does not accept a time given as seconds since the Unix Epoch.)

Note though The One True Awk available direct from Brian Kernighan does now have the strftime() function built-in as well as a systime() function to return the current time in seconds since the Unix Epoch), so perhaps the Awk solution is the most portable.

Open a URL without using a browser from a batch file

Not sure whether you have already gotten your owner solution. I have been using the following powshell command to achieve it:

powershell.exe -noprofile -command "Invoke-WebRequest -Uri http://your_url"

How to get the current time in milliseconds from C in Linux?

Use gettimeofday() to get the time in seconds and microseconds. Combining and rounding to milliseconds is left as an exercise.

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

No. two elements with the same id are not valid. IDs are unique, if you wish to do something like that, use a class. Don't forget that elements can have multiple classes by using a space as a delimeter:

<div class="myclass sexy"></div>

Fully backup a git repo?

git bundle

I like that method, as it results in only one file, easier to copy around.
See ProGit: little bundle of joy.
See also "How can I email someone a git repository?", where the command

git bundle create /tmp/foo-all --all

is detailed:

git bundle will only package references that are shown by git show-ref: this includes heads, tags, and remote heads.
It is very important that the basis used be held by the destination.
It is okay to err on the side of caution, causing the bundle file to contain objects already in the destination, as these are ignored when unpacking at the destination.


For using that bundle, you can clone it, specifying a non-existent folder (outside of any git repo):

git clone /tmp/foo-all newFolder

NoClassDefFoundError - Eclipse and Android

I have encountered the same issue. The reason was that the library that I was trying to use had been compiled with a standard JDK 7.

I recompiled it with the -source 1.6 -target 1.6 options and it worked fine.

Default interface methods are only supported starting with Android N

You should use Java 8 to solve this, based on the Android documentation you can do this by

clicking File > Project Structure

and change Source Compatibility and Target Compatibility.

enter image description here

and you can also configure it directly in the app-level build.gradle file:

android {
  ...
  // Configure only for each module that uses Java 8
  // language features (either in its source code or
  // through dependencies).
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Error Code: 1005. Can't create table '...' (errno: 150)

I had a similar error. The problem had to do with the child and parent table not having the same charset and collation. This can be fixed by appending ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

CREATE TABLE IF NOT EXISTS `country` (`id` INT(11) NOT NULL AUTO_INCREMENT,...) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8;

... on the SQL statement means that there is some missing code.

A better way to check if a path exists or not in PowerShell

The alias solution you posted is clever, but I would argue against its use in scripts, for the same reason I don't like using any aliases in scripts; it tends to harm readability.

If this is something you want to add to your profile so you can type out quick commands or use it as a shell, then I could see that making sense.

You might consider piping instead:

if ($path | Test-Path) { ... }
if (-not ($path | Test-Path)) { ... }
if (!($path | Test-Path)) { ... }

Alternatively, for the negative approach, if appropriate for your code, you can make it a positive check then use else for the negative:

if (Test-Path $path) {
    throw "File already exists."
} else {
   # The thing you really wanted to do.
}

jQuery: Change button text on click

its work short code

$('.SeeMore2').click(function(){ var $this = $(this).toggleClass('SeeMore2'); if($(this).hasClass('SeeMore2')) { $(this).text('See More');
} else { $(this).text('See Less'); } });

Malformed String ValueError ast.literal_eval() with String representation of Tuple

Use eval() instead of ast.literal_eval() if the input is trusted (which it is in your case).

raw_data = userfile.read().split('\n')
for a in raw_data : 
    print a
    btc_history.append(eval(a))

This works for me in Python 3.6.0

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

How to enable curl in Wamp server

The steps are as follows :

  1. Close WAMP (if running)
  2. Navigate to WAMP\bin\php\(your version of php)\
  3. Edit php.ini
  4. Search for curl, uncomment extension=php_curl.dll
  5. Navigate to WAMP\bin\Apache\(your version of apache)\bin\
  6. Edit php.ini
  7. Search for curl, uncomment extension=php_curl.dll
  8. Save both
  9. Restart WAMP

jQuery: count number of rows in a table

I got the following:

jQuery('#tableId').find('tr').index();

How do I (or can I) SELECT DISTINCT on multiple columns?

If you put together the answers so far, clean up and improve, you would arrive at this superior query:

UPDATE sales
SET    status = 'ACTIVE'
WHERE  (saleprice, saledate) IN (
    SELECT saleprice, saledate
    FROM   sales
    GROUP  BY saleprice, saledate
    HAVING count(*) = 1 
    );

Which is much faster than either of them. Nukes the performance of the currently accepted answer by factor 10 - 15 (in my tests on PostgreSQL 8.4 and 9.1).

But this is still far from optimal. Use a NOT EXISTS (anti-)semi-join for even better performance. EXISTS is standard SQL, has been around forever (at least since PostgreSQL 7.2, long before this question was asked) and fits the presented requirements perfectly:

UPDATE sales s
SET    status = 'ACTIVE'
WHERE  NOT EXISTS (
   SELECT FROM sales s1                     -- SELECT list can be empty for EXISTS
   WHERE  s.saleprice = s1.saleprice
   AND    s.saledate  = s1.saledate
   AND    s.id <> s1.id                     -- except for row itself
   )
AND    s.status IS DISTINCT FROM 'ACTIVE';  -- avoid empty updates. see below

db<>fiddle here
Old SQL Fiddle

Unique key to identify row

If you don't have a primary or unique key for the table (id in the example), you can substitute with the system column ctid for the purpose of this query (but not for some other purposes):

   AND    s1.ctid <> s.ctid

Every table should have a primary key. Add one if you didn't have one, yet. I suggest a serial or an IDENTITY column in Postgres 10+.

Related:

How is this faster?

The subquery in the EXISTS anti-semi-join can stop evaluating as soon as the first dupe is found (no point in looking further). For a base table with few duplicates this is only mildly more efficient. With lots of duplicates this becomes way more efficient.

Exclude empty updates

For rows that already have status = 'ACTIVE' this update would not change anything, but still insert a new row version at full cost (minor exceptions apply). Normally, you do not want this. Add another WHERE condition like demonstrated above to avoid this and make it even faster:

If status is defined NOT NULL, you can simplify to:

AND status <> 'ACTIVE';

The data type of the column must support the <> operator. Some types like json don't. See:

Subtle difference in NULL handling

This query (unlike the currently accepted answer by Joel) does not treat NULL values as equal. The following two rows for (saleprice, saledate) would qualify as "distinct" (though looking identical to the human eye):

(123, NULL)
(123, NULL)

Also passes in a unique index and almost anywhere else, since NULL values do not compare equal according to the SQL standard. See:

OTOH, GROUP BY, DISTINCT or DISTINCT ON () treat NULL values as equal. Use an appropriate query style depending on what you want to achieve. You can still use this faster query with IS NOT DISTINCT FROM instead of = for any or all comparisons to make NULL compare equal. More:

If all columns being compared are defined NOT NULL, there is no room for disagreement.

Checking length of dictionary object

Count and show keys in a dictionary (run in console):

o=[];count=0; for (i in topicNames) { ++count; o.push(count+": "+ i) } o.join("\n")

Sample output:

"1: Phase-out Left-hand
2: Define All Top Level Taxonomies But Processes
3: 987
4: 16:00
5: Identify suppliers"

Simple count function:

function size_dict(d){c=0; for (i in d) ++c; return c}

$('body').on('click', '.anything', function(){})

If you want to capture click on everything then do

$("*").click(function(){
//code here
}

I use this for selector: http://api.jquery.com/all-selector/

This is used for handling clicks: http://api.jquery.com/click/

And then use http://api.jquery.com/event.preventDefault/

To stop normal clicking actions.

How to customize a Spinner in Android

The most elegant and flexible solution I have found so far is here: http://android-er.blogspot.sg/2010/12/custom-arrayadapter-for-spinner-with.html

Basically, follow these steps:

  1. Create custom layout xml file for your dropdown item, let's say I will call it spinner_item.xml
  2. Create custom view class, for your dropdown Adapter. In this custom class, you need to overwrite and set your custom dropdown item layout in getView() and getDropdownView() method. My code is as below:

    public class CustomArrayAdapter extends ArrayAdapter<String>{
    
    private List<String> objects;
    private Context context;
    
    public CustomArrayAdapter(Context context, int resourceId,
         List<String> objects) {
         super(context, resourceId, objects);
         this.objects = objects;
         this.context = context;
    }
    
    @Override
    public View getDropDownView(int position, View convertView,
        ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      return getCustomView(position, convertView, parent);
    }
    
    public View getCustomView(int position, View convertView, ViewGroup parent) {
    
    LayoutInflater inflater=(LayoutInflater) context.getSystemService(  Context.LAYOUT_INFLATER_SERVICE );
    View row=inflater.inflate(R.layout.spinner_item, parent, false);
    TextView label=(TextView)row.findViewById(R.id.spItem);
     label.setText(objects.get(position));
    
    if (position == 0) {//Special style for dropdown header
          label.setTextColor(context.getResources().getColor(R.color.text_hint_color));
    }
    
    return row;
    }
    
    }
    
  3. In your activity or fragment, make use of the custom adapter for your spinner view. Something like this:

    Spinner sp = (Spinner)findViewById(R.id.spMySpinner);
    ArrayAdapter<String> myAdapter = new CustomArrayAdapter(this, R.layout.spinner_item, options);
    sp.setAdapter(myAdapter);
    

where options is the list of dropdown item string.

Dynamically updating css in Angular 2

The accepted answer is not incorrect.

For grouped styles one can also use the ngStyle directive.

<some-element [ngStyle]="{'font-style': styleExpression, 'font-weight': 12}">...</some-element>

The official docs are here

equivalent to push() or pop() for arrays?

For those who don't have time to refactor the code to replace arrays with Collections (for example ArrayList), there is an alternative. Unlike Collections, the length of an array cannot be changed, but the array can be replaced, like this:

array = push(array, item);

The drawbacks are that

  • the whole array has to be copied each time you push, and
  • the original array Object is not changed, so you have to update the variable(s) as appropriate.

Here is the push method for String:
(You can create multiple push methods, one for String, one for int, etc)

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    for (int i = 0; i < array.length; i++)
        longer[i] = array[i];
    longer[array.length] = push;
    return longer;
}

This alternative is more efficient, shorter & harder to read:

private static String[] push(String[] array, String push) {
    String[] longer = new String[array.length + 1];
    System.arraycopy(array, 0, longer, 0, array.length);
    longer[array.length] = push;
    return longer;
}

Converting a POSTMAN request to Curl

Starting from Postman 8 you need to visit here

enter image description here

Redirecting to a certain route based on condition

If you do not want to use angular-ui-router, but would like to have your controllers lazy loaded via RequireJS, there are couple of problems with event $routeChangeStart when using your controllers as RequireJS modules (lazy loaded).

You cannot be sure the controller will be loaded before $routeChangeStart gets triggered -- in fact it wont be loaded. That means you cannot access properties of next route like locals or $$route because they are not yet setup.
Example:

app.config(["$routeProvider", function($routeProvider) {
    $routeProvider.when("/foo", {
        controller: "Foo",
        resolve: {
            controller: ["$q", function($q) {
                var deferred = $q.defer();
                require(["path/to/controller/Foo"], function(Foo) {
                    // now controller is loaded
                    deferred.resolve();
                });
                return deferred.promise;
            }]
        }
    });
}]);

app.run(["$rootScope", function($rootScope) {
    $rootScope.$on("$routeChangeStart", function(event, next, current) {
        console.log(next.$$route, next.locals); // undefined, undefined
    });
}]);

This means you cannot check access rights in there.

Solution:

As loading of controller is done via resolve, you can do the same with your access control check:

app.config(["$routeProvider", function($routeProvider) {
    $routeProvider.when("/foo", {
        controller: "Foo",
        resolve: {
            controller: ["$q", function($q) {
                var deferred = $q.defer();
                require(["path/to/controller/Foo"], function(Foo) {
                    // now controller is loaded
                    deferred.resolve();
                });
                return deferred.promise;
            }],
            access: ["$q", function($q) {
                var deferred = $q.defer();
                if (/* some logic to determine access is granted */) {
                    deferred.resolve();
                } else {
                    deferred.reject("You have no access rights to go there");
                }
                return deferred.promise;
            }],
        }
    });
}]);

app.run(["$rootScope", function($rootScope) {
    $rootScope.$on("$routeChangeError", function(event, next, current, error) {
        console.log("Error: " + error); // "Error: You have no access rights to go there"
    });
}]);

Note here that instead of using event $routeChangeStart I'm using $routeChangeError

Simple logical operators in Bash

if ([ $NUM1 == 1 ] || [ $NUM2 == 1 ]) && [ -z "$STR" ]
then
    echo STR is empty but should have a value.
fi

How to increase the distance between table columns in HTML?

A better solution than selected answer would be to use border-size rather than border-spacing. The main problem with using border-spacing is that even the first column would have a spacing in the front.

For example,

_x000D_
_x000D_
table {_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 80px 0;_x000D_
}_x000D_
_x000D_
td {_x000D_
  padding: 10px 0;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First Column</td>_x000D_
    <td>Second Column</td>_x000D_
    <td>Third Column</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1</td>_x000D_
    <td>2</td>_x000D_
    <td>3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

To avoid this use: border-left: 100px solid #FFF; and set border:0px for the first column.

For example,

_x000D_
_x000D_
td,th{_x000D_
  border-left: 100px solid #FFF;_x000D_
}_x000D_
_x000D_
 tr>td:first-child {_x000D_
   border:0px;_x000D_
 }
_x000D_
<table id="t">_x000D_
  <tr>_x000D_
    <td>Column1</td>_x000D_
    <td>Column2</td>_x000D_
    <td>Column3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>1000</td>_x000D_
    <td>2000</td>_x000D_
    <td>3000</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Make the size of a heatmap bigger with seaborn

You could alter the figsize by passing a tuple showing the width, height parameters you would like to keep.

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10,10))         # Sample figsize in inches
sns.heatmap(df1.iloc[:, 1:6:], annot=True, linewidths=.5, ax=ax)

EDIT

I remember answering a similar question of yours where you had to set the index as TIMESTAMP. So, you could then do something like below:

df = df.set_index('TIMESTAMP')
df.resample('30min').mean()
fig, ax = plt.subplots()
ax = sns.heatmap(df.iloc[:, 1:6:], annot=True, linewidths=.5)
ax.set_yticklabels([i.strftime("%Y-%m-%d %H:%M:%S") for i in df.index], rotation=0)

For the head of the dataframe you posted, the plot would look like:

enter image description here

Check if an element has event listener on it. No jQuery

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListener method.

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

Difference between timestamps with/without time zone in PostgreSQL

I try to explain it more understandably than the referred PostgreSQL documentation.

Neither TIMESTAMP variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:

  • TIMESTAMP WITHOUT TIME ZONE stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30', then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00' and '2011-07-01 06:30:30+05' are the same as just '2011-07-01 06:30:30'. For Java developers: it's analogous to java.time.LocalDateTime.

  • TIMESTAMP WITH TIME ZONE stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30') it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'). The output is displayed converted to the current time zone of the PostgreSQL session. For Java developers: It's analogous to java.time.Instant (with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime (or to java.util.Date or java.sql.Timestamp of course).

Some say that both TIMESTAMP variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE is stored like a TIMESTAMP WITH TIME ZONE, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)

Best Way to View Generated Source of Webpage?

Justin is dead on. The key point here is that HTML is just a language for describing a document. Once the browser reads it, it's gone. Open tags, close tags, and formatting are all taken care of by the parser and then go away. Any tool that shows you HTML is generating it based on the contents of the document, so it will always be valid.

I had to explain this to another web developer once, and it took a little while for him to accept it.

You can try it for yourself in any JavaScript console:

el = document.createElement('div');
el.innerHTML = "<p>Some text<P>More text";
el.innerHTML; // <p>Some text</p><p>More text</p>

The un-closed tags and uppercase tag names are gone, because that HTML was parsed and discarded after the second line.

The right way to modify the document from JavaScript is with document methods (createElement, appendChild, setAttribute, etc.) and you'll observe that there's no reference to tags or HTML syntax in any of those functions. If you're using document.write, innerHTML, or other HTML-speaking calls to modify your pages, the only way to validate it is to catch what you're putting into them and validate that HTML separately.

That said, the simplest way to get at the HTML representation of the document is this:

document.documentElement.innerHTML

Circular dependency in Spring

If two beans are dependent on each other then we should not use Constructor injection in both the bean definitions. Instead we have to use setter injection in any one of the beans. (of course we can use setter injection n both the bean definitions, but constructor injections in both throw 'BeanCurrentlyInCreationException'

Refer Spring doc at "https://docs.spring.io/spring/docs/current/spring-framework-reference/core.html#resources-resource"

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

How to efficiently calculate a running standard deviation?

Here is a practical example of how you could implement a running standard deviation with python and numpy:

a = np.arange(1, 10)
s = 0
s2 = 0
for i in range(0, len(a)):
    s += a[i]
    s2 += a[i] ** 2 
    n = (i + 1)
    m = s / n
    std = np.sqrt((s2 / n) - (m * m))
    print(std, np.std(a[:i + 1]))

This will print out the calculated standard deviation and a check standard deviation calculated with numpy:

0.0 0.0
0.5 0.5
0.8164965809277263 0.816496580927726
1.118033988749895 1.118033988749895
1.4142135623730951 1.4142135623730951
1.707825127659933 1.707825127659933
2.0 2.0
2.29128784747792 2.29128784747792
2.5819888974716116 2.581988897471611

I am just using the formula described in this thread:

stdev = sqrt((sum_x2 / n) - (mean * mean)) 

Create an ArrayList with multiple object types?

User Defined Class Array List Example

import java.util.*;  

public class UserDefinedClassInArrayList {

    public static void main(String[] args) {

        //Creating user defined class objects  
        Student s1=new Student(1,"AAA",13);  
        Student s2=new Student(2,"BBB",14);  
        Student s3=new Student(3,"CCC",15); 

        ArrayList<Student> al=new ArrayList<Student>();
        al.add(s1);
        al.add(s2);  
        al.add(s3);  

        Iterator itr=al.iterator();  

        //traverse elements of ArrayList object  
        while(itr.hasNext()){  
            Student st=(Student)itr.next();  
            System.out.println(st.rollno+" "+st.name+" "+st.age);  
        }  
    }
}

class Student{  
    int rollno;  
    String name;  
    int age;  
    Student(int rollno,String name,int age){  
        this.rollno=rollno;  
        this.name=name;  
        this.age=age;  
    }  
} 

Program Output:

1 AAA 13

2 BBB 14

3 CCC 15

iPhone App Icons - Exact Radius?

After trying some of the answers in this post, I consulted with Louie Mantia (former Apple, Square, and Iconfactory designer) and all the answers so far on this post are wrong (or at least incomplete). Apple starts with the 57px icon and a radius of 10 then scales up or down from there. Thus you can calculate the radius for any icon size using 10/57 x new size (for example 10/57 x 114 gives 20, which is the proper radius for a 114px icon). Here is a list of the most commonly used icons, proper naming conventions, pixel dimensions, and corner radii.

  1. Icon1024.png - 1024px - 179.649
  2. Icon512.png - 512px - 89.825
  3. Icon.png - 57px - 10
  4. [email protected] - 114px - 20
  5. Icon-72.png - 72px - 12.632
  6. [email protected] - 144px - 25.263
  7. Icon-Small.png - 29px - 5.088
  8. [email protected] - 58px - 10.175

Also, as mentioned in other answers, you don't actually want to crop any of the images you use in the binary or submit to Apple. Those should all be square and not have any transparency. Apple will automatically mask each icon in the appropriate context.

Knowing the above is important, however, for icon usage within app UI where you have to apply the mask in code, or pre-rendered in photoshop. It's also helpful when creating artwork for websites and other promotional material.

Additional reading:

Neven Mrgan on additional icon sizes and other design considerations: ios app icon sizes

Bjango's Marc Edwards on the different options for creating roundrects in Photoshop and why it matters: roundrect

Apple's official docs on icon size and design considerations: Icons and Images

Update:

I did some tests in Photoshop CS6 and it seems as though 3 digits after the decimal point is enough precision to end up with the exact same vector (at least as displayed by Photoshop at 3200% zoom). The Round Rect Tool sometimes rounds the input to the nearest whole number, but you can see a significant difference between 90 and 89.825. And several times the Round Rectangle Tool didn't round up and actually showed multiple digits after the decimal point. Not sure what's going on there, but it's definitely using and storing the more precise number that was entered.

Anyhow, I've updated the list above to include just 3 digits after the decimal point (before there were 13!). In most situations it would probably be hard to tell the difference between a transparent 512px icon masked at a 90px radius and one masked at 89.825, but the antialiasing of the rounded corner would definitely end up slightly different and would likely be visible in certain circumstances especially if a second, more precise mask is applied by Apple, in code, or otherwise.

Kill process by name?

You can use pkill <process_name> in a unix system to kill process by name.

Then the python code will be:

>>> import os
>>> process_name=iChat
>>> os.system('pkill '+process_name)

Bootstrap 4: responsive sidebar menu to top navbar

Big screen:

navigation side bar in big screen size

Small screen (Mobile)

sidebar in small mobile size screen

if this is what you wanted this is code https://plnkr.co/edit/PCCJb9f7f93HT4OubLmM?p=preview

CSS + HTML + JQUERY :

_x000D_
_x000D_
    _x000D_
    @import "https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700";_x000D_
    body {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      background: #fafafa;_x000D_
    }_x000D_
    _x000D_
    p {_x000D_
      font-family: 'Poppins', sans-serif;_x000D_
      font-size: 1.1em;_x000D_
      font-weight: 300;_x000D_
      line-height: 1.7em;_x000D_
      color: #999;_x000D_
    }_x000D_
    _x000D_
    a,_x000D_
    a:hover,_x000D_
    a:focus {_x000D_
      color: inherit;_x000D_
      text-decoration: none;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    .navbar {_x000D_
      padding: 15px 10px;_x000D_
      background: #fff;_x000D_
      border: none;_x000D_
      border-radius: 0;_x000D_
      margin-bottom: 40px;_x000D_
      box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.1);_x000D_
    }_x000D_
    _x000D_
    .navbar-btn {_x000D_
      box-shadow: none;_x000D_
      outline: none !important;_x000D_
      border: none;_x000D_
    }_x000D_
    _x000D_
    .line {_x000D_
      width: 100%;_x000D_
      height: 1px;_x000D_
      border-bottom: 1px dashed #ddd;_x000D_
      margin: 40px 0;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    SIDEBAR STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #sidebar {_x000D_
      width: 250px;_x000D_
      position: fixed;_x000D_
      top: 0;_x000D_
      left: 0;_x000D_
      height: 100vh;_x000D_
      z-index: 999;_x000D_
      background: #7386D5;_x000D_
      color: #fff !important;_x000D_
      transition: all 0.3s;_x000D_
    }_x000D_
    _x000D_
    #sidebar.active {_x000D_
      margin-left: -250px;_x000D_
    }_x000D_
    _x000D_
    #sidebar .sidebar-header {_x000D_
      padding: 20px;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul.components {_x000D_
      padding: 20px 0;_x000D_
      border-bottom: 1px solid #47748b;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul p {_x000D_
      color: #fff;_x000D_
      padding: 10px;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a {_x000D_
      padding: 10px;_x000D_
      font-size: 1.1em;_x000D_
      display: block;_x000D_
      color:white;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li a:hover {_x000D_
      color: #7386D5;_x000D_
      background: #fff;_x000D_
    }_x000D_
    _x000D_
    #sidebar ul li.active>a,_x000D_
    a[aria-expanded="true"] {_x000D_
      color: #fff;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    a[data-toggle="collapse"] {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="false"]::before,_x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e259';_x000D_
      display: block;_x000D_
      position: absolute;_x000D_
      right: 20px;_x000D_
      font-family: 'Glyphicons Halflings';_x000D_
      font-size: 0.6em;_x000D_
    }_x000D_
    _x000D_
    a[aria-expanded="true"]::before {_x000D_
      content: '\e260';_x000D_
    }_x000D_
    _x000D_
    ul ul a {_x000D_
      font-size: 0.9em !important;_x000D_
      padding-left: 30px !important;_x000D_
      background: #6d7fcc;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs {_x000D_
      padding: 20px;_x000D_
    }_x000D_
    _x000D_
    ul.CTAs a {_x000D_
      text-align: center;_x000D_
      font-size: 0.9em !important;_x000D_
      display: block;_x000D_
      border-radius: 5px;_x000D_
      margin-bottom: 5px;_x000D_
    }_x000D_
    _x000D_
    a.download {_x000D_
      background: #fff;_x000D_
      color: #7386D5;_x000D_
    }_x000D_
    _x000D_
    a.article,_x000D_
    a.article:hover {_x000D_
      background: #6d7fcc !important;_x000D_
      color: #fff !important;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    CONTENT STYLE_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    #content {_x000D_
      width: calc(100% - 250px);_x000D_
      padding: 40px;_x000D_
      min-height: 100vh;_x000D_
      transition: all 0.3s;_x000D_
      position: absolute;_x000D_
      top: 0;_x000D_
      right: 0;_x000D_
    }_x000D_
    _x000D_
    #content.active {_x000D_
      width: 100%;_x000D_
    }_x000D_
    /* ---------------------------------------------------_x000D_
    MEDIAQUERIES_x000D_
----------------------------------------------------- */_x000D_
    _x000D_
    @media (max-width: 768px) {_x000D_
      #sidebar {_x000D_
        margin-left: -250px;_x000D_
      }_x000D_
      #sidebar.active {_x000D_
        margin-left: 0;_x000D_
      }_x000D_
      #content {_x000D_
        width: 100%;_x000D_
      }_x000D_
      #content.active {_x000D_
        width: calc(100% - 250px);_x000D_
      }_x000D_
      #sidebarCollapse span {_x000D_
        display: none;_x000D_
      }_x000D_
    }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
  <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
_x000D_
  <title>Collapsible sidebar using Bootstrap 3</title>_x000D_
_x000D_
  <!-- Bootstrap CSS CDN -->_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <!-- Our Custom CSS -->_x000D_
  <link rel="stylesheet" href="style2.css">_x000D_
  <!-- Scrollbar Custom CSS -->_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css">_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
_x000D_
_x000D_
  <div class="wrapper">_x000D_
    <!-- Sidebar Holder -->_x000D_
    <nav id="sidebar">_x000D_
      <div class="sidebar-header">_x000D_
        <h3>Header as you want </h3>_x000D_
        </h3>_x000D_
      </div>_x000D_
_x000D_
      <ul class="list-unstyled components">_x000D_
        <p>Dummy Heading</p>_x000D_
        <li class="active">_x000D_
          <a href="#menu">Animación</a>_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Ilustración</a>_x000D_
_x000D_
_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#menu">Interacción</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Blog</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">Acerca</a>_x000D_
        </li>_x000D_
        <li>_x000D_
          <a href="#">contacto</a>_x000D_
        </li>_x000D_
_x000D_
_x000D_
      </ul>_x000D_
_x000D_
_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content Holder -->_x000D_
    <div id="content">_x000D_
_x000D_
      <nav class="navbar navbar-default">_x000D_
        <div class="container-fluid">_x000D_
_x000D_
          <div class="navbar-header">_x000D_
            <button type="button" id="sidebarCollapse" class="btn btn-info navbar-btn">_x000D_
                                <i class="glyphicon glyphicon-align-left"></i>_x000D_
                                <span>Toggle Sidebar</span>_x000D_
                            </button>_x000D_
          </div>_x000D_
_x000D_
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
            <ul class="nav navbar-nav navbar-right">_x000D_
              <li><a href="#">Page</a></li>_x000D_
            </ul>_x000D_
          </div>_x000D_
        </div>_x000D_
      </nav>_x000D_
_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
  <!-- jQuery CDN -->_x000D_
  <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>_x000D_
  <!-- Bootstrap Js CDN -->_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
  <!-- jQuery Custom Scroller CDN -->_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>_x000D_
_x000D_
  <script type="text/javascript">_x000D_
    $(document).ready(function() {_x000D_
_x000D_
_x000D_
      $('#sidebarCollapse').on('click', function() {_x000D_
        $('#sidebar, #content').toggleClass('active');_x000D_
        $('.collapse.in').toggleClass('in');_x000D_
        $('a[aria-expanded=true]').attr('aria-expanded', 'false');_x000D_
      });_x000D_
    });_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

if this is what you want .

Multiple WHERE Clauses with LINQ extension methods

you can use && and write all conditions in to the same where clause, or you can .Where().Where().Where()... and so on.

How do I set up IntelliJ IDEA for Android applications?

I've spent a day on trying to put all the pieces together, been in hundreds of sites and tutorials, but they all skip trivial steps.

So here's the full guide:

  1. Download and install Java JDK (Choose the Java platform)
  2. Download and install Android SDK (Installer is recommended)
  3. After android SD finishes installing, open SDK Manager under Android SDK Tools (sometimes needs to be opened under admin's privileges)
  4. Choose everything and mark Accept All and install.
  5. Download and install IntelliJ IDEA (The community edition is free)
  6. Wait for all downloads and installations and stuff to finish.

New Project:

  1. Run IntelliJ
  2. Create a new project (there's a tutorial here)
  3. Enter the name, choose Android type.
  4. There's a step missing in the tutorial, when you are asked to choose the JDK (before choosing the SDK) you need to choose the Java JDK you've installed earlier. Should be under C:\Program Files\Java\jdk{version}
  5. Choose a New platform ( if there's not one selected ) , the SDK platform is the android platform at C:\Program Files\Android\android-sdk-windows.
  6. Choose the android version.
  7. Now you can write your program.

Compiling:

  1. Near the Run button you need to select the drop-down-list, choose Edit Configurations
  2. In the Prefer Android Virtual device select the ... button
  3. Click on create, give it a name, press OK.
  4. Double click the new device to choose it.
  5. Press OK.
  6. You're ready to run the program.

How do I export an Android Studio project?

In the Android Studio go to File then Close Project. Then take the folder (in the workspace folder) of the project and copy it to a flash memory or whatever. Then when you get comfortable at home, copy this folder in the workspace folder you've already created, open the Android Studio and go to File then Open and import this project into your workspace.

The problem you have with this is that you're searching for the wrong term here, because in Android, exporting a project means compiling it to .apk file (not exporting the project). Import/Export is used for the .apk management, what you need is Open/Close project, the other thing is just copy/paste.

Getting user input

sys.argv[0] is not the first argument but the filename of the python program you are currently executing. I think you want sys.argv[1]

How to check if internet connection is present in Java?

You should connect to the place that your actual application needs. Otherwise you're testing whether you have a connection to somewhere irrelevant (Google in this case).

In particular, if you're trying to talk to a web service, and if you're in control of the web service, it would be a good idea to have some sort of cheap "get the status" web method. That way you have a much better idea of whether your "real" call is likely to work.

In other cases, just opening a connection to a port that should be open may be enough - or sending a ping. InetAddress.isReachable may well be an appropriate API for your needs here.

how to move elasticsearch data from one server to another

You can use snapshot/restore feature available in Elasticsearch for this. Once you have setup a Filesystem based snapshot store, you can move it around between clusters and restore on a different cluster

How can I regenerate ios folder in React Native project?

Since react-native eject is depreciated in 60.3 and I was getting diff errors trying to upgrade form 60.1 to 60.3 regenerating the android folder was not working.

I had to

rm -R node_modules

Then update react-native in package.json to 59.1 (remove package-lock.json)

Run

npm install

react-native eject

This will regenerate your android and ios folders Finally upgrade back to 60.3

react-native upgrade

react-native upgrade while back and 59.1 did not regenerate my android folder so the eject was necessary.

Print specific part of webpage

I Got a better option,

First separate the printable and nonprintable section by class name or id

_x000D_
_x000D_
window.onafterprint = onAfterPrint;_x000D_
_x000D_
function print(){_x000D_
  //hide the nonPrintable div  _x000D_
}_x000D_
_x000D_
function onAfterPrint(){_x000D_
  // Visible the nonPrintable div_x000D_
}
_x000D_
<input type="button" onclick="print()" value="Print"/>
_x000D_
_x000D_
_x000D_

That's all

Calling one Bash script from another Script passing it arguments with quotes and spaces

Quote your args in Testscript 1:

echo "TestScript1 Arguments:"
echo "$1"
echo "$2"
echo "$#"
./testscript2 "$1" "$2"

Android replace the current fragment with another fragment

Latest Stuff

Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.

Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.

  1. Add Kotlin extension for Fragments to your project.

In your app level build.gradle file add the following,

dependencies {
    def fragment_version = "1.2.5"

    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
  1. Then simple code to replace the fragment,

In your activity

supportFragmentManager.commit {
    replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
    addToBackStack(null)
}

References

Check latest version of Fragment extension

More on Fragments

Is it valid to define functions in JSON results?

A short answer is NO...

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

Look at the reason why:

When exchanging data between a browser and a server, the data can only be text.

JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

We can also convert any JSON received from the server into JavaScript objects.

This way we can work with the data as JavaScript objects, with no complicated parsing and translations.

But wait...

There is still ways to store your function, it's widely not recommended to that, but still possible:

We said, you can save a string... how about converting your function to a string then?

const data = {func: '()=>"a FUNC"'};

Then you can stringify data using JSON.stringify(data) and then using JSON.parse to parse it (if this step needed)...

And eval to execute a string function (before doing that, just let you know using eval widely not recommended):

eval(data.func)(); //return "a FUNC"

Multiple linear regression in Python

try a generalized linear model with a gaussian family

y = np.array([-6, -5, -10, -5, -8, -3, -6, -8, -8])
X = np.array([
    [-4.95, -4.55, -10.96, -1.08, -6.52, -0.81, -7.01, -4.46, -11.54],
    [-5.87, -4.52, -11.64, -3.36, -7.45, -2.36, -7.33, -7.65, -10.03],
    [-0.76, -0.71, -0.98, 0.75, -0.86, -0.50, -0.33, -0.94, -1.03],
    [14.73, 13.74, 15.49, 24.72, 16.59, 22.44, 13.93, 11.40, 18.18],
    [4.02, 4.47, 4.18, 4.96, 4.29, 4.81, 4.32, 4.43, 4.28],
    [0.20, 0.16, 0.19, 0.16, 0.10, 0.15, 0.21, 0.16, 0.21],
    [0.45, 0.50, 0.53, 0.60, 0.48, 0.53, 0.50, 0.49, 0.55],
])
X=zip(*reversed(X))

df=pd.DataFrame({'X':X,'y':y})
columns=7
for i in range(0,columns):
    df['X'+str(i)]=df.apply(lambda row: row['X'][i],axis=1)

df=df.drop('X',axis=1)
print(df)


#model_formula='y ~ X0+X1+X2+X3+X4+X5+X6'
model_formula='y ~ X0'

model_family = sm.families.Gaussian()
model_fit = glm(formula = model_formula, 
             data = df, 
             family = model_family).fit()

print(model_fit.summary())

# Extract coefficients from the fitted model wells_fit
#print(model_fit.params)
intercept, slope = model_fit.params

# Print coefficients
print('Intercept =', intercept)
print('Slope =', slope)

# Extract and print confidence intervals
print(model_fit.conf_int())

df2=pd.DataFrame()
df2['X0']=np.linspace(0.50,0.70,50)

df3=pd.DataFrame()
df3['X1']=np.linspace(0.20,0.60,50)

prediction0=model_fit.predict(df2)
#prediction1=model_fit.predict(df3)

plt.plot(df2['X0'],prediction0,label='X0')
plt.ylabel("y")
plt.xlabel("X0")
plt.show()

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Well you could solve this with a temp table..

DECLARE @RoleToAdds TABLE
([RoleID] int, [PageID] int)

INSERT INTO @RoleToAdds ([RoleID], [PageID])
    VALUES
    (1, 2),
    (1, 3),
    (1, 4),
    (2, 5)

INSERT INTO [dbo].[RolePages] ([RoleID], [PageID])
    SELECT rta.[RoleID], rta.[PageID] FROM @RoleToAdds rta WHERE NOT EXISTS 
        (SELECT * FROM [RolePages] rp WHERE rp.PageID = rta.PageID AND rp.RoleID = rta.RoleID)

This might not work for big amounts of data but for a few rows it should work!

How do I declare a model class in my Angular 2 component using TypeScript?

create model.ts in your component directory as below

export module DataModel {
       export interface DataObjectName {
         propertyName: type;
        }
       export interface DataObjectAnother {
         propertyName: type;
        }
    }

then in your component import above as, import {DataModel} from './model';

export class YourComponent {
   public DataObject: DataModel.DataObjectName;
}

your DataObject should have all the properties from DataObjectName.

Check empty string in Swift?

A concise way to check if the string is nil or empty would be:

var myString: String? = nil

if (myString ?? "").isEmpty {
    print("String is nil or empty")
}

How to check if an array value exists?

Assuming you are using a simple array

. i.e.

$MyArray = array("red","blue","green");

You can use this function

function val_in_arr($val,$arr){
  foreach($arr as $arr_val){
    if($arr_val == $val){
      return true;
    }
  }
  return false;
}

Usage:

val_in_arr("red",$MyArray); //returns true
val_in_arr("brown",$MyArray); //returns false

Using classes with the Arduino

I created this simple one a while back. The main challenge I had was to create a good build environment - a makefile that would compile and link/deploy everything without having to use the GUI. For the code, here is the header:

class AMLed
{
    private:
          uint8_t _ledPin;
          long _turnOffTime;

    public:
          AMLed(uint8_t pin);
          void setOn();
          void setOff();
          // Turn the led on for a given amount of time (relies
          // on a call to check() in the main loop()).
          void setOnForTime(int millis);
          void check();
};

And here is the main source

AMLed::AMLed(uint8_t ledPin) : _ledPin(ledPin), _turnOffTime(0)
{
    pinMode(_ledPin, OUTPUT);
}

void AMLed::setOn()
{
    digitalWrite(_ledPin, HIGH);
}

void AMLed::setOff()
{
    digitalWrite(_ledPin, LOW);
}

void AMLed::setOnForTime(int p_millis)
{
    _turnOffTime = millis() + p_millis;
    setOn();
}

void AMLed::check()
{
    if (_turnOffTime != 0 && (millis() > _turnOffTime))
    {
        _turnOffTime = 0;
        setOff();
    }
}

It's more prettily formatted here: http://amkimian.blogspot.com/2009/07/trivial-led-class.html

To use, I simply do something like this in the .pde file:

#include "AM_Led.h"

#define TIME_LED    12   // The port for the LED

AMLed test(TIME_LED);

SQLAlchemy IN clause

How about

session.query(MyUserClass).filter(MyUserClass.id.in_((123,456))).all()

edit: Without the ORM, it would be

session.execute(
    select(
        [MyUserTable.c.id, MyUserTable.c.name], 
        MyUserTable.c.id.in_((123, 456))
    )
).fetchall()

select() takes two parameters, the first one is a list of fields to retrieve, the second one is the where condition. You can access all fields on a table object via the c (or columns) property.

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

Use In instead of =

 select * from dbo.books
 where isbn in (select isbn from dbo.lending 
                where act between @fdate and @tdate
                and stat ='close'
               )

or you can use Exists

SELECT t1.*,t2.*
FROM  books   t1 
WHERE  EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
                t2.act between @fdate and @tdate and t2.stat ='close' )

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<style>
a{
cursor: default;
}
</style>

In the above code [cursor:default] is used. Default is the usual arrow cursor that appears.

And if you use [cursor: pointer] then you can access to the hand like cursor that appears when you hover over a link.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

Measuring text height to be drawn on Canvas ( Android )

The height is the text size you have set on the Paint variable.

Another way to find out the height is

mPaint.getTextSize();

How do I remove accents from characters in a PHP string?

Based on @Mimouni answer I made this function to transliterate Accented strings to Non Accented strings.

/**
 * @param $str Convert string to lowercase and replace special chars to equivalents ou remove its
 * @return string
 */
function _slugify(string $string): string
{
    $str = $string; // for comparisons
    $str = _toUtf8($str); // Force to work with string in UTF-8
    $str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);

    if ($str != htmlentities($string, ENT_QUOTES, 'UTF-8')) { // iconv fails
        $str = _toUtf8($string);
        $str = htmlentities($str, ENT_QUOTES, 'UTF-8');
        $str = preg_replace('#&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);#i', '$1', $str);
        // Need to strip non ASCII chars or any other than a-z, A-Z, 0-9...
        $str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
        $str = preg_replace(array('#[^0-9a-z]#i', '#[ -]+#'), ' ', $str);
        $str = trim($str, ' -');
    }

    // lowercase
    $string = strtolower($str);

    return $string;
}

To convert strings to UTF-8, here I use the Multi Byte String extension. Note that I break string in pieces to avoid trouble with mixed content (I have such situation) and convert word by word.

/**
 * @param $str string String in any encoding
 * @return string
 */
function _toUtf8(string $str_in): ?string
{
    if (!function_exists('mb_detect_encoding')) {
        throw new \Exception('The Multi Byte String extension is absent!');
    }
    $str_out = [];
    $words = explode(" ", $str_in);
    foreach ($words as $word) {
        $current_encoding = mb_detect_encoding($word, 'UTF-8, ASCII, ISO-8859-1');
        $str_out[] = mb_convert_encoding($word, 'UTF-8', $current_encoding);
    }
    return implode(" ", $str_out);
}

Footer Notes: Was the only solution that pass in PHPUnit UnitTests in Windows command Line (locale issues) The @gabo solution should work but unfortunately not for me

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

It turns out setting these configuration properties is pretty straight forward, but the official documentation is more general so it might be hard to find when searching specifically for connection pool configuration information.

To set the maximum pool size for tomcat-jdbc, set this property in your .properties or .yml file:

spring.datasource.maxActive=5

You can also use the following if you prefer:

spring.datasource.max-active=5

You can set any connection pool property you want this way. Here is a complete list of properties supported by tomcat-jdbc.

To understand how this works more generally you need to dig into the Spring-Boot code a bit.

Spring-Boot constructs the DataSource like this (see here, line 102):

@ConfigurationProperties(prefix = DataSourceAutoConfiguration.CONFIGURATION_PREFIX)
@Bean
public DataSource dataSource() {
    DataSourceBuilder factory = DataSourceBuilder
            .create(this.properties.getClassLoader())
            .driverClassName(this.properties.getDriverClassName())
            .url(this.properties.getUrl())
            .username(this.properties.getUsername())
            .password(this.properties.getPassword());
    return factory.build();
}

The DataSourceBuilder is responsible for figuring out which pooling library to use, by checking for each of a series of know classes on the classpath. It then constructs the DataSource and returns it to the dataSource() function.

At this point, magic kicks in using @ConfigurationProperties. This annotation tells Spring to look for properties with prefix CONFIGURATION_PREFIX (which is spring.datasource). For each property that starts with that prefix, Spring will try to call the setter on the DataSource with that property.

The Tomcat DataSource is an extension of DataSourceProxy, which has the method setMaxActive().

And that's how your spring.datasource.maxActive=5 gets applied correctly!

What about other connection pools

I haven't tried, but if you are using one of the other Spring-Boot supported connection pools (currently HikariCP or Commons DBCP) you should be able to set the properties the same way, but you'll need to look at the project documentation to know what is available.

How can I disable a button on a jQuery UI dialog?

I created a jQuery function in order to make this task a bit easier. Probably now there is a better solution... either way, here's my 2cents. :)

Just add this to your JS file:

$.fn.dialogButtons = function(name, state){
var buttons = $(this).next('div').find('button');
if(!name)return buttons;
return buttons.each(function(){
    var text = $(this).text();
    if(text==name && state=='disabled') {$(this).attr('disabled',true).addClass('ui-state-disabled');return this;}
    if(text==name && state=='enabled') {$(this).attr('disabled',false).removeClass('ui-state-disabled');return this;}
    if(text==name){return this;}
    if(name=='disabled'){$(this).attr('disabled',true).addClass('ui-state-disabled');return buttons;}
    if(name=='enabled'){$(this).attr('disabled',false).removeClass('ui-state-disabled');return buttons;}
});};

Disable button 'Ok' on dialog with class 'dialog':

$('.dialog').dialogButtons('Ok', 'disabled');

Enable all buttons:

$('.dialog').dialogButtons('enabled');

Enable 'Close' button and change color:

$('.dialog').dialogButtons('Close', 'enabled').css('color','red');

Text on all buttons red:

$('.dialog').dialogButtons().css('color','red');

Hope this helps :)

Numpy: Get random set of rows from 2D array

If you want to generate multiple random subsets of rows, for example if your doing RANSAC.

num_pop = 10
num_samples = 2
pop_in_sample = 3
rows_to_sample = np.random.random([num_pop, 5])
random_numbers = np.random.random([num_samples, num_pop])
samples = np.argsort(random_numbers, axis=1)[:, :pop_in_sample]
# will be shape [num_samples, pop_in_sample, 5]
row_subsets = rows_to_sample[samples, :]

sizing div based on window width

Try absolute positioning:

<div style="position:relative;width:100%;">
    <div id="help" style="
    position:absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index:1;">
        <img src="/portfolio/space_1_header.png" border="0" style="width:100%;">
    </div>
</div>

Reading string by char till end of line C/C++

A text file does not have \0 at the end of lines. It has \n. \n is a character, not a string, so it must be enclosed in single quotes

if (c == '\n')

CSS image resize percentage of itself?

This is a very old thread but I found it while searching for a simple solution to display retina (high res) screen capture on standard resolution display.

So there is an HTML only solution for modern browsers :

<img srcset="image.jpg 100w" sizes="50px" src="image.jpg"/>

This is telling the browser that the image is twice the dimension of it intended display size. The value are proportional and do not need to reflect the actual size of the image. One can use 2w 1px as well to achieve the same effect. The src attribute is only used by legacy browsers.

The nice effect of it is that it display the same size on retina or standard display, shrinking on the latter.

Pointer-to-pointer dynamic two-dimensional array

What you describe for the second method only gives you a 1D array:

int *board = new int[10];

This just allocates an array with 10 elements. Perhaps you meant something like this:

int **board = new int*[4];
for (int i = 0; i < 4; i++) {
  board[i] = new int[10];
}

In this case, we allocate 4 int*s and then make each of those point to a dynamically allocated array of 10 ints.

So now we're comparing that with int* board[4];. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*s, as the array will be destroyed at the end of its scope.

The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:

for (int i = 0; i < 4; i++) {
  delete[] board[i];
}
delete[] board;

I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4> or perhaps a std::vector<std::vector<int>> which you initialise to the appropriate size.

How to fix request failed on channel 0

Just rebooting a AWS instance works for me to clear the error "shell request failed on channel 0"

How do I perform an insert and return inserted identity with Dapper?

The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).

You can return it as an int by casting it as follows:

string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";

int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

Jquery: how to trigger click event on pressing enter key

Are you trying to mimic a click on a button when the enter key is pressed? If so you may need to use the trigger syntax.

Try changing

$('input[name = butAssignProd]').click();

to

$('input[name = butAssignProd]').trigger("click");

If this isn't the problem then try taking a second look at your key capture syntax by looking at the solutions in this post: jQuery Event Keypress: Which key was pressed?

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

What is unit testing and how do you do it?

Unit testing involves breaking your program into pieces, and subjecting each piece to a series of tests.

Usually tests are run as separate programs, but the method of testing varies, depending on the language, and type of software (GUI, command-line, library).

Most languages have unit testing frameworks, you should look into one for yours.

Tests are usually run periodically, often after every change to the source code. The more often the better, because the sooner you will catch problems.

How to access the correct `this` inside a callback?

Here are several ways to access parent context inside child context -

  1. You can use bind() function.
  2. Store reference to context/this inside another variable(see below example).
  3. Use ES6 Arrow functions.
  4. Alter code/function design/architecture - for this you should have command over design patterns in javascript.

1. Use bind() function

function MyConstructor(data, transport) {
    this.data = data;
    transport.on('data', ( function () {
        alert(this.data);
    }).bind(this) );
}
// Mock transport object
var transport = {
    on: function(event, callback) {
        setTimeout(callback, 1000);
    }
};
// called as
var obj = new MyConstructor('foo', transport);

If you are using underscore.js - http://underscorejs.org/#bind

transport.on('data', _.bind(function () {
    alert(this.data);
}, this));

2 Store reference to context/this inside another variable

function MyConstructor(data, transport) {
  var self = this;
  this.data = data;
  transport.on('data', function() {
    alert(self.data);
  });
}

3 Arrow function

function MyConstructor(data, transport) {
  this.data = data;
  transport.on('data', () => {
    alert(this.data);
  });
}

How do you know if Tomcat Server is installed on your PC

In order to make

     http://localhost:8080

work, tomcat has to be started first. You can check server.xml file in conf folder for the port information. You can search if tomcat is installed on your machine. Just go to start and then type tomcat. If it is installed it will give you the directory where it is installed. Then you can select that path and run it from command prompt. Example if tomcat is installed in C:\Programfile\tomcat. You need to set this path in command prompt,go to bin folder and startup. Example: C:\Programfile\tomcat\bin\startup. Else you can also run it by directly going to the path and run startup batch file.

Oracle "(+)" Operator

In Oracle, (+) denotes the "optional" table in the JOIN. So in your query,

SELECT a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id(+)

it's a LEFT OUTER JOIN of table 'b' to table 'a'. It will return all data of table 'a' without losing its data when the other side (optional table 'b') has no data.

Diagram of Left Outer Join

The modern standard syntax for the same query would be

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b ON a.id=b.id

or with a shorthand for a.id=b.id (not supported by all databases):

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
LEFT JOIN b USING(id)

If you remove (+) then it will be normal inner join query

Older syntax, in both Oracle and other databases:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id=b.id

More modern syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
INNER JOIN b ON a.id=b.id

Or simply:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
JOIN b ON a.id=b.id

Diagram of Inner Join

It will only return all data where both 'a' & 'b' tables 'id' value is same, means common part.

If you want to make your query a Right Join

This is just the same as a LEFT JOIN, but switches which table is optional.

Diagram of Right Outer Join

Old Oracle syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a,b
WHERE a.id(+)=b.id

Modern standard syntax:

SELECT  a.id, b.id, a.col_2, b.col_2, ...
FROM a
RIGHT JOIN b ON a.id=b.id

Ref & help:

https://asktom.oracle.com/pls/asktom/f?p=100:11:::::P11_QUESTION_ID:6585774577187

Left Outer Join using + sign in Oracle 11g

https://www.w3schools.com/sql/sql_join_left.asp

Getting Integer value from a String using javascript/jquery

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

How can I check if some text exist or not in the page using Selenium?

  boolean Error = driver.getPageSource().contains("Your username or password was incorrect.");
    if (Error == true)
    {
     System.out.print("Login unsuccessful");
    }
    else
    {
     System.out.print("Login successful");
    }

How can I get the application's path in a .NET console application?

For anyone interested in asp.net web apps. Here are my results of 3 different methods

protected void Application_Start(object sender, EventArgs e)
{
  string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
  string p3 = this.Server.MapPath("");
  Console.WriteLine("p1 = " + p1);
  Console.WriteLine("p2 = " + p2);
  Console.WriteLine("p3 = " + p3);
}

result

p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging

the app is physically running from "C:\inetpub\SBSPortal_staging", so the first solution is definitely not appropriate for web apps.

Least common multiple for 3 or more numbers

Here is a C# port of Virgil Disgr4ce's implemenation:

public class MathUtils
{
    /// <summary>
    /// Calculates the least common multiple of 2+ numbers.
    /// </summary>
    /// <remarks>
    /// Uses recursion based on lcm(a,b,c) = lcm(a,lcm(b,c)).
    /// Ported from http://stackoverflow.com/a/2641293/420175.
    /// </remarks>
    public static Int64 LCM(IList<Int64> numbers)
    {
        if (numbers.Count < 2)
            throw new ArgumentException("you must pass two or more numbers");
        return LCM(numbers, 0);
    }

    public static Int64 LCM(params Int64[] numbers)
    {
        return LCM((IList<Int64>)numbers);
    }

    private static Int64 LCM(IList<Int64> numbers, int i)
    {
        // Recursively iterate through pairs of arguments
        // i.e. lcm(args[0], lcm(args[1], lcm(args[2], args[3])))

        if (i + 2 == numbers.Count)
        {
            return LCM(numbers[i], numbers[i+1]);
        }
        else
        {
            return LCM(numbers[i], LCM(numbers, i+1));
        }
    }

    public static Int64 LCM(Int64 a, Int64 b)
    {
        return (a * b / GCD(a, b));
    }

    /// <summary>
    /// Finds the greatest common denominator for 2 numbers.
    /// </summary>
    /// <remarks>
    /// Also from http://stackoverflow.com/a/2641293/420175.
    /// </remarks>
    public static Int64 GCD(Int64 a, Int64 b)
    {
        // Euclidean algorithm
        Int64 t;
        while (b != 0)
        {
            t = b;
            b = a % b;
            a = t;
        }
        return a;
    }
}'

@font-face not working

You need to put the font file name / path in quotes.
Eg.

url("../fonts/Gotham-Medium.ttf")

or

url('../fonts/Gotham-Medium.ttf')

and not

url(../fonts/Gotham-Medium.ttf)

Also @FONT-FACE only works with some font files. :o(

All the sites where you can download fonts, never say which fonts work and which ones don't.

SQL Server: Multiple table joins with a WHERE clause

You need to do a LEFT JOIN.

SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN dbo.Software_Computer
    ON Computer.ID = Software_Computer.ComputerID
LEFT JOIN dbo.Software
    ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN dbo.Application
    ON Application.ID = Software.ApplicationID
WHERE Computer.ID = 1 

Here is the explanation:

The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the right table returns one row and the left table returns more than one matching row for it, the values in the right table will be repeated for each distinct row on the left table. From Oracle 9i onwards the LEFT OUTER JOIN statement can be used as well as (+).

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

Linq with group by having count

Like this:

from c in db.Company
group c by c.Name into grp
where grp.Count() > 1
select grp.Key

Or, using the method syntax:

Company
    .GroupBy(c => c.Name)
    .Where(grp => grp.Count() > 1)
    .Select(grp => grp.Key);

Unable to execute dex: method ID not in [0, 0xffff]: 65536

You can analyse problem (dex file references) using Android Studio:

Build -> Analyse APK ..

On the result panel click on classes.dex file

And you'll see:

enter image description here

How to use delimiter for csv in python

Your code is blanking out your file:

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)

if you want to read the file in, you will need to use csv.reader and open the file for reading.

import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
    print line

If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).

How do I specify a password to 'psql' non-interactively?

From the official documentation:

It is also convenient to have a ~/.pgpass file to avoid regularly having to type in passwords. See Section 30.13 for more information.

...

This file should contain lines of the following format:

hostname:port:database:username:password

The password field from the first line that matches the current connection parameters will be used.

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

My Solution in laravel 5.2

{{ Form::open(['route' => ['votes.submit', $video->id],  'method' => 'POST']) }}
    <button type="submit" class="btn btn-primary">
        <span class="glyphicon glyphicon-thumbs-up"></span> Votar
    </button>
{{ Form::close() }}

My Routes File (under middleware)

Route::post('votar/{id}', [
    'as' => 'votes.submit',
    'uses' => 'VotesController@submit'
]);

Route::delete('votar/{id}', [
    'as' => 'votes.destroy',
    'uses' => 'VotesController@destroy'
]);

Gulp command not found after install

Not sure why the question was down-voted, but I had the same issue and following the blog post recommended solve the issue. One thing I should add is that in my case, once I ran:

npm config set prefix /usr/local

I confirmed the npm root -g was pointing to /usr/local/lib/node_modules/npm, but in order to install gulp in /usr/local/lib/node_modules, I had to use sudo:

sudo npm install gulp -g

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

Don't know if this will be everybody's answer, but after some digging, here's what we came up with.

The error is obviously caused by the fact that the listener was not accepting connections, but why would we get that error when other tests could connect fine (we could also connect no problem through sqlplus)? The key to the issue wasn't that we couldn't connect, but that it was intermittent

After some investigation, we found that there was some static data created during the class setup that would keep open connections for the life of the test class, creating new ones as it went. Now, even though all of the resources were properly released when this class went out of scope (via a finally{} block, of course), there were some cases during the run when this class would swallow up all available connections (okay, bad practice alert - this was unit test code that connected directly rather than using a pool, so the same problem could not happen in production).

The fix was to not make that class static and run in the class setup, but instead use it in the per method setUp and tearDown methods.

So if you get this error in your own apps, slap a profiler on that bad boy and see if you might have a connection leak. Hope that helps.

Auto submit form on page load

Add the following to Body tag,

<body onload="document.forms['member_signup'].submit()">

and give name attribute to your Form.

<form method="POST" action="" name="member_signup">

In where shall I use isset() and !empty()

If you have a $_POST['param'] and assume it's string type then

isset($_POST['param']) && $_POST['param'] != '' && $_POST['param'] != '0'

is identical to

!empty($_POST['param'])

What is meant by Ems? (Android TextView)

android:ems or setEms(n) sets the width of a TextView to fit a text of n 'M' letters regardless of the actual text extension and text size. See wikipedia Em unit

but only when the layout_width is set to "wrap_content". Other layout_width values override the ems width setting.

Adding an android:textSize attribute determines the physical width of the view to the textSize * length of a text of n 'M's set above.

Interface vs Abstract Class (general OO)

I think the answer they are looking for is the fundamental or OPPS philosophical difference.

The abstract class inheritance is used when the derived class shares the core properties and behaviour of the abstract class. The kind of behaviour that actually defines the class.

On the other hand interface inheritance is used when the classes share peripheral behaviour, ones which do not necessarily define the derived class.

For eg. A Car and a Truck share a lot of core properties and behaviour of an Automobile abstract class, but they also share some peripheral behaviour like Generate exhaust which even non automobile classes like Drillers or PowerGenerators share and doesn't necessarily defines a Car or a Truck, so Car, Truck, Driller and PowerGenerator can all share the same interface IExhaust.

how to avoid extra blank page at end while printing?

Solution described here helped me (webarchive link).

First of all, you can add border to all elements to see what causes a new page to be appended (maybe some margins, paddings, etc).

div { border: 1px solid black;}

And the solution itself was to add the following styles:

html, body { height: auto; }

How to clear variables in ipython?

An quit option in the Console Panel will also clear all variables in variable explorer

*** Note that you will be loosing all the code which you have run in Console Panel

Open Excel file for reading with VBA without display

Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.

OTHERWISE, possibly GetObject(<filename with path>) is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.

Dim wb As Workbook

Set wb = GetObject("C:\MyData.xlsx")  'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False

If you want to read a particular sheet, need not even define a Workbook variable

Dim sh As Worksheet
Set sh = GetObject("C:\MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook

IIS7 folder permissions for web application

In IIS 7 (not IIS 7.5), sites access files and folders based on the account set on the application pool for the site. By default, in IIS7, this account is NETWORK SERVICE.

Specify an Identity for an Application Pool (IIS 7)

In IIS 7.5 (Windows 2008 R2 and Windows 7), the application pools run under the ApplicationPoolIdentity which is created when the application pool starts. If you want to set ACLS for this account, you need to choose IIS AppPool\ApplicationPoolName instead of NT Authority\Network Service.

Bootstrap 3 Collapse show state with Chevron icon

Angular seems to cause issues with the JavaScript-based approaches here ( at least the ones I've tried ) . I found this solution here: http://www.codeproject.com/Articles/987311/Collapsible-Responsive-Master-Child-Grid-Using-Ang . The gist of it is to use data-ng-click on the toggle button and make the method to change the button in the controller using the $scope context .

I guess I could provide more detail... my buttons are set to the glyphicon of the initial state of the div they collapse ( glyphicon-chevron-right == collapsed div ) .

page.html:

<div class="title-1">
    <button data-toggle="collapse" data-target="#panel-{{ p_idx }}" class="dropdown-toggle title-btn glyphicon glyphicon-chevron-right" data-ng-click="collapse($event)"></button>
</div>
<div id="panel-{{ p_idx }}" class="collapse sect">
    ...
</div>

controllers.js:

.controller('PageController', function($scope, $rootScope) {
    $scope.collapse = function (event) {
        $(event.target).toggleClass("glyphicon-chevron-down glyphicon-chevron-right");
    };
)

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

#include errors detected in vscode

In my case I did not need to close the whole VS-Code, closing the opened file (and sometimes even saving it) solved the issue.

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

I modified the script by Nicolay77 to output the database to stdout (the usual way of unix scripts) so that I could output the data to text file or pipe it to any program I want. The resulting script is a bit simpler and works well.

Some examples:

./mdb_to_mysql.sh database.mdb > data.sql

./mdb_to_mysql.sh database.mdb | mysql destination-db -u user -p

Here is the modified script (save to mdb_to_mysql.sh)

#!/bin/bash
TABLES=$(mdb-tables -1 $1)

for t in $TABLES
do
    echo "DROP TABLE IF EXISTS $t;"
done

mdb-schema $1 mysql

for t in $TABLES
do
    mdb-export -D '%Y-%m-%d %H:%M:%S' -I mysql $1 $t
done

Infinite Recursion with Jackson JSON and Hibernate JPA issue

I'm a late comer and it's such a long thread already. But I spent a couple of hours trying to figure this out too, and would like to give my case as another example.

I tried both JsonIgnore, JsonIgnoreProperties and BackReference solutions, but strangely enough it was like they weren't picked up.

I used Lombok and thought that maybe it interferes, since it creates constructors and overrides toString (saw toString in stackoverflowerror stack).

Finally it wasn't Lombok's fault - I used automatic NetBeans generation of JPA entities from database tables, without giving it much thought - well, and one of the annotations that were added to the generated classes was @XmlRootElement. Once I removed it everything started working. Oh well.

Getting the computer name in Java

I agree with peterh's answer, so for those of you who like to copy and paste instead of 60 more seconds of Googling:

private String getComputerName()
{
    Map<String, String> env = System.getenv();
    if (env.containsKey("COMPUTERNAME"))
        return env.get("COMPUTERNAME");
    else if (env.containsKey("HOSTNAME"))
        return env.get("HOSTNAME");
    else
        return "Unknown Computer";
}

I have tested this in Windows 7 and it works. If peterh was right the else if should take care of Mac and Linux. Maybe someone can test this? You could also implement Brian Roach's answer inside the else if you wanted extra robustness.

How to generate random float number in C

while it might not matter now here is a function which generate a float between 2 values.

#include <math.h>

float func_Uniform(float left, float right) {
    float randomNumber = sin(rand() * rand());
    return left + (right - left) * fabs(randomNumber);
}

Class has no member named

Did you remember to include the closing brace in main?

#include <iostream>
#include "Attack.h"

using namespace std;

int main()
{
  Attack attackObj;
  attackObj.printShiz();
}

How to increment a letter N times per iteration and store in an array?

ord() will not work because your end string is two characters long.

Returns the ASCII value of the first character of string.

Watch it break.

From my testing, you need to check that the end string doesn't get "stepped over". The perl-style character incrementation is a cool method, but it is a single-stepping method. For this reason, an inner loop helps it along when necessary. This is actually not a bother, in fact, it is useful because we need to check if the loop(s) should be broken on each single step.

Code: (Demo)

function excelCols($letter,$end,$step=1){  // function doesn't check that $end is "later" than $letter
    if($step==0)return [];  // prevent infinite loop
    do{
        $letters[]=$letter;  // store letter
        for($x=0; $x<$step; ++$x){  // increment in accordance with $step declaration
            if($letter===$end)break(2);  // break if end is "stepped on"
            ++$letter;
        }
    }while(true);
    return $letters;    
}
echo implode(' ',excelCols('A','JJ',4));
echo "\n --- \n";
echo implode(' ',excelCols('A','BB',3));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',1));
echo "\n --- \n";
echo implode(' ',excelCols('A','ZZ',3));

Output:

A E I M Q U Y AC AG AK AO AS AW BA BE BI BM BQ BU BY CC CG CK CO CS CW DA DE DI DM DQ DU DY EC EG EK EO ES EW FA FE FI FM FQ FU FY GC GG GK GO GS GW HA HE HI HM HQ HU HY IC IG IK IO IS IW JA JE JI
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ
 --- 
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z AA AB AC AD AE AF AG AH AI AJ AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ BA BB BC BD BE BF BG BH BI BJ BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ CA CB CC CD CE CF CG CH CI CJ CK CL CM CN CO CP CQ CR CS CT CU CV CW CX CY CZ DA DB DC DD DE DF DG DH DI DJ DK DL DM DN DO DP DQ DR DS DT DU DV DW DX DY DZ EA EB EC ED EE EF EG EH EI EJ EK EL EM EN EO EP EQ ER ES ET EU EV EW EX EY EZ FA FB FC FD FE FF FG FH FI FJ FK FL FM FN FO FP FQ FR FS FT FU FV FW FX FY FZ GA GB GC GD GE GF GG GH GI GJ GK GL GM GN GO GP GQ GR GS GT GU GV GW GX GY GZ HA HB HC HD HE HF HG HH HI HJ HK HL HM HN HO HP HQ HR HS HT HU HV HW HX HY HZ IA IB IC ID IE IF IG IH II IJ IK IL IM IN IO IP IQ IR IS IT IU IV IW IX IY IZ JA JB JC JD JE JF JG JH JI JJ JK JL JM JN JO JP JQ JR JS JT JU JV JW JX JY JZ KA KB KC KD KE KF KG KH KI KJ KK KL KM KN KO KP KQ KR KS KT KU KV KW KX KY KZ LA LB LC LD LE LF LG LH LI LJ LK LL LM LN LO LP LQ LR LS LT LU LV LW LX LY LZ MA MB MC MD ME MF MG MH MI MJ MK ML MM MN MO MP MQ MR MS MT MU MV MW MX MY MZ NA NB NC ND NE NF NG NH NI NJ NK NL NM NN NO NP NQ NR NS NT NU NV NW NX NY NZ OA OB OC OD OE OF OG OH OI OJ OK OL OM ON OO OP OQ OR OS OT OU OV OW OX OY OZ PA PB PC PD PE PF PG PH PI PJ PK PL PM PN PO PP PQ PR PS PT PU PV PW PX PY PZ QA QB QC QD QE QF QG QH QI QJ QK QL QM QN QO QP QQ QR QS QT QU QV QW QX QY QZ RA RB RC RD RE RF RG RH RI RJ RK RL RM RN RO RP RQ RR RS RT RU RV RW RX RY RZ SA SB SC SD SE SF SG SH SI SJ SK SL SM SN SO SP SQ SR SS ST SU SV SW SX SY SZ TA TB TC TD TE TF TG TH TI TJ TK TL TM TN TO TP TQ TR TS TT TU TV TW TX TY TZ UA UB UC UD UE UF UG UH UI UJ UK UL UM UN UO UP UQ UR US UT UU UV UW UX UY UZ VA VB VC VD VE VF VG VH VI VJ VK VL VM VN VO VP VQ VR VS VT VU VV VW VX VY VZ WA WB WC WD WE WF WG WH WI WJ WK WL WM WN WO WP WQ WR WS WT WU WV WW WX WY WZ XA XB XC XD XE XF XG XH XI XJ XK XL XM XN XO XP XQ XR XS XT XU XV XW XX XY XZ YA YB YC YD YE YF YG YH YI YJ YK YL YM YN YO YP YQ YR YS YT YU YV YW YX YY YZ ZA ZB ZC ZD ZE ZF ZG ZH ZI ZJ ZK ZL ZM ZN ZO ZP ZQ ZR ZS ZT ZU ZV ZW ZX ZY ZZ
 --- 
A D G J M P S V Y AB AE AH AK AN AQ AT AW AZ BC BF BI BL BO BR BU BX CA CD CG CJ CM CP CS CV CY DB DE DH DK DN DQ DT DW DZ EC EF EI EL EO ER EU EX FA FD FG FJ FM FP FS FV FY GB GE GH GK GN GQ GT GW GZ HC HF HI HL HO HR HU HX IA ID IG IJ IM IP IS IV IY JB JE JH JK JN JQ JT JW JZ KC KF KI KL KO KR KU KX LA LD LG LJ LM LP LS LV LY MB ME MH MK MN MQ MT MW MZ NC NF NI NL NO NR NU NX OA OD OG OJ OM OP OS OV OY PB PE PH PK PN PQ PT PW PZ QC QF QI QL QO QR QU QX RA RD RG RJ RM RP RS RV RY SB SE SH SK SN SQ ST SW SZ TC TF TI TL TO TR TU TX UA UD UG UJ UM UP US UV UY VB VE VH VK VN VQ VT VW VZ WC WF WI WL WO WR WU WX XA XD XG XJ XM XP XS XV XY YB YE YH YK YN YQ YT YW YZ ZC ZF ZI ZL ZO ZR ZU ZX

Here is an array-functions approach:

Code: (Demo)

$start='C';
$end='DD';
$step=4;

// generate and store more than we need (this is an obvious method disadvantage)
$result=$array=range('A','Z',1);  // store A - Z as $array and $result
foreach($array as $a){
    foreach($array as $b){
        $result[]="$a$b";  // store double letter combinations
        if(in_array($end,$result)){break(2);}  // stop asap
    }
}
//echo implode(' ',$result),"\n\n";

// slice away from the front of the array
$result=array_slice($result,array_search($start,$result));  // reindex keys
//echo implode(' ',$result),"\n\n";

 // punch out elements that are not "stepped on"
$result=array_filter($result,function($k)use($step){return $k%$step==0;},ARRAY_FILTER_USE_KEY); // use modulo

// result is ready
echo implode(' ',$result);

Output:

C G K O S W AA AE AI AM AQ AU AY BC BG BK BO BS BW CA CE CI CM CQ CU CY DC

Removing an item from a select box

To Remove an Item

$("select#mySelect option[value='option1']").remove(); 

To Add an item

$("#mySelect").append('<option value="option1">Option</option>');

To Check for an option

$('#yourSelect option[value=yourValue]').length > 0;

To remove a selected option

$('#mySelect :selected').remove(); 

Remove border from buttons

$(".myButtonClass").css(["border:none; background-color:white; padding:0"]);

Python Remove last char from string and return it

Strings are "immutable" for good reason: It really saves a lot of headaches, more often than you'd think. It also allows python to be very smart about optimizing their use. If you want to process your string in increments, you can pull out part of it with split() or separate it into two parts using indices:

a = "abc"
a, result = a[:-1], a[-1]

This shows that you're splitting your string in two. If you'll be examining every byte of the string, you can iterate over it (in reverse, if you wish):

for result in reversed(a):
    ...

I should add this seems a little contrived: Your string is more likely to have some separator, and then you'll use split:

ans = "foo,blah,etc."
for a in ans.split(","):
    ...

C# version of java's synchronized keyword?

First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).

For the method-level stuff, there is [MethodImpl]:

[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}

This can also be used on accessors (properties and events):

private int i;
public int SomeProperty
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    get { return i; }
    [MethodImpl(MethodImplOptions.Synchronized)]
    set { i = value; }
}

Note that field-like events are synchronized by default, while auto-implemented properties are not:

public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized

Personally, I don't like the implementation of MethodImpl as it locks this or typeof(Foo) - which is against best practice. The preferred option is to use your own locks:

private readonly object syncLock = new object();
public void SomeMethod() {
    lock(syncLock) { /* code */ }
}

Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this) / lock(Type) - however, in more recent compilers it uses Interlocked updates - so thread-safe without the nasty parts.

This allows more granular usage, and allows use of Monitor.Wait/Monitor.Pulse etc to communicate between threads.

A related blog entry (later revisited).

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

we had this same issue starting this morning and goti it solved... hope this helps...

SSL on IIS 8

  1. Everything was working fine yesterday and last night our SSL was updated on the IIS site.
  2. While checking out the site Bindings to the SSL noticed that IIS8 has a new checkbox Require Server Name Indication, it was not checked so preceded to enable it.
  3. That triggered the problem.
  4. Went back to IIS, disabled the checkbox.... Problem Solved!!!!

Hope this helps!!!

SQL Server SELECT INTO @variable?

I found your question looking for a solution to the same problem; and what other answers fail to point is a way to use a variable to change the name of the table for every execution of your procedure in a permanent form, not temporary.

So far what I do is concatenate the entire SQL code with the variables to use. Like this:

declare @table_name as varchar(30)
select @table_name = CONVERT(varchar(30), getdate(), 112)
set @table_name = 'DAILY_SNAPSHOT_' + @table_name

EXEC('
        SELECT var1, var2, var3
        INTO '+@table_name+'
        FROM my_view
        WHERE string = ''Strings must use double apostrophe''
    ');

I hope it helps, but it could be cumbersome if the code is too large, so if you've found a better way, please share!

Laravel Eloquent "WHERE NOT IN"

$created_po = array();
     $challan = modelname::where('fieldname','!=', 0)->get();
     // dd($challan);
     foreach ($challan as $rec){
         $created_po[] = array_push($created_po,$rec->fieldname);
     }
     $data = modelname::whereNotIn('fieldname',$created_po)->orderBy('fieldname','desc')->with('modelfunction')->get();

Conda command is not recognized on Windows 10

In Windows, you will have to set the path to the location where you installed Anaconda3 to.

For me, I installed anaconda3 into C:\Anaconda3. Therefore you need to add C:\Anaconda3 as well as C:\Anaconda3\Scripts\ to your path variable, e.g. set PATH=%PATH%;C:\Anaconda3;C:\Anaconda3\Scripts\.

You can do this via powershell (see above, https://msdn.microsoft.com/en-us/library/windows/desktop/bb776899(v=vs.85).aspx ), or hit the windows key ? enter environment ? choose from settings ? edit environment variables for your account ? select Path variable ? Edit ? New.

To test it, open a new dos shell, and you should be able to use conda commands now. E.g., try conda --version.

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

Git Cherry-pick vs Merge Workflow

In my opinion cherry-picking should be reserved for rare situations where it is required, for example if you did some fix on directly on 'master' branch (trunk, main development branch) and then realized that it should be applied also to 'maint'. You should base workflow either on merge, or on rebase (or "git pull --rebase").

Please remember that cherry-picked or rebased commit is different from the point of view of Git (has different SHA-1 identifier) than the original, so it is different than the commit in remote repository. (Rebase can usually deal with this, as it checks patch id i.e. the changes, not a commit id).

Also in git you can merge many branches at once: so called octopus merge. Note that octopus merge has to succeed without conflicts. Nevertheless it might be useful.

HTH.

What is the default scope of a method in Java?

The default scope is "default". It's weird--see these references for more info.

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

I had this problem because i was adding bundle and certificate in wrong order so maybe this could help someone else.

Before (which is wrong) :

cat ca_bundle.crt certificate.crt > bundle_chained.crt

After (which is right)

cat certificate.crt ca_bundle.crt > bundle_chained.crt

And Please don't forget to update the appropriate conf (ssl_certificate must now point to the chained crt) as

server {
    listen              443 ssl;
    server_name         www.example.com;
    ssl_certificate     bundle_chained.crt;
    ssl_certificate_key www.example.com.key;
    ...
}

From the nginx manpage:

If the server certificate and the bundle have been concatenated in the wrong order, nginx will fail to start and will display the error message:

SSL_CTX_use_PrivateKey_file(" ... /www.example.com.key") failed
   (SSL: error:0B080074:x509 certificate routines:
    X509_check_private_key:key values mismatch)

What does "Table does not support optimize, doing recreate + analyze instead" mean?

That's really an informational message.

Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).

InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.

The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:

Table does not support optimize is the InnoDB storage engine saying...

"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."

"doing recreate + analyze instead" is the InnoDB storage engine saying...

"I have decided to perform a different set of operations which will achieve an equivalent result."

Why are empty catch blocks a bad idea?

Empty catch blocks are usually put in because the coder doesn't really know what they are doing. At my organization, an empty catch block must include a comment as to why doing nothing with the exception is a good idea.

On a related note, most people don't know that a try{} block can be followed with either a catch{} or a finally{}, only one is required.

if statement checks for null but still throws a NullPointerException

Change Below line

if (str == null | str.length() == 0) {

into

if (str == null || str.isEmpty()) {

now your code will run corectlly. Make sure str.isEmpty() comes after str == null because calling isEmpty() on null will cause NullPointerException. Because of Java uses Short-circuit evaluation when str == null is true it will not evaluate str.isEmpty()

How can I use optional parameters in a T-SQL stored procedure?

This also works:

    ...
    WHERE
        (FirstName IS NULL OR FirstName = ISNULL(@FirstName, FirstName)) AND
        (LastName IS NULL OR LastName = ISNULL(@LastName, LastName)) AND
        (Title IS NULL OR Title = ISNULL(@Title, Title))

How to change the color of a button?

The RIGHT way...

The following methods actually work.

if you wish - using a theme
By default a buttons color is android:colorAccent. So, if you create a style like this...

<style name="Button.White" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@android:color/white</item>
</style>

You can use it like this...

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Button.White"
    />

alternatively - using a tint
You can simply add android:backgroundTint for API Level 21 and higher, or app:backgroundTint for API Level 7 and higher.

For more information, see this blog.

The problem with the accepted answer...

If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.

Add a column to existing table and uniquely number them on MS SQL Server

for oracle you could do something like below

alter table mytable add (myfield integer);

update mytable set myfield = rownum;

How to sum all column values in multi-dimensional array?

For those who landed here and are searching for a solution that merges N arrays AND also sums the values of identical keys found in the N arrays, I've written this function that works recursively as well. (See: https://gist.github.com/Nickology/f700e319cbafab5eaedc)

Example:

$a = array( "A" => "bob", "sum" => 10, "C" => array("x","y","z" => 50) );
$b = array( "A" => "max", "sum" => 12, "C" => array("x","y","z" => 45) );
$c = array( "A" => "tom", "sum" =>  8, "C" => array("x","y","z" => 50, "w" => 1) );

print_r(array_merge_recursive_numeric($a,$b,$c));

Will result in:

Array
(
    [A] => tom
    [sum] => 30
    [C] => Array
        (
            [0] => x
            [1] => y
            [z] => 145
            [w] => 1
        )

)

Here's the code:

<?php 
/**
 * array_merge_recursive_numeric function.  Merges N arrays into one array AND sums the values of identical keys.
 * WARNING: If keys have values of different types, the latter values replace the previous ones.
 * 
 * Source: https://gist.github.com/Nickology/f700e319cbafab5eaedc
 * @params N arrays (all parameters must be arrays)
 * @author Nick Jouannem <[email protected]>
 * @access public
 * @return void
 */
function array_merge_recursive_numeric() {

    // Gather all arrays
    $arrays = func_get_args();

    // If there's only one array, it's already merged
    if (count($arrays)==1) {
        return $arrays[0];
    }

    // Remove any items in $arrays that are NOT arrays
    foreach($arrays as $key => $array) {
        if (!is_array($array)) {
            unset($arrays[$key]);
        }
    }

    // We start by setting the first array as our final array.
    // We will merge all other arrays with this one.
    $final = array_shift($arrays);

    foreach($arrays as $b) {

        foreach($final as $key => $value) {

            // If $key does not exist in $b, then it is unique and can be safely merged
            if (!isset($b[$key])) {

                $final[$key] = $value;

            } else {

                // If $key is present in $b, then we need to merge and sum numeric values in both
                if ( is_numeric($value) && is_numeric($b[$key]) ) {
                    // If both values for these keys are numeric, we sum them
                    $final[$key] = $value + $b[$key];
                } else if (is_array($value) && is_array($b[$key])) {
                    // If both values are arrays, we recursively call ourself
                    $final[$key] = array_merge_recursive_numeric($value, $b[$key]);
                } else {
                    // If both keys exist but differ in type, then we cannot merge them.
                    // In this scenario, we will $b's value for $key is used
                    $final[$key] = $b[$key];
                }

            }

        }

        // Finally, we need to merge any keys that exist only in $b
        foreach($b as $key => $value) {
            if (!isset($final[$key])) {
                $final[$key] = $value;
            }
        }

    }

    return $final;

}

?>

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I've made a short code to do that and I want to share it with you.

Here the main code:

public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{

  MailMessage email = new MailMessage();
  email.From = new MailAddress(from);
  email.To.Add(to);
  email.Subject = subject;
  email.Body = Message;
  SmtpClient smtp = new SmtpClient(host, port);
  smtp.UseDefaultCredentials = false;
  NetworkCredential nc = new NetworkCredential(from, password);
  smtp.Credentials = nc;
  smtp.EnableSsl = true;
  email.IsBodyHtml = true;
  email.Priority = MailPriority.Normal;
  email.BodyEncoding = Encoding.UTF8;

  if (file.Length > 0)
  {
    Attachment attachment;
    attachment = new Attachment(file);
    email.Attachments.Add(attachment);
  }

  // smtp.Send(email);
  smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
  string userstate = "sending ...";
  smtp.SendAsync(email, userstate);
}

private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
  string result = "";
  if (e.Cancelled)
  {    
    MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
  }
  else if (e.Error != null)
  {
    MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }
  else {
    MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
  }

}

In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example

using (OpenFileDialog attachement = new OpenFileDialog()
{
  Filter = "Exel Client|*.png",
  ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
  Send("[email protected]", "gmail_password", 
       "[email protected]", "just smile ", "mail with attachement",
       "smtp.gmail.com", 587, attachement.FileName);

}
}

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Save a list to a .txt file

Try this, if it helps you

values = ['1', '2', '3']

with open("file.txt", "w") as output:
    output.write(str(values))

"Default Activity Not Found" on Android Studio upgrade

In Android Studio 4.0 please change Launch to Nothing:

Run/Debug Configuration -> Android App -> app -> General -> Launch Options -> Launch : Nothing

enter image description here

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

[SOLVED] Neos/swiftmailer: Address in mailbox given [] does not comply with RFC 2822, 3.6.2

Exception in line 261 of /var/www/html/vendor/Packages/Libraries/swiftmailer/swiftmailer/lib/classes/Swift/Mime/Headers/MailboxHeader.php: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

private function _assertValidAddress($address)
{
    if (!preg_match('/^'.$this->getGrammar()->getDefinition('addr-spec').'$/D',
        $address)) {
        throw new Swift_RfcComplianceException(
            'Address in mailbox given ['.$address.
            '] does not comply with RFC 2822, 3.6.2.'
            );
    }
}

https://discuss.neos.io/t/solved-neos-swiftmailer-address-in-mailbox-given-does-not-comply-with-rfc-2822-3-6-2/3012

AngularJS sorting rows by table header

I'm just getting my feet wet with angular, but I found this great tutorial.
Here's a working plunk I put together with credit to Scott Allen and the above tutorial. Click search to display the sortable table.

For each column header you need to make it clickable - ng-click on a link will work. This will set the sortName of the column to sort.

<th>
     <a href="#" ng-click="sortName='name'; sortReverse = !sortReverse">
          <span ng-show="sortName == 'name' && sortReverse" class="glyphicon glyphicon-triangle-bottom"></span>
          <span ng-show="sortName == 'name' && !sortReverse" class="glyphicon glyphicon-triangle-top"></span>
           Name
     </a>
</th>

Then, in the table body you can pipe in that sortName in the orderBy filter orderBy:sortName:sortReverse

<tr ng-repeat="repo in repos | orderBy:sortName:sortReverse | filter:searchRepos">
     <td>{{repo.name}}</td>
     <td class="tag tag-primary">{{repo.stargazers_count | number}}</td>
     <td>{{repo.language}}</td>
</tr>

Store a closure as a variable in Swift

Closures can be declared as typealias as below

typealias Completion = (Bool, Any, Error) -> Void

If you want to use in your function anywhere in code; you can write like normal variable

func xyz(with param1: String, completion: Completion) {
}