Programs & Examples On #Maven nar plugin

The nar-maven-plugin (formerly "maven-nar-plugin") is a Maven plugin that provides a platform-agnostic way of managing native code dependencies of Java projects.

How can I change a file's encoding with vim?

It could be useful to change the encoding just on the command line before the file is read:

rem On MicroSoft Windows
vim --cmd "set encoding=utf-8" file.ext
# In *nix shell
vim --cmd 'set encoding=utf-8' file.ext

See starting, --cmd.

How to terminate a Python script

A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

Example:

#do stuff
if this == that:
  quit()

Find duplicate records in MongoDB

Use aggregation on name and get name with count > 1:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
]);

To sort the results by most to least duplicates:

db.collection.aggregate([
    {"$group" : { "_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"_id" :{ "$ne" : null } , "count" : {"$gt": 1} } }, 
    {"$sort": {"count" : -1} },
    {"$project": {"name" : "$_id", "_id" : 0} }     
]);

To use with another column name than "name", change "$name" to "$column_name"

toBe(true) vs toBeTruthy() vs toBeTrue()

What I do when I wonder something like the question asked here is go to the source.

toBe()

expect().toBe() is defined as:

function toBe() {
  return {
    compare: function(actual, expected) {
      return {
        pass: actual === expected
      };
    }
  };
}

It performs its test with === which means that when used as expect(foo).toBe(true), it will pass only if foo actually has the value true. Truthy values won't make the test pass.

toBeTruthy()

expect().toBeTruthy() is defined as:

function toBeTruthy() {
  return {
    compare: function(actual) {
      return {
        pass: !!actual
      };
    }
  };
}

Type coercion

A value is truthy if the coercion of this value to a boolean yields the value true. The operation !! tests for truthiness by coercing the value passed to expect to a boolean. Note that contrarily to what the currently accepted answer implies, == true is not a correct test for truthiness. You'll get funny things like

> "hello" == true
false
> "" == true
false
> [] == true
false
> [1, 2, 3] == true
false

Whereas using !! yields:

> !!"hello"
true
> !!""
false
> !![1, 2, 3]
true
> !![] 
true

(Yes, empty or not, an array is truthy.)

toBeTrue()

expect().toBeTrue() is part of Jasmine-Matchers (which is registered on npm as jasmine-expect after a later project registered jasmine-matchers first).

expect().toBeTrue() is defined as:

function toBeTrue(actual) {
  return actual === true ||
    is(actual, 'Boolean') &&
    actual.valueOf();
}

The difference with expect().toBeTrue() and expect().toBe(true) is that expect().toBeTrue() tests whether it is dealing with a Boolean object. expect(new Boolean(true)).toBe(true) would fail whereas expect(new Boolean(true)).toBeTrue() would pass. This is because of this funny thing:

> new Boolean(true) === true
false
> new Boolean(true) === false
false

At least it is truthy:

> !!new Boolean(true)
true

Which is best suited for use with elem.isDisplayed()?

Ultimately Protractor hands off this request to Selenium. The documentation states that the value produced by .isDisplayed() is a promise that resolves to a boolean. I would take it at face value and use .toBeTrue() or .toBe(true). If I found a case where the implementation returns truthy/falsy values, I would file a bug report.

How to automatically generate unique id in SQL like UID12345678?

The only viable solution in my opinion is to use

  • an ID INT IDENTITY(1,1) column to get SQL Server to handle the automatic increment of your numeric value
  • a computed, persisted column to convert that numeric value to the value you need

So try this:

CREATE TABLE dbo.tblUsers
  (ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
   UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
   .... your other columns here....
  )

Now, every time you insert a row into tblUsers without specifying values for ID or UserID:

INSERT INTO dbo.tblUsersCol1, Col2, ..., ColN)
VALUES (Val1, Val2, ....., ValN)

then SQL Server will automatically and safely increase your ID value, and UserID will contain values like UID00000001, UID00000002,...... and so on - automatically, safely, reliably, no duplicates.

Update: the column UserID is computed - but it still OF COURSE has a data type, as a quick peek into the Object Explorer reveals:

enter image description here

How to get next/previous record in MySQL?

next:

select * from foo where id = (select min(id) from foo where id > 4)

previous:

select * from foo where id = (select max(id) from foo where id < 4)

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

Are you using express?

Check your path(note the "/" after /public/):

app.use(express.static(__dirname + "/public/"));

//note: you do not need the "/" before "css" because its already included above:

rel="stylesheet" href="css/style.css

Hope this helps

change html input type by JS?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.or/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function changefield(){
    document.getElementById("passwordbox").innerHTML = "<input id=\"passwordfield\" type=\"password\" name=\"password-field\" title=\"Password\" tabindex=\"2\" />";
    document.getElementById("password-field".focus();
}
</script>
</head>

<body>
<div id="passwordbox">
<input id="password-field" type="text" name="password-field" title="Password"onfocus="changefield();" value="Password" tabindex="2" />
</div>
<input type="submit" name="submit" value="sign in" tabindex="3" />

</body>
</html>

How to sum columns in a dataTable?

It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data

var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
                          group b by b.Field<string>("A_GROUP_BY_FIELD") into g
                          select new
                          {
                              tag = g.Key,
                              count = g.Count(),
                              sum = g.Sum(c => c.Field<double>("rvMoney"))
                          };

How to check for file lock?

The other answers rely on old information. This one provides a better solution.

Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked. The Restart Manager API is available beginning with Windows Vista and Windows Server 2008 (Restart Manager: Run-time Requirements).

I put together code that takes the path of a file and returns a List<Process> of all processes that are locking that file.

static public class FileUtil
{
    [StructLayout(LayoutKind.Sequential)]
    struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
    }

    const int RmRebootReasonNone = 0;
    const int CCH_RM_MAX_APP_NAME = 255;
    const int CCH_RM_MAX_SVC_NAME = 63;

    enum RM_APP_TYPE
    {
        RmUnknownApp = 0,
        RmMainWindow = 1,
        RmOtherWindow = 2,
        RmService = 3,
        RmExplorer = 4,
        RmConsole = 5,
        RmCritical = 1000
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct RM_PROCESS_INFO
    {
        public RM_UNIQUE_PROCESS Process;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
        public string strAppName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
        public string strServiceShortName;

        public RM_APP_TYPE ApplicationType;
        public uint AppStatus;
        public uint TSSessionId;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bRestartable;
    }

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
    static extern int RmRegisterResources(uint pSessionHandle,
                                          UInt32 nFiles,
                                          string[] rgsFilenames,
                                          UInt32 nApplications,
                                          [In] RM_UNIQUE_PROCESS[] rgApplications,
                                          UInt32 nServices,
                                          string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    static extern int RmEndSession(uint pSessionHandle);

    [DllImport("rstrtmgr.dll")]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

    /// <summary>
    /// Find out what process(es) have a lock on the specified file.
    /// </summary>
    /// <param name="path">Path of the file.</param>
    /// <returns>Processes locking the file</returns>
    /// <remarks>See also:
    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
    /// 
    /// </remarks>
    static public List<Process> WhoIsLocking(string path)
    {
        uint handle;
        string key = Guid.NewGuid().ToString();
        List<Process> processes = new List<Process>();

        int res = RmStartSession(out handle, 0, key);

        if (res != 0)
            throw new Exception("Could not begin restart session.  Unable to determine file locker.");

        try
        {
            const int ERROR_MORE_DATA = 234;
            uint pnProcInfoNeeded = 0,
                 pnProcInfo = 0,
                 lpdwRebootReasons = RmRebootReasonNone;

            string[] resources = new string[] { path }; // Just checking on one resource.

            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

            if (res != 0) 
                throw new Exception("Could not register resource.");                                    

            //Note: there's a race condition here -- the first call to RmGetList() returns
            //      the total number of process. However, when we call RmGetList() again to get
            //      the actual processes this number may have increased.
            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

            if (res == ERROR_MORE_DATA)
            {
                // Create an array to store the process results
                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                pnProcInfo = pnProcInfoNeeded;

                // Get the list
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);

                if (res == 0)
                {
                    processes = new List<Process>((int)pnProcInfo);

                    // Enumerate all of the results and add them to the 
                    // list to be returned
                    for (int i = 0; i < pnProcInfo; i++)
                    {
                        try
                        {
                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                        }
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    }
                }
                else
                    throw new Exception("Could not list processes locking resource.");                    
            }
            else if (res != 0)
                throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    
        }
        finally
        {
            RmEndSession(handle);
        }

        return processes;
    }
}

UPDATE

Here is another discussion with sample code on how to use the Restart Manager API.

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

Can I export a variable to the environment from a bash script without sourcing it?

Is there any way to access to the $VAR by just executing export.bash without sourcing it ?

Quick answer: No.

But there are several possible workarounds.

The most obvious one, which you've already mentioned, is to use source or . to execute the script in the context of the calling shell:

$ cat set-vars1.sh 
export FOO=BAR
$ . set-vars1.sh 
$ echo $FOO
BAR

Another way is to have the script, rather than setting an environment variable, print commands that will set the environment variable:

$ cat set-vars2.sh
#!/bin/bash
echo export FOO=BAR
$ eval "$(./set-vars2.sh)"
$ echo "$FOO"
BAR

A third approach is to have a script that sets your environment variable(s) internally and then invokes a specified command with that environment:

$ cat set-vars3.sh
#!/bin/bash
export FOO=BAR
exec "$@"
$ ./set-vars3.sh printenv | grep FOO
FOO=BAR

This last approach can be quite useful, though it's inconvenient for interactive use since it doesn't give you the settings in your current shell (with all the other settings and history you've built up).

How do multiple clients connect simultaneously to one port, say 80, on a server?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all". An easy mistake to make is to listen on address 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/dcore/tree/master/apps/quicknet) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

How to set the env variable for PHP?

Follow this for Windows operating system with WAMP installed.

System > Advanced System Settings > Environment Variables
Click new

Variable name  : path
Variable value : c:\wamp\bin\php\php5.3.13\


Click ok

Installing J2EE into existing eclipse IDE

Step 1 Go to Help ---> Install New Software...

Step 2 Try to find "http://download.eclipse.org/webtools/updates" under work with drop down. If you find then select and install all the available updates.

If you can not find then click on Add -> Add Repository. Name: Eclipse Webtools Location: http://download.eclipse.org/webtools/updates Select all available updates and Install them.

Visit http://download.eclipse.org/webtools/updates/ for more details.

Show default value in Spinner in android

Spinner don't support Hint, i recommend you to make a custom spinner adapter.

check this link : https://stackoverflow.com/a/13878692/1725748

How to get an object's property's value by property name?

$com1 = new-object PSobject                                                         #Task1
$com2 = new-object PSobject                                                         #Task1
$com3 = new-object PSobject                                                         #Task1



$com1 | add-member noteproperty -name user -value jindpal                           #Task2
$com1 | add-member noteproperty -name code -value IT01                              #Task2
$com1 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com2 | add-member noteproperty -name user -value singh                             #Task2
$com2 | add-member noteproperty -name code -value IT02                              #Task2
$com2 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}       #Task3


$com3 | add-member noteproperty -name user -value dhanoa                             #Task2
$com3 | add-member noteproperty -name code -value IT03                               #Task2
$com3 | add-member scriptmethod ver {[system.Environment]::oSVersion.Version}        #Task3


$arr += $com1, $com2, $com3                                                          #Task4


write-host "windows version of computer1 is: "$com1.ver()                            #Task3
write-host "user name of computer1 is: "$com1.user                                   #Task6
write-host "code of computer1 is: "$com1,code                                        #Task5
write-host "windows version of computer2 is: "$com2.ver()                            #Task3
write-host "user name of computer2 is: "$com2.user                                   #Task6
write-host "windows version of computer3 is: "$com3.ver()                            #Task3
write-host "user name of computer3 is: "$com1.user                                   #Task6
write-host "code of computer3 is: "$com3,code                                        #Task5

read-host

Matching exact string with JavaScript

Write your regex differently:

var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false

What are some good SSH Servers for windows?

OpenSSH is a contender. Looks like it hasn't been updated in a while though.

It's the de facto choice in my opinion. And yes, running under Cygwin is really the nicest method.

Highcharts - redraw() vs. new Highcharts.chart

chart.series[0].setData(data,true);

The setData method itself will call the redraw method

Using Tkinter in python to edit the title bar

For anybody who runs into the issue of having two windows open, and runs across this question. Here is how I stumbled upon a solution.

The reason the code in this question is producing two windows is because

Frame.__init__(self, parent)

is being run before

self.root = Tk()

The simple fix is to run Tk() before running Frame.__init_()

self.root = Tk()
Frame.__init__(self, parent)

Why that is the case, I'm not entirely sure.

Get protocol + host name from URL

Is there anything wrong with pure string operations:

url = 'http://stackoverflow.com/questions/9626535/get-domain-name-from-url'
parts = url.split('//', 1)
print parts[0]+'//'+parts[1].split('/', 1)[0]
>>> http://stackoverflow.com

If you prefer having a trailing slash appended, extend this script a bit like so:

parts = url.split('//', 1)
base = parts[0]+'//'+parts[1].split('/', 1)[0]
print base + (len(url) > len(base) and url[len(base)]=='/'and'/' or '')

That can probably be optimized a bit ...

The point of test %eax %eax

This checks if EAX is zero. The instruction test does bitwise AND between the arguments, and if EAX contains zero, the result sets the ZF, or ZeroFlag.

Should you commit .gitignore into the Git repos?

You typically do commit .gitignore. In fact, I personally go as far as making sure my index is always clean when I'm not working on something. (git status should show nothing.)

There are cases where you want to ignore stuff that really isn't project specific. For example, your text editor may create automatic *~ backup files, or another example would be the .DS_Store files created by OS X.

I'd say, if others are complaining about those rules cluttering up your .gitignore, leave them out and instead put them in a global excludes file.

By default this file resides in $XDG_CONFIG_HOME/git/ignore (defaults to ~/.config/git/ignore), but this location can be changed by setting the core.excludesfile option. For example:

git config --global core.excludesfile ~/.gitignore

Simply create and edit the global excludesfile to your heart's content; it'll apply to every git repository you work on on that machine.

When to use RSpec let()?

Dissenting voice here: after 5 years of rspec I don't like let very much.

1. Lazy evaluation often makes test setup confusing

It becomes difficult to reason about setup when some things that have been declared in setup are not actually affecting state, while others are.

Eventually, out of frustration someone just changes let to let! (same thing without lazy evaluation) in order to get their spec working. If this works out for them, a new habit is born: when a new spec is added to an older suite and it doesn't work, the first thing the writer tries is to add bangs to random let calls.

Pretty soon all the performance benefits are gone.

2. Special syntax is unusual to non-rspec users

I would rather teach Ruby to my team than the tricks of rspec. Instance variables or method calls are useful everywhere in this project and others, let syntax will only be useful in rspec.

3. The "benefits" allow us to easily ignore good design changes

let() is good for expensive dependencies that we don't want to create over and over. It also pairs well with subject, allowing you to dry up repeated calls to multi-argument methods

Expensive dependencies repeated in many times, and methods with big signatures are both points where we could make the code better:

  • maybe I can introduce a new abstraction that isolates a dependency from the rest of my code (which would mean fewer tests need it)
  • maybe the code under test is doing too much
  • maybe I need to inject smarter objects instead of a long list of primitives
  • maybe I have a violation of tell-don't-ask
  • maybe the expensive code can be made faster (rarer - beware of premature optimisation here)

In all these cases, I can address the symptom of difficult tests with a soothing balm of rspec magic, or I can try address the cause. I feel like I spent way too much of the last few years on the former and now I want some better code.

To answer the original question: I would prefer not to, but I do still use let. I mostly use it to fit in with the style of the rest of the team (it seems like most Rails programmers in the world are now deep into their rspec magic so that is very often). Sometimes I use it when I'm adding a test to some code that I don't have control of, or don't have time to refactor to a better abstraction: i.e. when the only option is the painkiller.

Javascript (+) sign concatenates instead of giving sum of variables

Use only:

divID = "question-" + parseInt(i) + 1;

When "n" comes from html input field or is declared as string, you need to use explicit conversion.

var n = "1"; //type is string
var frstCol = 5;
lstCol = frstCol + parseInt(n);

If "n" is integer, don't need conversion.

n = 1; //type is int
var frstCol = 5, lstCol = frstCol + n;

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

Interesting question! While there are plenty of guides on horizontally and vertically centering a div, an authoritative treatment of the subject where the centered div is of an unpredetermined width is conspicuously absent.

Let's apply some basic constraints:

  • No Javascript
  • No mangling of the display property to table-cell, which is of questionable support status

Given this, my entry into the fray is the use of the inline-block display property to horizontally center the span within an absolutely positioned div of predetermined height, vertically centered within the parent container in the traditional top: 50%; margin-top: -123px fashion.

Markup: div > div > span

CSS:

body > div { position: relative; height: XYZ; width: XYZ; }
div > div { 
  position: absolute;
  top: 50%;
  height: 30px;
  margin-top: -15px; 
  text-align: center;}
div > span { display: inline-block; }

Source: http://jsfiddle.net/38EFb/


An alternate solution that doesn't require extraneous markups but that very likely produces more problems than it solves is to use the line-height property. Don't do this. But it is included here as an academic note: http://jsfiddle.net/gucwW/

Regex to check whether a string contains only numbers

If you want to match the numbers with signed values, you can use:

var reg = new RegExp('^(\-?|\+?)\d*$');

It will validate the numbers of format: +1, -1, 1.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

JavaScript code:

  • on mousedown event: set selectedIndex property value to -1
  • on change event: handle event

The only drawback is that when the user clicks on the dropdown list, the currently selected item does not appear selected

Counting number of lines, words, and characters in a text file

The file pointer is set to the end of the file when the 1st while is executed. try this:

Scanner in = new Scanner(file);


        while(in.hasNext())
        {
            in.next();
            words++;
        }
        in = new Scanner(file);
        while(in.hasNextLine())
        {
            in.nextLine();
            lines++;
        }
        in = new Scanner(file);
        while(in.hasNextByte())
        {
            in.nextByte();
            chars++;
        }

Find all CSV files in a directory using Python

import os
import glob

path = 'c:\\'
extension = 'csv'
os.chdir(path)
result = glob.glob('*.{}'.format(extension))
print(result)

Delete all documents from index/type without deleting type

Starting from Elasticsearch 2.x delete is not anymore allowed, since documents remain in the index causing index corruption.

Why does GitHub recommend HTTPS over SSH?

Maybe because it's harder to steal a password from your brain then to steal a key file from your computer (at least to my knowledge, maybe some substances exist already or methods but this is an infinite discussion)? And if you password protect the key, then you are using a password again and the same problems arise (but some might argue that you have to do more work, because you need to get the key and then crack the password).

how to call a method in another Activity from Activity

Declare a SecondActivity variable in FirstActivity

Like this

public class FirstActivity extends Activity {  

SecondActivity secactivity;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
  }      

  public void method() {
    // some code

  secactivity.call_method();// 'Method' is Name of the any one method in SecondActivity

  }  
}  

Using this format you can call any method from one activity to another.

Missing maven .m2 folder

Is there some command to create this folder?

If smb face this issue again, you should know the most simple way to create .m2 folder.
If you unzipped maven and set up maven path variable - just try mvn clean command from anywhere you like!
Dont be afraid of error messages when running - it works and creates needed directory.

How to trim whitespace from a Bash variable?

This worked for me:

text="   trim my edges    "

trimmed=$text
trimmed=${trimmed##+( )} #Remove longest matching series of spaces from the front
trimmed=${trimmed%%+( )} #Remove longest matching series of spaces from the back

echo "<$trimmed>" #Adding angle braces just to make it easier to confirm that all spaces are removed

#Result
<trim my edges>

To put that on fewer lines for the same result:

text="    trim my edges    "
trimmed=${${text##+( )}%%+( )}

run a python script in terminal without the python command

You use a shebang line at the start of your script:

#!/usr/bin/env python

make the file executable:

chmod +x arbitraryname

and put it in a directory on your PATH (can be a symlink):

cd ~/bin/
ln -s ~/some/path/to/myscript/arbitraryname

apache ProxyPass: how to preserve original IP address

If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.

<Location />            
   ProxyPass http://localhost:1339/ retry=0
   ProxyPassReverse http://localhost:1339/
   ProxyPreserveHost On
   ProxyErrorOverride Off
</Location>

To get the IP address have following options

console.log(">>>", req.ip);// this works fine for me returned a valid ip address 
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address 
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined 
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address 

So either use req.ip or req.headers['x-forwarded-for']

ModelState.IsValid == false, why?

As has just happened to me - this can also happen when you add a required property to your model without updating your form. In this case the ValidationSummary will not list the error message.

Reading string from input with space character?

#include<stdio.h>
int main()
{
   char name[100];
   printf("Enter your name: ");
   scanf("%[^\n]s",name);
   printf("Your Name is: %s",name);
   return 0;
}

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

You should also make sure you have set appropriate Project Facets Java version. Module Properties -> Project Facets -> Java 1.6 should be checked

How to print a specific row of a pandas DataFrame?

If you want to display at row=159220

row=159220

#To display in a table format
display(res.loc[row:row])
display(res.iloc[row:row+1])

#To display in print format
display(res.loc[row])
display(res.iloc[row])

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Spring Boot 2.2.2 / Gradle:

Gradle (build.gradle):

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Entity (User.class):

LocalDate dateOfBirth;

Code:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);

How to detect installed version of MS-Office?

How about HKEY_CLASSES_ROOT\Word.Application\CurVer?

How do I close a tkinter window?

root.destroy will work.
root.quit will also work.

In my case I had

quitButton = Button(frame, text = "Quit", command = root.destroy)

Hope it helps.

Choose File Dialog

I have created FolderLayout which may help you. This link helped me

folderview.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView android:id="@+id/path" android:text="Path"
        android:layout_width="match_parent" android:layout_height="wrap_content"></TextView>
    <ListView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:id="@+id/list"></ListView>

</LinearLayout>

FolderLayout.java

package com.testsample.activity;




   public class FolderLayout extends LinearLayout implements OnItemClickListener {

    Context context;
    IFolderItemListener folderListener;
    private List<String> item = null;
    private List<String> path = null;
    private String root = "/";
    private TextView myPath;
    private ListView lstView;

    public FolderLayout(Context context, AttributeSet attrs) {
        super(context, attrs);

        // TODO Auto-generated constructor stub
        this.context = context;


        LayoutInflater layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.folderview, this);

        myPath = (TextView) findViewById(R.id.path);
        lstView = (ListView) findViewById(R.id.list);

        Log.i("FolderView", "Constructed");
        getDir(root, lstView);

    }

    public void setIFolderItemListener(IFolderItemListener folderItemListener) {
        this.folderListener = folderItemListener;
    }

    //Set Directory for view at anytime
    public void setDir(String dirPath){
        getDir(dirPath, lstView);
    }


    private void getDir(String dirPath, ListView v) {

        myPath.setText("Location: " + dirPath);
        item = new ArrayList<String>();
        path = new ArrayList<String>();
        File f = new File(dirPath);
        File[] files = f.listFiles();

        if (!dirPath.equals(root)) {

            item.add(root);
            path.add(root);
            item.add("../");
            path.add(f.getParent());

        }
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            path.add(file.getPath());
            if (file.isDirectory())
                item.add(file.getName() + "/");
            else
                item.add(file.getName());

        }

        Log.i("Folders", files.length + "");

        setItemList(item);

    }

    //can manually set Item to display, if u want
    public void setItemList(List<String> item){
        ArrayAdapter<String> fileList = new ArrayAdapter<String>(context,
                R.layout.row, item);

        lstView.setAdapter(fileList);
        lstView.setOnItemClickListener(this);
    }


    public void onListItemClick(ListView l, View v, int position, long id) {
        File file = new File(path.get(position));
        if (file.isDirectory()) {
            if (file.canRead())
                getDir(path.get(position), l);
            else {
//what to do when folder is unreadable
                if (folderListener != null) {
                    folderListener.OnCannotFileRead(file);

                }

            }
        } else {

//what to do when file is clicked
//You can add more,like checking extension,and performing separate actions
            if (folderListener != null) {
                folderListener.OnFileClicked(file);
            }

        }
    }

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        // TODO Auto-generated method stub
        onListItemClick((ListView) arg0, arg0, arg2, arg3);
    }

}

And an Interface IFolderItemListener to add what to do when a fileItem is clicked

IFolderItemListener.java

public interface IFolderItemListener {

    void OnCannotFileRead(File file);//implement what to do folder is Unreadable
    void OnFileClicked(File file);//What to do When a file is clicked
}

Also an xml to define the row

row.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowtext" android:layout_width="fill_parent"
    android:textSize="23sp" android:layout_height="match_parent"/>

How to Use in your Application

In your xml,

folders.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent"
    android:orientation="horizontal" android:weightSum="1">
    <com.testsample.activity.FolderLayout android:layout_height="match_parent" layout="@layout/folderview"
        android:layout_weight="0.35"
        android:layout_width="200dp" android:id="@+id/localfolders"></com.testsample.activity.FolderLayout></LinearLayout>

In Your Activity,

SampleFolderActivity.java

public class SampleFolderActivity extends Activity implements IFolderItemListener {

    FolderLayout localFolders;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        localFolders = (FolderLayout)findViewById(R.id.localfolders);
        localFolders.setIFolderItemListener(this);
            localFolders.setDir("./sys");//change directory if u want,default is root   

    }

    //Your stuff here for Cannot open Folder
    public void OnCannotFileRead(File file) {
        // TODO Auto-generated method stub
        new AlertDialog.Builder(this)
        .setIcon(R.drawable.icon)
        .setTitle(
                "[" + file.getName()
                        + "] folder can't be read!")
        .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog,
                            int which) {


                    }
                }).show();

    }


    //Your stuff here for file Click
    public void OnFileClicked(File file) {
        // TODO Auto-generated method stub
        new AlertDialog.Builder(this)
        .setIcon(R.drawable.icon)
        .setTitle("[" + file.getName() + "]")
        .setPositiveButton("OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {


                    }

                }).show();
    }

}

Import the libraries needed. Hope these help you...

How to upgrade pip3?

If you have 2 versions of Python (eg: 2.7.x and 3.6), you need do:

  1. add the path of 2.x to system PATH
  2. add the path of 3.x to system PATH
  3. pip3 install --upgrade pip setuptools wheel

for example, in my .zshrc file:

export PATH=/usr/local/Cellar/python@2/2.7.15/bin:/usr/local/Cellar/python/3.6.5/bin:$PATH

You can exec command pip --version and pip3 --version check the pip from the special version. Because if don't add Python path to $PATH, and exec pip3 install --upgrade pip setuptools wheel, your pip will be changed to pip from python3, but the pip should from python2.x

How to remove all files from directory without removing directory in Node.js

How about run a command line:

require('child_process').execSync('rm -rf /path/to/directory/*')

Make docker use IPv4 for port binding

For CentOS users,

I've got same issue on CentOS7 and setting net.ipv4.ip_forward to 1 solves the issue. Please, refer to Docker Networking Disabled: WARNING: IPv4 forwarding is disabled. Networking will not work for more details.

Python: Importing urllib.quote

urllib went through some changes in Python3 and can now be imported from the parse submodule

>>> from urllib.parse import quote  
>>> quote('"')                      
'%22'                               

Socket.io + Node.js Cross-Origin Request Blocked

I just wanted to say that after trying a bunch of things, what fixed my CORS problem was simply using an older version of socket.io (version 2.2.0). My package.json file now looks like this:

{
  "name": "current-project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "devStart": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "socket.io": "^2.2.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.0"
  }
}


If you execute npm install with this, you may find that the CORS problem goes away when trying to use socket.io. At least it worked for me.

Remove Backslashes from Json Data in JavaScript

You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:

JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);

Understanding .get() method in Python

The get method of a dict (like for example characters) works just like indexing the dict, except that, if the key is missing, instead of raising a KeyError it returns the default value (if you call .get with just one argument, the key, the default value is None).

So an equivalent Python function (where calling myget(d, k, v) is just like d.get(k, v) might be:

def myget(d, k, v=None):
  try: return d[k]
  except KeyError: return v

The sample code in your question is clearly trying to count the number of occurrences of each character: if it already has a count for a given character, get returns it (so it's just incremented by one), else get returns 0 (so the incrementing correctly gives 1 at a character's first occurrence in the string).

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

I use this script

EXEC sp_MSForEachTable ‘ALTER TABLE ? NOCHECK CONSTRAINT ALL’
EXEC sp_MSForEachTable ‘DELETE FROM ?’
EXEC sp_MSForEachTable ‘ALTER TABLE ? CHECK CONSTRAINT ALL’
GO

Using node.js as a simple web server

Is very easy with the tons of libraries presents today. Answers here are functional. If you want another version for start faster and simple

Of course first install node.js. Later:

> # module with zero dependencies
> npm install -g @kawix/core@latest 
> # change /path/to/static with your folder or empty for current
> kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" /path/to/static

Here the content of "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express-static.js" (you don't need download it, i posted for understand how works behind)

// you can use like this:
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" /path/to/static
// kwcore "https://raw.githubusercontent.com/voxsoftware/kawix-core/master/example/npmrequire/express.js" 

// this will download the npm module and make a local cache
import express from 'npm://express@^4.16.4'
import Path from 'path'

var folder= process.argv[2] || "."
folder= Path.resolve(process.cwd(), folder)
console.log("Using folder as public: " + folder)

var app = express() 
app.use(express.static(folder)) 
app.listen(8181)
console.log("Listening on 8181")

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

Named capturing groups in JavaScript regex?

As Tim Pietzcker said ECMAScript 2018 introduces named capturing groups into JavaScript regexes. But what I did not find in the above answers was how to use the named captured group in the regex itself.

you can use named captured group with this syntax: \k<name>. for example

var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/

and as Forivin said you can use captured group in object result as follow:

let result = regexObj.exec('2019-28-06 year is 2019');
// result.groups.year === '2019';
// result.groups.month === '06';
// result.groups.day === '28';

_x000D_
_x000D_
  var regexObj = /(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>/mgi;_x000D_
_x000D_
function check(){_x000D_
    var inp = document.getElementById("tinput").value;_x000D_
    let result = regexObj.exec(inp);_x000D_
    document.getElementById("year").innerHTML = result.groups.year;_x000D_
    document.getElementById("month").innerHTML = result.groups.month;_x000D_
    document.getElementById("day").innerHTML = result.groups.day;_x000D_
}
_x000D_
td, th{_x000D_
  border: solid 2px #ccc;_x000D_
}
_x000D_
<input id="tinput" type="text" value="2019-28-06 year is 2019"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span>Pattern: "(?<year>\d{4})-(?<day>\d{2})-(?<month>\d{2}) year is \k<year>";_x000D_
<br/>_x000D_
<br/>_x000D_
<button onclick="check()">Check!</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>Year</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Month</span>_x000D_
      </th>_x000D_
      <th>_x000D_
        <span>Day</span>_x000D_
      </th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>_x000D_
        <span id="year"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="month"></span>_x000D_
      </td>_x000D_
      <td>_x000D_
        <span id="day"></span>_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Intellij IDEA Java classes not auto compiling on save

Please follow both steps:

1 - Enable Automake from the compiler

  • Press: ctrl + shift + A (For Mac ? + shift + A)
  • Type: make project automatically
  • Hit: Enter
  • Enable Make Project automatically feature

2 - Enable Automake when the application is running

  • Press: ctrl + shift + A (For Mac ? + shift + A)
  • Type: Registry
  • Find the key compiler.automake.allow.when.app.running and enable it or click the checkbox next to it

Note: Restart your application now :)

Note: This should also allow live reload with spring boot devtools.

Confirm button before running deleting routine from website

Call this function onclick of button

/*pass whatever you want instead of id */
function doConfirm(id) {
    var ok = confirm("Are you sure to Delete?");
    if (ok) {
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                window.location = "create_dealer.php";
            }
        }

        xmlhttp.open("GET", "delete_dealer.php?id=" + id);
        // file name where delete code is written
        xmlhttp.send();
    }
}

CASCADE DELETE just once

I wrote a (recursive) function to delete any row based on its primary key. I wrote this because I did not want to create my constraints as "on delete cascade". I wanted to be able to delete complex sets of data (as a DBA) but not allow my programmers to be able to cascade delete without thinking through all of the repercussions. I'm still testing out this function, so there may be bugs in it -- but please don't try it if your DB has multi column primary (and thus foreign) keys. Also, the keys all have to be able to be represented in string form, but it could be written in a way that doesn't have that restriction. I use this function VERY SPARINGLY anyway, I value my data too much to enable the cascading constraints on everything. Basically this function is passed in the schema, table name, and primary value (in string form), and it will start by finding any foreign keys on that table and makes sure data doesn't exist-- if it does, it recursively calls itsself on the found data. It uses an array of data already marked for deletion to prevent infinite loops. Please test it out and let me know how it works for you. Note: It's a little slow. I call it like so: select delete_cascade('public','my_table','1');

create or replace function delete_cascade(p_schema varchar, p_table varchar, p_key varchar, p_recursion varchar[] default null)
 returns integer as $$
declare
    rx record;
    rd record;
    v_sql varchar;
    v_recursion_key varchar;
    recnum integer;
    v_primary_key varchar;
    v_rows integer;
begin
    recnum := 0;
    select ccu.column_name into v_primary_key
        from
        information_schema.table_constraints  tc
        join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
        and tc.constraint_type='PRIMARY KEY'
        and tc.table_name=p_table
        and tc.table_schema=p_schema;

    for rx in (
        select kcu.table_name as foreign_table_name, 
        kcu.column_name as foreign_column_name, 
        kcu.table_schema foreign_table_schema,
        kcu2.column_name as foreign_table_primary_key
        from information_schema.constraint_column_usage ccu
        join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema 
        join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
        join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
        join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
        where ccu.table_name=p_table  and ccu.table_schema=p_schema
        and TC.CONSTRAINT_TYPE='FOREIGN KEY'
        and tc2.constraint_type='PRIMARY KEY'
)
    loop
        v_sql := 'select '||rx.foreign_table_primary_key||' as key from '||rx.foreign_table_schema||'.'||rx.foreign_table_name||'
            where '||rx.foreign_column_name||'='||quote_literal(p_key)||' for update';
        --raise notice '%',v_sql;
        --found a foreign key, now find the primary keys for any data that exists in any of those tables.
        for rd in execute v_sql
        loop
            v_recursion_key=rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name||'='||rd.key;
            if (v_recursion_key = any (p_recursion)) then
                --raise notice 'Avoiding infinite loop';
            else
                --raise notice 'Recursing to %,%',rx.foreign_table_name, rd.key;
                recnum:= recnum +delete_cascade(rx.foreign_table_schema::varchar, rx.foreign_table_name::varchar, rd.key::varchar, p_recursion||v_recursion_key);
            end if;
        end loop;
    end loop;
    begin
    --actually delete original record.
    v_sql := 'delete from '||p_schema||'.'||p_table||' where '||v_primary_key||'='||quote_literal(p_key);
    execute v_sql;
    get diagnostics v_rows= row_count;
    --raise notice 'Deleting %.% %=%',p_schema,p_table,v_primary_key,p_key;
    recnum:= recnum +v_rows;
    exception when others then recnum=0;
    end;

    return recnum;
end;
$$
language PLPGSQL;

Javascript Regular Expression Remove Spaces

I would recommend you use the literal notation, and the \s character class:

//..
return str.replace(/\s/g, '');
//..

There's a difference between using the character class \s and just ' ', this will match a lot more white-space characters, for example '\t\r\n' etc.., looking for ' ' will replace only the ASCII 32 blank space.

The RegExp constructor is useful when you want to build a dynamic pattern, in this case you don't need it.

Moreover, as you said, "[\s]+" didn't work with the RegExp constructor, that's because you are passing a string, and you should "double escape" the back-slashes, otherwise they will be interpreted as character escapes inside the string (e.g.: "\s" === "s" (unknown escape)).

How to find if directory exists in Python

os provides you with a lot of these capabilities:

import os
os.path.isdir(dir_in) #True/False: check if this is a directory
os.listdir(dir_in)    #gets you a list of all files and directories under dir_in

the listdir will throw an exception if the input path is invalid.

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

How do I connect to an MDF database file?

Add space between Data Source

 con.ConnectionString = @"Data Source=.\SQLEXPRESS;
                          AttachDbFilename=c:\folder\SampleDatabase.mdf;
                          Integrated Security=True;
                          Connect Timeout=30;
                          User Instance=True";

Constraint Layout Vertical Align Center

I also had a requirement something similar to it. I wanted to have a container in the center of the screen and inside the container there are many views. Following is the xml layout code. Here i'm using nested constraint layout to create container in the center of the screen.

    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
tools:context=".activities.AppInfoActivity">

<ImageView
    android:id="@+id/ivClose"
    android:layout_width="30dp"
    android:layout_height="30dp"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp"
    android:src="@drawable/ic_round_close_24"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="300dp"
    android:layout_height="300dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.5">

    <ImageView
        android:id="@+id/ivAppIcon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/dead" />

    <TextView
        android:id="@+id/tvAppName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Birds Shooter Plane"
        android:textAlignment="center"
        android:textSize="30sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/ivAppIcon" />

    <TextView
        android:id="@+id/tvAppVersion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Version : 1.0"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvAppName" />

    <TextView
        android:id="@+id/tvDevelopedBy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="Developed by"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvAppVersion" />

    <TextView
        android:id="@+id/tvDevelopedName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="K Pradeep Kumar Reddy"
        android:textAlignment="center"
        android:textSize="14sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDevelopedBy" />

    <TextView
        android:id="@+id/tvContact"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Contact : [email protected]"
        android:textAlignment="center"
        android:textSize="12sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvDevelopedName" />

    <TextView
        android:id="@+id/tvCheckForUpdate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:text="@string/check_for_update"
        android:textAlignment="center"
        android:textSize="14sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvContact" />
</androidx.constraintlayout.widget.ConstraintLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Here is the screenshot of the layout enter image description here

Other solution is to remove the nested constraint layout and add constraint_vertical_bias = 0.5 attribute to the top element in the center of layout. I think this is called as chaining of views.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/gradient_background"
tools:context=".activities.AppInfoActivity">

<ImageView
android:id="@+id/ivClose"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:src="@drawable/ic_round_close_24"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/ivAppIcon"
android:layout_width="100dp"
android:layout_height="100dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.5"
app:srcCompat="@drawable/dead" />

<TextView
android:id="@+id/tvAppName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_display_name"
android:textAlignment="center"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivAppIcon" />

<TextView
android:id="@+id/tvAppVersion"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/version"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppName" />

<TextView
android:id="@+id/tvDevelopedBy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="@string/developed_by"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvAppVersion" />

<TextView
android:id="@+id/tvDevelopedName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/developer_name"
android:textAlignment="center"
android:textSize="14sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedBy" />

<TextView
android:id="@+id/tvContact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:text="@string/developer_email"
android:textAlignment="center"
android:textSize="12sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvDevelopedName" />
<TextView
android:id="@+id/tvCheckForUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:text="@string/check_for_update"
android:textAlignment="center"
android:textSize="14sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvContact" />
</androidx.constraintlayout.widget.ConstraintLayout>

Here is the screenshot of the layout enter image description here

How to change context root of a dynamic web project in Eclipse?

In the java project, open .settings folder. there locate the file named "org.eclipse.wst.common.component" . Change tag <wb-module deploy-name="NEW_NAME"> .

Also you may want to change context root in project properties

Received an invalid column length from the bcp client for colid 6

I know this post is old but I ran into this same issue and finally figured out a solution to determine which column was causing the problem and report it back as needed. I determined that colid returned in the SqlException is not zero based so you need to subtract 1 from it to get the value. After that it is used as the index of the _sortedColumnMappings ArrayList of the SqlBulkCopy instance not the index of the column mappings that were added to the SqlBulkCopy instance. One thing to note is that SqlBulkCopy will stop on the first error received so this may not be the only issue but at least helps to figure it out.

try
{
    bulkCopy.WriteToServer(importTable);
    sqlTran.Commit();
}    
catch (SqlException ex)
{
    if (ex.Message.Contains("Received an invalid column length from the bcp client for colid"))
    {
        string pattern = @"\d+";
        Match match = Regex.Match(ex.Message.ToString(), pattern);
        var index = Convert.ToInt32(match.Value) -1;

        FieldInfo fi = typeof(SqlBulkCopy).GetField("_sortedColumnMappings", BindingFlags.NonPublic | BindingFlags.Instance);
        var sortedColumns = fi.GetValue(bulkCopy);
        var items = (Object[])sortedColumns.GetType().GetField("_items", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sortedColumns);

        FieldInfo itemdata = items[index].GetType().GetField("_metadata", BindingFlags.NonPublic | BindingFlags.Instance);
        var metadata = itemdata.GetValue(items[index]);

        var column = metadata.GetType().GetField("column", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        var length = metadata.GetType().GetField("length", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(metadata);
        throw new DataFormatException(String.Format("Column: {0} contains data with a length greater than: {1}", column, length));
    }

    throw;
}

What is declarative programming?

It may sound odd, but I'd add Excel (or any spreadsheet really) to the list of declarative systems. A good example of this is given here.

jQuery select option elements by value

With jQuery > 1.6.1 should be better to use this syntax:

$('#span_id select option[value="' + some_value + '"]').prop('selected', true);

How to get URL parameter using jQuery or plain JavaScript?

_x000D_
_x000D_
function GetRequestParam(param)_x000D_
{_x000D_
 var res = null;_x000D_
 try{_x000D_
  var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI_x000D_
  var ar = qs.split('&');_x000D_
  $.each(ar, function(a, b){_x000D_
   var kv = b.split('=');_x000D_
   if(param === kv[0]){_x000D_
    res = kv[1];_x000D_
    return false;//break loop_x000D_
   }_x000D_
  });_x000D_
 }catch(e){}_x000D_
 return res;_x000D_
}
_x000D_
_x000D_
_x000D_

Get Max value from List<myType>

Simplest is actually just Age.Max(), you don't need any more code.

EPPlus - Read Excel Table

There is no native but what if you use what I put in this post:

How to parse excel rows back to types using EPPlus

If you want to point it at a table only it will need to be modified. Something like this should do it:

public static IEnumerable<T> ConvertTableToObjects<T>(this ExcelTable table) where T : new()
{
    //DateTime Conversion
    var convertDateTime = new Func<double, DateTime>(excelDate =>
    {
        if (excelDate < 1)
            throw new ArgumentException("Excel dates cannot be smaller than 0.");

        var dateOfReference = new DateTime(1900, 1, 1);

        if (excelDate > 60d)
            excelDate = excelDate - 2;
        else
            excelDate = excelDate - 1;
        return dateOfReference.AddDays(excelDate);
    });

    //Get the properties of T
    var tprops = (new T())
        .GetType()
        .GetProperties()
        .ToList();

    //Get the cells based on the table address
    var start = table.Address.Start;
    var end = table.Address.End;
    var cells = new List<ExcelRangeBase>();

    //Have to use for loops insteadof worksheet.Cells to protect against empties
    for (var r = start.Row; r <= end.Row; r++)
        for (var c = start.Column; c <= end.Column; c++)
            cells.Add(table.WorkSheet.Cells[r, c]);

    var groups = cells
        .GroupBy(cell => cell.Start.Row)
        .ToList();

    //Assume the second row represents column data types (big assumption!)
    var types = groups
        .Skip(1)
        .First()
        .Select(rcell => rcell.Value.GetType())
        .ToList();

    //Assume first row has the column names
    var colnames = groups
        .First()
        .Select((hcell, idx) => new { Name = hcell.Value.ToString(), index = idx })
        .Where(o => tprops.Select(p => p.Name).Contains(o.Name))
        .ToList();

    //Everything after the header is data
    var rowvalues = groups
        .Skip(1) //Exclude header
        .Select(cg => cg.Select(c => c.Value).ToList());

    //Create the collection container
    var collection = rowvalues
        .Select(row =>
        {
            var tnew = new T();
            colnames.ForEach(colname =>
            {
                //This is the real wrinkle to using reflection - Excel stores all numbers as double including int
                var val = row[colname.index];
                var type = types[colname.index];
                var prop = tprops.First(p => p.Name == colname.Name);

                //If it is numeric it is a double since that is how excel stores all numbers
                if (type == typeof(double))
                {
                    if (!string.IsNullOrWhiteSpace(val?.ToString()))
                    {
                        //Unbox it
                        var unboxedVal = (double)val;

                        //FAR FROM A COMPLETE LIST!!!
                        if (prop.PropertyType == typeof(Int32))
                            prop.SetValue(tnew, (int)unboxedVal);
                        else if (prop.PropertyType == typeof(double))
                            prop.SetValue(tnew, unboxedVal);
                        else if (prop.PropertyType == typeof(DateTime))
                            prop.SetValue(tnew, convertDateTime(unboxedVal));
                        else
                            throw new NotImplementedException(String.Format("Type '{0}' not implemented yet!", prop.PropertyType.Name));
                    }
                }
                else
                {
                    //Its a string
                    prop.SetValue(tnew, val);
                }
            });

            return tnew;
        });


    //Send it back
    return collection;
}

Here is a test method:

[TestMethod]
public void Table_To_Object_Test()
{
    //Create a test file
    var fi = new FileInfo(@"c:\temp\Table_To_Object.xlsx");

    using (var package = new ExcelPackage(fi))
    {
        var workbook = package.Workbook;
        var worksheet = workbook.Worksheets.First();
        var ThatList = worksheet.Tables.First().ConvertTableToObjects<ExcelData>();
        foreach (var data in ThatList)
        {
            Console.WriteLine(data.Id + data.Name + data.Gender);
        }

        package.Save();
    }
}

Gave this in the console:

1JohnMale
2MariaFemale
3DanielUnknown

Just be careful if you Id field is an number or string in excel since the class is expecting a string.

How to access command line arguments of the caller inside a function?

One can do it like this as well

#!/bin/bash
# script_name function_test.sh
function argument(){
for i in $@;do
    echo $i
done;
}
argument $@

Now call your script like

./function_test.sh argument1 argument2

android - listview get item view by position

You can get only visible View from ListView because row views in ListView are reuseable. If you use mListView.getChildAt(0) you get first visible view. This view is associated with item from adapter at position mListView.getFirstVisiblePosition().

How can I check if a URL exists via PHP?

Here is a solution that reads only the first byte of source code... returning false if the file_get_contents fails... This will also work for remote files like images.

 function urlExists($url)
{
    if (@file_get_contents($url,false,NULL,0,1))
    {
        return true;
    }
    return false;
}

max value of integer

In C, the language itself does not determine the representation of certain datatypes. It can vary from machine to machine, on embedded systems the int can be 16 bit wide, though usually it is 32 bit.

The only requirement is that short int <= int <= long int by size. Also, there is a recommendation that int should represent the native capacity of the processor.

All types are signed. The unsigned modifier allows you to use the highest bit as part of the value (otherwise it is reserved for the sign bit).

Here's a short table of the possible values for the possible data types:

          width                     minimum                         maximum
signed    8 bit                        -128                            +127
signed   16 bit                     -32 768                         +32 767
signed   32 bit              -2 147 483 648                  +2 147 483 647
signed   64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807
unsigned  8 bit                           0                            +255
unsigned 16 bit                           0                         +65 535
unsigned 32 bit                           0                  +4 294 967 295
unsigned 64 bit                           0     +18 446 744 073 709 551 615

In Java, the Java Language Specification determines the representation of the data types.

The order is: byte 8 bits, short 16 bits, int 32 bits, long 64 bits. All of these types are signed, there are no unsigned versions. However, bit manipulations treat the numbers as they were unsigned (that is, handling all bits correctly).

The character data type char is 16 bits wide, unsigned, and holds characters using UTF-16 encoding (however, it is possible to assign a char an arbitrary unsigned 16 bit integer that represents an invalid character codepoint)

          width                     minimum                         maximum

SIGNED
byte:     8 bit                        -128                            +127
short:   16 bit                     -32 768                         +32 767
int:     32 bit              -2 147 483 648                  +2 147 483 647
long:    64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807

UNSIGNED
char     16 bit                           0                         +65 535

Ascending and Descending Number Order in java

you can make two function one for Ascending and another for Descending the next two functions work after convert array to List

public List<Integer> sortDescending(List<Integer> arr){
    Comparator<Integer> c = Collections.reverseOrder();
    Collections.sort(arr,c);
    return arr;
  }

next function

public List<Integer> sortAscending(List<Integer> arr){   
    Collections.sort(arr);
    return arr;
  }

Git copy changes from one branch to another

Merge the changes from BranchA to BranchB. When you are on BranchB execute git merge BranchA

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

You can first insert data into blob field and then copy to text field with the folloing function

CREATE OR REPLACE FUNCTION blob2text() RETURNS void AS $$
Declare
    ref record;
    i integer;
Begin
    FOR ref IN SELECT id, blob_field FROM table LOOP

          --  find 0x00 and replace with space    
      i := position(E'\\000'::bytea in ref.blob_field);
      WHILE i > 0 LOOP
        ref.bob_field := set_byte(ref.blob_field, i-1, 20);
        i := position(E'\\000'::bytea in ref.blobl_field);
      END LOOP

    UPDATE table SET field = encode(ref.blob_field, 'escape') WHERE id = ref.id;
    END LOOP;

End; $$ LANGUAGE plpgsql; 

--

SELECT blob2text();

Resize image proportionally with CSS?

To resize the image proportionally using CSS:

img.resize {
    width:540px; /* you can use % */
    height: auto;
}

C++ printing boolean, what is displayed?

The standard streams have a boolalpha flag that determines what gets displayed -- when it's false, they'll display as 0 and 1. When it's true, they'll display as false and true.

There's also an std::boolalpha manipulator to set the flag, so this:

#include <iostream>
#include <iomanip>

int main() {
    std::cout<<false<<"\n";
    std::cout << std::boolalpha;   
    std::cout<<false<<"\n";
    return 0;
}

...produces output like:

0
false

For what it's worth, the actual word produced when boolalpha is set to true is localized--that is, <locale> has a num_put category that handles numeric conversions, so if you imbue a stream with the right locale, it can/will print out true and false as they're represented in that locale. For example,

#include <iostream>
#include <iomanip>
#include <locale>

int main() {
    std::cout.imbue(std::locale("fr"));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

...and at least in theory (assuming your compiler/standard library accept "fr" as an identifier for "French") it might print out faux instead of false. I should add, however, that real support for this is uneven at best--even the Dinkumware/Microsoft library (usually quite good in this respect) prints false for every language I've checked.

The names that get used are defined in a numpunct facet though, so if you really want them to print out correctly for particular language, you can create a numpunct facet to do that. For example, one that (I believe) is at least reasonably accurate for French would look like this:

#include <array>
#include <string>
#include <locale>
#include <ios>
#include <iostream>

class my_fr : public std::numpunct< char > {
protected:
    char do_decimal_point() const { return ','; }
    char do_thousands_sep() const { return '.'; }
    std::string do_grouping() const { return "\3"; }
    std::string do_truename() const { return "vrai";  }
    std::string do_falsename() const { return "faux"; }
};

int main() {
    std::cout.imbue(std::locale(std::locale(), new my_fr));

    std::cout << false << "\n";
    std::cout << std::boolalpha;
    std::cout << false << "\n";
    return 0;
}

And the result is (as you'd probably expect):

0
faux

How to set UICollectionViewCell Width and Height programmatically

Size ratio according to iPhone size :

Here's what you can do to have different width and height for cell's regarding the iPhone size :

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let width = (self.view.frame.size.width - 12 * 3) / 3 //some width
    let height = width * 1.5 //ratio
    return CGSize(width: width, height: height)
}

And maybe you should also disable your AutoLayout constraints on cell for this answer to work.

Highlighting Text Color using Html.fromHtml() in Android?

font is deprecated use span instead Html.fromHtml("<span style=color:red>"+content+"</span>")

Problems with Android Fragment back stack

If you are Struggling with addToBackStack() & popBackStack() then simply use

FragmentTransaction ft =getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, new HomeFragment(), "Home");
ft.commit();`

In your Activity In OnBackPressed() find out fargment by tag and then do your stuff

Fragment home = getSupportFragmentManager().findFragmentByTag("Home");

if (home instanceof HomeFragment && home.isVisible()) {
    // do you stuff
}

For more Information https://github.com/DattaHujare/NavigationDrawer I never use addToBackStack() for handling fragment.

How to add click event to a iframe with JQuery

None of the suggested answers worked for me. I solved a similar case the following way:

<a href="http://my-target-url.com" id="iframe-wrapper"></a>
<iframe id="iframe_id" src="http://something.com" allowtrancparency="yes" frameborder="o"></iframe>

The css (of course exact positioning should change according to the app requirements):

#iframe-wrapper, iframe#iframe_id {
  width: 162px;
  border: none;
  height: 21px;
  position: absolute;
  top: 3px;
  left: 398px;
}
#alerts-wrapper {
  z-index: 1000;
}

Of course now you can catch any event on the iframe-wrapper.

Ternary operators in JavaScript without an "else"

In your case i see the ternary operator as redundant. You could assign the variable directly to the expression, using ||, && operators.

!defaults.slideshowWidth ? defaults.slideshowWidth = obj.find('img').width()+'px' : null ;

will become :

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

It's more clear, it's more "javascript" style.

Working with time DURATION, not time of day

Highlight the cell(s)/column which you want as Duration, right click on the mouse to "Format Cells". Go to "Custom" and look for "h:mm" if you want to input duration in hour and minutes format. If you want to include seconds as well, click on "h:mm:ss". You can even add up the total duration after that.

Hope this helps.

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

We can use ng-src but when ng-src's value became null, '' or undefined, ng-src will not work. So just use ng-if for this case:

http://jsfiddle.net/Hx7B9/299/

<div ng-app>
    <div ng-controller="AppCtrl"> 
        <a href='#'><img ng-src="{{link}}" ng-if="!!link"/></a>
        <button ng-click="changeLink()">Change Image</button>
    </div>
</div>

How to save a list as numpy array in python?

You can use numpy.asarray, for example to convert a list into an array:

>>> a = [1, 2]
>>> np.asarray(a)
array([1, 2])

How to get the server path to the web directory in Symfony2 from inside the controller?

For Symfony3 In your controller try

$request->server->get('DOCUMENT_ROOT').$request->getBasePath()

C# switch on type

I did it one time with a workaround, hope it helps.

string fullName = typeof(MyObj).FullName;

switch (fullName)
{
    case "fullName1":
    case "fullName2":
    case "fullName3":
}

Find closing HTML tag in Sublime Text

Try Emmet plug-in command Go To Matching Pair:

http://docs.emmet.io/actions/go-to-pair/

Shortcut (Mac): Shift + Control + T

Shortcut (PC): Control + Alt + J

https://github.com/sergeche/emmet-sublime#available-actions

How to cherry pick a range of commits and merge into another branch?

Assume that you have 2 branches,

"branchA" : includes commits you want to copy (from "commitA" to "commitB"

"branchB" : the branch you want the commits to be transferred from "branchA"

1)

 git checkout <branchA>

2) get the IDs of "commitA" and "commitB"

3)

git checkout <branchB>

4)

git cherry-pick <commitA>^..<commitB>

5) In case you have a conflict, solve it and type

git cherry-pick --continue

to continue the cherry-pick process.

Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean

The scheduling guide isn't a web app so you probably have some mouldy stuff in your pom.xml from the REST guide? If you follow the instructions closely it should work. Another potential issue with the code you posted above is that your @EnableAutoConfiguration class is not used in the context, only as a main method (which may not be a problem for the scheduling guide but it probably is for a bunch of others).

How to get and set the current web page scroll position?

You're looking for the document.documentElement.scrollTop property.

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

When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.

So, by convention, you use the angle brackets for standard includes and the double quotes for everything else. This ensures that in the (not recommended) case in which you have a local header with the same name as a standard header, the right one will be chosen in each case.

Excel CSV. file with more than 1,048,576 rows of data

First you want to change the file format from csv to txt. That is simple to do, just edit the file name and change csv to txt. (Windows will give you warning about possibly corrupting the data, but it is fine, just click ok). Then make a copy of the txt file so that now you have two files both with 2 millions rows of data. Then open up the first txt file and delete the second million rows and save the file. Then open the second txt file and delete the first million rows and save the file. Now change the two files back to csv the same way you changed them to txt originally.

PHP: Show yes/no confirmation dialog

Try this:

<td>
    <a onclick="return confirm(\'Are you sure?\');" href="'.base_url('category/delete_category/'.$row->category_id).'" class="btn btn-danger btn-sm"><i class="fa fa-trash"></i> Delete Coupon</a>
</td>

How to create a HTML Table from a PHP array?

You may use this function. To add table header you can setup a second parameter $myTableArrayHeader and do the same with the header information in front of the body:

function insertTable($myTableArrayBody) {
    $x = 0;
    $y = 0;
    $seTableStr = '<table><tbody>';
    while (isset($myTableArrayBody[$y][$x])) {
        $seTableStr .= '<tr>';
        while (isset($myTableArrayBody[$y][$x])) {
            $seTableStr .= '<td>' . $myTableArrayBody[$y][$x] . '</td>';
            $x++;
        }
        $seTableStr .= '</tr>';
        $x = 0;
        $y++;
    }
    $seTableStr .= '</tbody></table>';
    return $seTableStr;
}

ORA-28000: the account is locked error getting frequently

Here other solution to only unlock the blocked user. From your command prompt log as SYSDBA:

sqlplus "/ as sysdba"

Then type the following command:

alter user <your_username> account unlock;

JQuery .on() method with multiple event handlers to one selector

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});

How to make a window always stay on top in .Net?

Here is the SetForegroundWindow equivalent:

form.Activate();

I have seen people doing weird things like:

this.TopMost = true;
this.Focus();
this.BringToFront();
this.TopMost = false;

http://blog.jorgearimany.com/2010/10/win32-setforegroundwindow-equivalent-in.html

jquery change class name

You can do This : $("#td_id").removeClass('Old_class'); $("#td_id").addClass('New_class'); Or You can do This

$("#td_id").removeClass('Old_class').addClass('New_class');

Best way to style a TextBox in CSS

You can use:

input[type=text]
{
 /*Styles*/
}

Define your common style attributes inside this. and for extra style you can add a class then.

How to launch PowerShell (not a script) from the command line

If you go to C:\Windows\system32\Windowspowershell\v1.0 (and C:\Windows\syswow64\Windowspowershell\v1.0 on x64 machines) in Windows Explorer and double-click powershell.exe you will see that it opens PowerShell with a black background. The PowerShell console shows up as blue when opened from the start menu because the console properties for shortcuts to powershell.exe can be set independently from the default properties.

To set the default options, font, colors and layout, open a PowerShell console, type Alt-Space, and select the Defaults menu option.

Running start powershell from cmd.exe should start a new console with your default settings.

How do I get class name in PHP?

It looks like ReflectionClass is a pretty productive option.

class MyClass {
    public function test() {
        // 'MyClass'
        return (new \ReflectionClass($this))->getShortName();
    }
}

Benchmark:

Method Name      Iterations    Average Time      Ops/second
--------------  ------------  --------------    -------------
testExplode   : [10,000    ] [0.0000020221710] [494,518.01547]
testSubstring : [10,000    ] [0.0000017177343] [582,162.19968]
testReflection: [10,000    ] [0.0000015984058] [625,623.34059]

Convert JSON String to Pretty Print JSON output using Jackson

Since jackson-databind:2.10 JsonNode has the toPrettyString() method to easily format JSON:

objectMapper
  .readTree("{}")
  .toPrettyString()
;

From the docs:

public String toPrettyString()

Alternative to toString() that will serialize this node using Jackson default pretty-printer.

Since:
2.10

SQL string value spanning multiple lines in query

I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:

string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
   *
FROM
   tableA
WHERE
   Name = '{0}' AND
   Gender = '{1}'", name, gender);

It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting

HTML5 validation when the input type is not "submit"

The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.

However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.checkValidity()) {
    f.submit();
  } else {
    alert(document.getElementById('example').validationMessage);
  }
}

How to return data from PHP to a jQuery ajax call

It's an argument passed to your success function:

$.ajax({
  type: "POST",
  url: "somescript.php",
  datatype: "html",
  data: dataString,
  success: function(data) {
    alert(data);
    }
});

The full signature is success(data, textStatus, XMLHttpRequest), but you can use just he first argument if it's a simple string coming back. As always, see the docs for a full explanation :)

How to clear the entire array?

Find a better use for myself: I usually test if a variant is empty, and all of the above methods fail with the test. I found that you can actually set a variant to empty:

Dim aTable As Variant
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
If IsEmpty(aTable) Then
    'This is False
End If
ReDim aTable(2)
aTable = Empty
If IsEmpty(aTable) Then
    'This is true
End If
ReDim aTable(2)
Erase aTable
If IsEmpty(aTable) Then
    'This is False
End If

this way i get the behaviour i want

Creating a URL in the controller .NET MVC

Another way to create an absolute URL to an action:

var relativeUrl = Url.Action("MyAction");  //..or one of the other .Action() overloads
var currentUrl = Request.Url;

var absoluteUrl = new System.Uri(currentUrl, relativeUrl);

Is there any way I can define a variable in LaTeX?

Use \def command:

\def \variable {Something that's better to use as a variable}

Be aware that \def overrides preexisting macros without any warnings and therefore can cause various subtle errors. To overcome this either use namespaced variables like my_var or fall back to \newcommand, \renewcommand commands instead.

What are the differences between Mustache.js and Handlebars.js?

Another difference between them is the size of the file:

To see the performance benefits of Handlebars.js we must use precompiled templates.

Source: An Overview of JavaScript Templating Engines

AngularJs $http.post() does not send data

Add this in your js file:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

and add this to your server file:

$params = json_decode(file_get_contents('php://input'), true);

That should work.

Is there a foreach loop in Go?

https://golang.org/ref/spec#For_range

A "for" statement with a "range" clause iterates through all entries of an array, slice, string or map, or values received on a channel. For each entry it assigns iteration values to corresponding iteration variables and then executes the block.

As an example:

for index, element := range someSlice {
    // index is the index where we are
    // element is the element from someSlice for where we are
}

If you don't care about the index, you can use _:

for _, element := range someSlice {
    // element is the element from someSlice for where we are
}

The underscore, _, is the blank identifier, an anonymous placeholder.

How to change the background colour's opacity in CSS

Use rgba as most of the commonly used browsers supports it..

.social img:hover {
 background-color: rgba(0, 0, 0, .5)
}

Why do we use web.xml?

Web.xml is called as deployment descriptor file and its is is an XML file that contains information on the configuration of the web application, including the configuration of servlets.

Is Spring annotation @Controller same as @Service?

I already answered similar question on here Here is the Link

No both are different.

@Service annotation have use for other purpose and @Controller use for other. Actually Spring @Component, @Service, @Repository and @Controller annotations are used for automatic bean detection using classpath scan in Spring framework, but it doesn't ,mean that all functionalities are same. @Service: It indicates annotated class is a Service component in the business layer.

@Controller: Annotated class indicates that it is a controller components, and mainly used at presentation layer.

Find Number of CPUs and Cores per CPU using Command Prompt

You can use the environment variable NUMBER_OF_PROCESSORS for the total number of processors:

echo %NUMBER_OF_PROCESSORS%

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

Google is full of information on this. As Hans Passant said, Form controls are built in to Excel whereas ActiveX controls are loaded separately.

Generally you'll use Forms controls, they're simpler. ActiveX controls allow for more flexible design and should be used when the job just can't be done with a basic Forms control.

Many user's computers by default won't trust ActiveX, and it will be disabled; this sometimes needs to be manually added to the trust center. ActiveX is a microsoft-based technology and, as far as I'm aware, is not supported on the Mac. This is something you'll have to also consider, should you (or anyone you provide a workbook to) decide to use it on a Mac.

How to save RecyclerView's scroll position using RecyclerView.State?

Store

lastFirstVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();

Restore

((LinearLayoutManager) rv.getLayoutManager()).scrollToPosition(lastFirstVisiblePosition);

and if that doesn't work, try

((LinearLayoutManager) rv.getLayoutManager()).scrollToPositionWithOffset(lastFirstVisiblePosition,0)

Put store in onPause() and restore in onResume()

How to change Label Value using javascript

You're taking name in document.getElementById() Your cb should be txt206451 (ID Attribute) not name attribute.

Or

You can have it by document.getElementsByName()

var cb = document.getElementsByName('field206451')[0]; // First one

OR

var cb = document.getElementById('txt206451');

And for setting values into hidden use document.getElementsByName() like following

var cb = document.getElementById('txt206451');
var label = document.getElementsByName('label206451')[0]; // Get the first one of index
console.log(label);
cb.addEventListener('change', function (evt) { // use change here. not neccessarily
    if (this.checked) {
        label.value = 'Thanks'
    } else {
        label.value = '0'
    }
}, false);

Demo Fiddle

How To Set A JS object property name from a variable

jsonVariable = {}
for(i=1; i<3; i++) {        
   var jsonKey  = i+'name';
   jsonVariable[jsonKey] = 'name1'
}

this will be similar to

    jsonVariable = {
    1name : 'name1'
    2name : 'name1'
}

char initial value in Java

you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.

Hyper-V: Create shared folder between host and guest with internal network

Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

Prerequisites

  1. Ensure that Enhanced session mode settings are enabled on the Hyper-V host.

    Start Hyper-V Manager, and in the Actions section, select "Hyper-V Settings".

    hyper-v-settings

    Make sure that enhanced session mode is allowed in the Server section. Then, make sure that the enhanced session mode is available in the User section.

    use-enhanced-session-mode

  2. Enable Hyper-V Guest Services for your virtual machine

    Right-click on Virtual Machine > Settings. Select the Integration Services in the left-lower corner of the menu. Check Guest Service and click OK.

    enable-guest-services

Steps to share devices with Hyper-v virtual machine:

  1. Start a virtual machine and click Show Options in the pop-up windows.

    connect-to-vm

    Or click "Edit Session Settings..." in the Actions panel on the right

    edit-session-sessions

    It may only appear when you're (able to get) connected to it. If it doesn't appear try Starting and then Connecting to the VM while paying close attention to the panel in the Hyper-V Manager.

  2. View local resources. Then, select the "More..." menu.

    click-more

  3. From there, you can choose which devices to share. Removable drives are especially useful for file sharing.

    choose-the-devices-that-you-want-to-use

  4. Choose to "Save my settings for future connections to this virtual machine".

    save-my-settings-for-future-connections-to-this-vm

  5. Click Connect. Drive sharing is now complete, and you will see the shared drive in this PC > Network Locations section of Windows Explorer after using the enhanced session mode to sigh to the VM. You should now be able to copy files from a physical machine and paste them into a virtual machine, and vice versa.

    shared-drives-from-local-pc

Source (and for more info): Share Files, Folders or Drives Between Host and Hyper-V Virtual Machine

How do you share constants in NodeJS modules?

I think that const solves the problem for most people looking for this anwwer. If you really need an immutable constant, look into the other answers. To keep everything organized I save all constants on a folder and then require the whole folder.

src/main.js file

const constants = require("./consts_folder");

src/consts_folder/index.js

const deal = require("./deal.js")
const note = require("./note.js")


module.exports = {
  deal,
  note
}

Ps. here the deal and note will be first level on the main.js

src/consts_folder/note.js

exports.obj = {
  type: "object",
  description: "I'm a note object"
}

Ps. obj will be second level on the main.js

src/consts_folder/deal.js

exports.str = "I'm a deal string"

Ps. str will be second level on the main.js

Final result on main.js file:

console.log(constants.deal); Ouput:

{ deal: { str: 'I\'m a deal string' },

console.log(constants.note); Ouput:

note: { obj: { type: 'object', description: 'I\'m a note object' } }

What is the best way to redirect a page using React Router?

You can also use react router dom library useHistory;

`
import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}
`

https://reactrouter.com/web/api/Hooks/usehistory

Abstract Class vs Interface in C++

Please don't put members into an interface; though it's correct in phrasing. Please don't "delete" an interface.

class IInterface() 
{ 
   Public: 
   Virtual ~IInterface(){}; 
   … 
} 

Class ClassImpl : public IInterface 
{ 
    … 
} 

Int main() 
{ 

  IInterface* pInterface = new ClassImpl(); 
  … 
  delete pInterface; // Wrong in OO Programming, correct in C++.
}

How exactly does __attribute__((constructor)) work?

Here is a "concrete" (and possibly useful) example of how, why, and when to use these handy, yet unsightly constructs...

Xcode uses a "global" "user default" to decide which XCTestObserver class spews it's heart out to the beleaguered console.

In this example... when I implicitly load this psuedo-library, let's call it... libdemure.a, via a flag in my test target á la..

OTHER_LDFLAGS = -ldemure

I want to..

  1. At load (ie. when XCTest loads my test bundle), override the "default" XCTest "observer" class... (via the constructor function) PS: As far as I can tell.. anything done here could be done with equivalent effect inside my class' + (void) load { ... } method.

  2. run my tests.... in this case, with less inane verbosity in the logs (implementation upon request)

  3. Return the "global" XCTestObserver class to it's pristine state.. so as not to foul up other XCTest runs which haven't gotten on the bandwagon (aka. linked to libdemure.a). I guess this historically was done in dealloc.. but I'm not about to start messing with that old hag.

So...

#define USER_DEFS NSUserDefaults.standardUserDefaults

@interface      DemureTestObserver : XCTestObserver @end
@implementation DemureTestObserver

__attribute__((constructor)) static void hijack_observer() {

/*! here I totally hijack the default logging, but you CAN
    use multiple observers, just CSV them, 
    i.e. "@"DemureTestObserverm,XCTestLog"
*/
  [USER_DEFS setObject:@"DemureTestObserver" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

__attribute__((destructor)) static void reset_observer()  {

  // Clean up, and it's as if we had never been here.
  [USER_DEFS setObject:@"XCTestLog" 
                forKey:@"XCTestObserverClass"];
  [USER_DEFS synchronize];
}

...
@end

Without the linker flag... (Fashion-police swarm Cupertino demanding retribution, yet Apple's default prevails, as is desired, here)

enter image description here

WITH the -ldemure.a linker flag... (Comprehensible results, gasp... "thanks constructor/destructor"... Crowd cheers) enter image description here

How to compare two java objects

1) == evaluates reference equality in this case
2) im not too sure about the equals, but why not simply overriding the compare method and plant it inside MyClass?

How to convert Observable<any> to array[]

This should work:

GetCountries():Observable<CountryData[]>  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json());
}

For this to work you will need to import the following:

import 'rxjs/add/operator/map'

Check status of one port on remote host

In Command Prompt, you can use the command telnet.. For Example, to connect to IP 192.168.10.1 with port 80,

telnet 192.168.10.1 80

To enable telnet in Windows 7 and above click. From the linked article, enable telnet through control panel -> programs and features -> windows features -> telnet client, or just run this in an admin prompt:

dism /online /Enable-Feature /FeatureName:TelnetClient

Sass Nesting for :hover does not work

You can easily debug such things when you go through the generated CSS. In this case the pseudo-selector after conversion has to be attached to the class. Which is not the case. Use "&".

http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How to correctly iterate through getElementsByClassName

 <!--something like this--> 
<html>
<body>



<!-- i've used for loop...this pointer takes current element to apply a 
 particular change on it ...other elements take change by else condition 
-->  


<div class="classname" onclick="myFunction(this);">first</div>  
<div class="classname" onclick="myFunction(this);">second</div>


<script>
function myFunction(p) {
 var x = document.getElementsByClassName("classname");
 var i;
 for (i = 0; i < x.length; i++) {
    if(x[i] == p)
    {
x[i].style.background="blue";
    }
    else{
x[i].style.background="red";
    }
}
}


</script>
<!--this script will only work for a class with onclick event but if u want 
to use all class of same name then u can use querySelectorAll() ...-->




var variable_name=document.querySelectorAll('.classname');
for(var i=0;i<variable_name.length;i++){
variable_name[i].(--your option--);
}



 <!--if u like to divide it on some logic apply it inside this for loop 
 using your nodelist-->

</body>
</html>

How to "flatten" a multi-dimensional array to simple one in PHP?

Simple approach..See it via recursion..

<?php

function flatten_array($simple){
static $outputs=array();
foreach ( $simple as $value)
{
if(is_array($value)){
    flatten_array($value);
}
else{
    $outputs[]=$value;
}

}
return $outputs;
}

$eg=['s'=>['p','n'=>['t']]];
$out=flatten_array($eg);
print_r($out);

?>

Add key value pair to all objects in array

Simply you can add that way. see below the console image

enter image description here

Echo equivalent in PowerShell for script testing

Try Get-Content .\yourScript.PS1 and you will see the content of your script.

also you can insert this line in your scrip code:

get-content .\scriptname.PS1
script code
script code

....

React Native TextInput that only accepts numeric characters

Function to validate input:

validateInputs(text, type) {
let numreg = /^[0-9]+$/;
  if (type == 'username') {
    if (numreg.test(text)) {
      //test ok
    } else {
      //test not ok
    } 
  }
}



<TextInput
   onChangeText={text => this.validateInputs(text, 'username')}
/>

I hope this is helpful.

How do I determine file encoding in OS X?

The @ means that the file has extended file attributes associated with it. You can query them using the getxattr() function.

There's no definite way to detect the encoding of a file. Read this answer, it explains why.

There's a command line tool, enca, that attempts to guess the encoding. You might want to check it out.

How to display alt text for an image in chrome

You can use the title attribute.

<img height="90" width="90"
src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif"
alt="Google Images" title="Google Images" />

Which version of C# am I using

To get the C# version from code, use this code from the Microsoft documentation to get the .NET Framework version and then match it up using the table that everyone else mentions. You can code up the Framework to C# version map in a dictionary or something to actually have your function return the C# version. Works if you have .NET Framework >= 4.5.

using System;
using Microsoft.Win32;

public class GetDotNetVersion
{
   public static void Main()
   {
      Get45PlusFromRegistry();
   }

   private static void Get45PlusFromRegistry()
   {
      const string subkey = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\";

      using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(subkey))
      {
        if (ndpKey != null && ndpKey.GetValue("Release") != null) {
            Console.WriteLine($".NET Framework Version: {CheckFor45PlusVersion((int) ndpKey.GetValue("Release"))}");
        }
         else {
            Console.WriteLine(".NET Framework Version 4.5 or later is not detected.");
         } 
      }

      // Checking the version using >= enables forward compatibility.
      string CheckFor45PlusVersion(int releaseKey)
      {
         if (releaseKey >= 528040)
            return "4.8 or later";
         if (releaseKey >= 461808)
            return "4.7.2";
         if (releaseKey >= 461308)
            return "4.7.1";
         if (releaseKey >= 460798)
            return "4.7";
         if (releaseKey >= 394802)
            return "4.6.2";
         if (releaseKey >= 394254)
            return "4.6.1";      
         if (releaseKey >= 393295)
            return "4.6";      
         if (releaseKey >= 379893)
            return "4.5.2";      
         if (releaseKey >= 378675)
            return "4.5.1";      
         if (releaseKey >= 378389)
            return "4.5";      
         // This code should never execute. A non-null release key should mean
         // that 4.5 or later is installed.
         return "No 4.5 or later version detected";
      }
   }
}   
// This example displays output like the following:
//       .NET Framework Version: 4.6.1

How do I convert a byte array to Base64 in Java?

Use:

byte[] data = Base64.encode(base64str);

Encoding converts to Base64

You would need to reference commons codec from your project in order for that code to work.

For java8:

import java.util.Base64

How many significant digits do floats and doubles have in java?

float: 32 bits (4 bytes) where 23 bits are used for the mantissa (about 7 decimal digits). 8 bits are used for the exponent, so a float can “move” the decimal point to the right or to the left using those 8 bits. Doing so avoids storing lots of zeros in the mantissa as in 0.0000003 (3 × 10-7) or 3000000 (3 × 107). There is 1 bit used as the sign bit.

double: 64 bits (8 bytes) where 52 bits are used for the mantissa (about 16 decimal digits). 11 bits are used for the exponent and 1 bit is the sign bit.

Since we are using binary (only 0 and 1), one bit in the mantissa is implicitly 1 (both float and double use this trick) when the number is non-zero.

Also, since everything is in binary (mantissa and exponents) the conversions to decimal numbers are usually not exact. Numbers like 0.5, 0.25, 0.75, 0.125 are stored exactly, but 0.1 is not. As others have said, if you need to store cents precisely, do not use float or double, use int, long, BigInteger or BigDecimal.

Sources:

http://en.wikipedia.org/wiki/Floating_point#IEEE_754:_floating_point_in_modern_computers

http://en.wikipedia.org/wiki/Binary64

http://en.wikipedia.org/wiki/Binary32

How to add \newpage in Rmarkdown in a smart way?

You can make the pagebreak conditional on knitting to PDF. This worked for me.

```{r, results='asis', eval=(opts_knit$get('rmarkdown.pandoc.to') == 'latex')}
cat('\\pagebreak')
```

How to set the background image of a html 5 canvas to .png image

You can use this plugin, but for printing purpose i have added some code like <button onclick="window.print();">Print</button> and for saving image <button onclick="savePhoto();">Save Picture</button>

     function savePhoto() {
     var canvas = document.getElementById("canvas");
     var img    = canvas.toDataURL("image/png");
     window.location = img;}

checkout this plugin http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app

How to get the ActionBar height?

Here's an updated version with Kotlin I used assuming phone is higher than Honeycomb:

val actionBarHeight = with(TypedValue().also {context.theme.resolveAttribute(android.R.attr.actionBarSize, it, true)}) {
            TypedValue.complexToDimensionPixelSize(this.data, resources.displayMetrics)
        }

What's the fastest way to convert String to Number in JavaScript?

I find that num * 1 is simple, clear, and works for integers and floats...

How to bring view in front of everything?

i have faced the same problem. the following solution have worked for me.

 FrameLayout glFrame=(FrameLayout) findViewById(R.id.animatedView);
        glFrame.addView(yourView);
        glFrame.bringToFront();
        glFrame.invalidate();

2nd solution is by using xml adding this attribute to the view xml

android:translationZ=""

How to stop C++ console application from exiting immediately?

All you have to do set a variable for x then just type this in before the return 0;

cout<<"\nPress any key and hit enter to end...";
cin>>x;

Simplest way to detect a pinch

My answer is inspired by Jeffrey's answer. Where that answer gives a more abstract solution, I try to provide more concrete steps on how to potentially implement it. This is simply a guide, one that can be implemented more elegantly. For a more detailed example check out this tutorial by MDN web docs.

HTML:

<div id="zoom_here">....</div>

JS

<script>
var dist1=0;
function start(ev) {
           if (ev.targetTouches.length == 2) {//check if two fingers touched screen
               dist1 = Math.hypot( //get rough estimate of distance between two fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);                  
           }
    
    }
    function move(ev) {
           if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
                 // Check if the two target touches are the same ones that started
               var dist2 = Math.hypot(//get rough estimate of new distance between fingers
                ev.touches[0].pageX - ev.touches[1].pageX,
                ev.touches[0].pageY - ev.touches[1].pageY);
                //alert(dist);
                if(dist1>dist2) {//if fingers are closer now than when they first touched screen, they are pinching
                  alert('zoom out');
                }
                if(dist1<dist2) {//if fingers are further apart than when they first touched the screen, they are making the zoomin gesture
                   alert('zoom in');
                }
           }
           
    }
        document.getElementById ('zoom_here').addEventListener ('touchstart', start, false);
        document.getElementById('zoom_here').addEventListener('touchmove', move, false);
</script>

How do I properly set the permgen size?

You have to change the values in the CATALINA_OPTS option defined in the Tomcat Catalina start file. To increase the PermGen memory change the value of the MaxPermSize variable, otherwise change the value of the Xmx variable.

Linux & Mac OS: Open or create setenv.sh file placed in the "bin" directory. You have to apply the changes to this line:

export CATALINA_OPTS="$CATALINA_OPTS -server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m"

Windows:

Open or create the setenv.bat file placed in the "bin" directory:

set CATALINA_OPTS=-server -Xms256m -Xmx1024m -XX:PermSize=512m -XX:MaxPermSize=512m

What does $@ mean in a shell script?

$@ is nearly the same as $*, both meaning "all command line arguments". They are often used to simply pass all arguments to another program (thus forming a wrapper around that other program).

The difference between the two syntaxes shows up when you have an argument with spaces in it (e.g.) and put $@ in double quotes:

wrappedProgram "$@"
# ^^^ this is correct and will hand over all arguments in the way
#     we received them, i. e. as several arguments, each of them
#     containing all the spaces and other uglinesses they have.
wrappedProgram "$*"
# ^^^ this will hand over exactly one argument, containing all
#     original arguments, separated by single spaces.
wrappedProgram $*
# ^^^ this will join all arguments by single spaces as well and
#     will then split the string as the shell does on the command
#     line, thus it will split an argument containing spaces into
#     several arguments.

Example: Calling

wrapper "one two    three" four five "six seven"

will result in:

"$@": wrappedProgram "one two    three" four five "six seven"
"$*": wrappedProgram "one two    three four five six seven"
                             ^^^^ These spaces are part of the first
                                  argument and are not changed.
$*:   wrappedProgram one two three four five six seven

Open a folder using Process.Start

System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");

Just change the path or declare it in a string

Load dimension value from res/values/dimension.xml from source code

    This works but the value I get is multiplied times the screen density factor
  (1.5 for hdpi, 2.0 for xhdpi, etc).

I think it is good to get the value as per resolution but if you not want to do this give this in px.......

Density-independent pixel (dp)

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

I think it is good to change the value as per resolution but if you not want to do this give this in px.......

refer this link

as per this

dp

Density-independent Pixels - An abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi (dots per inch) screen, on which 1dp is roughly equal to 1px. When running on a higher density screen, the number of pixels used to draw 1dp is scaled up by a factor appropriate for the screen's dpi. Likewise, when on a lower density screen, the number of pixels used for 1dp is scaled down. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Using dp units (instead of px units) is a simple solution to making the view dimensions in your layout resize properly for different screen densities. In other words, it provides consistency for the real-world sizes of your UI elements across different devices.

px

Pixels - Corresponds to actual pixels on the screen. This unit of measure is not recommended because the actual representation can vary across devices; each devices may have a different number of pixels per inch and may have more or fewer total pixels available on the screen.

Passing variables to the next middleware using next() in Express.js

As mentioned above, res.locals is a good (recommended) way to do this. See here for a quick tutorial on how to do this in Express.

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Convert ASCII number to ASCII Character in C

If the number is stored in a string (which it would be if typed by a user), you can use atoi() to convert it to an integer.

An integer can be assigned directly to a character. A character is different mostly just because how it is interpreted and used.

char c = atoi("61");

Render Content Dynamically from an array map function in React Native

Don't forget to return the mapped array , like:

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })

}

Reference for the map() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Difference between pre-increment and post-increment in a loop?

There is more to ++i and i++ than loops and performance differences. ++i returns a l-value and i++ returns an r-value. Based on this, there are many things you can do to ( ++i ) but not to ( i++ ).

1- It is illegal to take the address of post increment result. Compiler won't even allow you.
2- Only constant references to post increment can exist, i.e., of the form const T&.
3- You cannot apply another post increment or decrement to the result of i++, i.e., there is no such thing as I++++. This would be parsed as ( i ++ ) ++ which is illegal.
4- When overloading pre-/post-increment and decrement operators, programmers are encouraged to define post- increment/decrement operators like:

T& operator ++ ( )
{
   // logical increment
   return *this;
}

const T operator ++ ( int )
{
    T temp( *this );
    ++*this;
    return temp;
}

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

Anaconda does not use the PYTHONPATH. One should however note that if the PYTHONPATH is set it could be used to load a library that is not in the anaconda environment. That is why before activating an environment it might be good to do a

unset PYTHONPATH

For instance this PYTHONPATH points to an incorrect pandas lib:

export PYTHONPATH=/home/john/share/usr/anaconda/lib/python
source activate anaconda-2.7
python
>>>> import pandas as pd
/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/__init__.py", line 6, in <module>
    from . import hashtable, tslib, lib
ImportError: /home/john/share/usr/lib/python/pandas-0.12.0-py2.7-linux-x86_64.egg/pandas/hashtable.so: undefined symbol: PyUnicodeUCS2_DecodeUTF8

unsetting the PYTHONPATH prevents the wrong pandas lib from being loaded:

unset PYTHONPATH
source activate anaconda-2.7
python
>>>> import pandas as pd
>>>>

XSS prevention in JSP/Servlet web application

There is no easy, out of the box solution against XSS. The OWASP ESAPI API has some support for the escaping that is very usefull, and they have tag libraries.

My approach was to basically to extend the stuts 2 tags in following ways.

  1. Modify s:property tag so it can take extra attributes stating what sort of escaping is required (escapeHtmlAttribute="true" etc.). This involves creating a new Property and PropertyTag classes. The Property class uses OWASP ESAPI api for the escaping.
  2. Change freemarker templates to use the new version of s:property and set the escaping.

If you didn't want to modify the classes in step 1, another approach would be to import the ESAPI tags into the freemarker templates and escape as needed. Then if you need to use a s:property tag in your JSP, wrap it with and ESAPI tag.

I have written a more detailed explanation here.

http://www.nutshellsoftware.org/software/securing-struts-2-using-esapi-part-1-securing-outputs/

I agree escaping inputs is not ideal.

Convert DateTime to String PHP

Its worked for me

$start_time   = date_create_from_format('Y-m-d H:i:s', $start_time);
$current_date = new DateTime();
$diff         = $start_time->diff($current_date);
$aa           = (string)$diff->format('%R%a');
echo gettype($aa);

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.

how to add background image to activity?

and dont forget to clean your project after writing these lines you`ll a get an error in your xml file until you´ve cleaned your project in eclipse: Project->Clean...

Is it possible to get a list of files under a directory of a website? How?

DirBuster is such a hacking script that guesses a bunch of common names as nsanders had mentioned. It literally brute forces lists of common words and file endings (.html, .php) and over time figures out the directory structure of such sites, this could discover the page as you described but would also discover many others.

What is the difference between a token and a lexeme?

a) Tokens are symbolic names for the entities that make up the text of the program; e.g. if for the keyword if, and id for any identifier. These make up the output of the lexical analyser. 5

(b) A pattern is a rule that specifies when a sequence of characters from the input constitutes a token; e.g the sequence i, f for the token if , and any sequence of alphanumerics starting with a letter for the token id.

(c) A lexeme is a sequence of characters from the input that match a pattern (and hence constitute an instance of a token); for example if matches the pattern for if , and foo123bar matches the pattern for id.

How to include PHP files that require an absolute path?

Another way to handle this that removes any need for includes at all is to use the autoload feature. Including everything your script needs "Just in Case" can impede performance. If your includes are all class or interface definitions, and you want to load them only when needed, you can overload the __autoload() function with your own code to find the appropriate class file and load it only when it's called. Here is the example from the manual:

function __autoload($class_name) {
    require_once $class_name . '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 

As long as you set your include_path variables accordingly, you never need to include a class file again.

How to submit a form using PhantomJS

Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS

// Example using HTTP POST operation

var page = require('webpage').create(),
    server = 'http://posttestserver.com/post.php?dump',
    data = 'universe=expanding&answer=42';

page.open(server, 'post', data, function (status) {
    if (status !== 'success') {
        console.log('Unable to post!');
    } else {
        console.log(page.content);
    }
    phantom.exit();
});

Java Timer vs ExecutorService?

ExecutorService is newer and more general. A timer is just a thread that periodically runs stuff you have scheduled for it.

An ExecutorService may be a thread pool, or even spread out across other systems in a cluster and do things like one-off batch execution, etc...

Just look at what each offers to decide.

Connect to Active Directory via LDAP

If your email address is '[email protected]', try changing the createDirectoryEntry() as below.

XYZ is an optional parameter if it exists in mydomain directory

static DirectoryEntry createDirectoryEntry()
{
    // create and return new LDAP connection with desired settings
    DirectoryEntry ldapConnection = new DirectoryEntry("myname.mydomain.com");
    ldapConnection.Path = "LDAP://OU=Users, OU=XYZ,DC=mydomain,DC=com";
    ldapConnection.AuthenticationType = AuthenticationTypes.Secure;
    return ldapConnection;
}

This will basically check for com -> mydomain -> XYZ -> Users -> abcd

The main function looks as below:

try
{
    username = "Firstname LastName"
    DirectoryEntry myLdapConnection = createDirectoryEntry();
    DirectorySearcher search = new DirectorySearcher(myLdapConnection);
    search.Filter = "(cn=" + username + ")";
    ....    

Open firewall port on CentOS 7

Hello in Centos 7 firewall-cmd. Yes correct if you use firewall-cmd --zone=public --add-port=2888/tcp but if you reload firewal firewall-cmd --reload

your config not will be save

you need to add key

firewall-cmd --permanent --zone=public --add-port=2888/tcp

How to submit http form using C#

I had a similar issue in MVC (which lead me to this problem).

I am receiving a FORM as a string response from a WebClient.UploadValues() request, which I then have to submit - so I can't use a second WebClient or HttpWebRequest. This request returned the string.

using (WebClient client = new WebClient())
  {
    byte[] response = client.UploadValues(urlToCall, "POST", new NameValueCollection()
    {
        { "test", "value123" }
    });

    result = System.Text.Encoding.UTF8.GetString(response);
  }

My solution, which could be used to solve the OP, is to append a Javascript auto submit to the end of the code, and then using @Html.Raw() to render it on a Razor page.

result += "<script>self.document.forms[0].submit()</script>";
someModel.rawHTML = result;
return View(someModel);

Razor Code:

@model SomeModel

@{
    Layout = null;
}

@Html.Raw(@Model.rawHTML)

I hope this can help anyone who finds themselves in the same situation.

Javascript add method to object

You can make bar a function making it a method.

Foo.bar = function(passvariable){  };

As a property it would just be assigned a string, data type or boolean

Foo.bar = "a place";

How to run a cronjob every X minutes?

In a crontab file, the fields are:

  • minute of the hour.
  • hour of the day.
  • day of the month.
  • month of the year.
  • day of the week.

So:

10 * * * * blah

means execute blah at 10 minutes past every hour.

If you want every five minutes, use either:

*/5 * * * * blah

meaning every minute but only every fifth one, or:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah

for older cron executables that don't understand the */x notation.

If it still seems to be not working after that, change the command to something like:

date >>/tmp/debug_cron_pax.txt

and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron daemon.

Prevent users from submitting a form by hitting Enter

I had to catch all three events related to pressing keys in order to prevent the form from being submitted:

    var preventSubmit = function(event) {
        if(event.keyCode == 13) {
            console.log("caught ya!");
            event.preventDefault();
            //event.stopPropagation();
            return false;
        }
    }
    $("#search").keypress(preventSubmit);
    $("#search").keydown(preventSubmit);
    $("#search").keyup(preventSubmit);

You can combine all the above into a nice compact version:

    $('#search').bind('keypress keydown keyup', function(e){
       if(e.keyCode == 13) { e.preventDefault(); }
    });

How can I create a memory leak in Java?

The interviewer might have be looking for a circular reference solution:

    public static void main(String[] args) {
        while (true) {
            Element first = new Element();
            first.next = new Element();
            first.next.next = first;
        }
    }

This is a classic problem with reference counting garbage collectors. You would then politely explain that JVMs use a much more sophisticated algorithm that doesn't have this limitation.

-Wes Tarle

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

If you used this to secure your server: http://www.thonky.com/how-to/prevent-base-64-decode-hack/

And then got the error: Code Igniter needs mysql_pconnect() in order to run.

I figured it out once I realized all the Code Igniter websites on the server were broken, so it wasn't a localized connection issue.

H.264 file size for 1 hr of HD video

If you know the bitrate, it's simply bitrate (bits per second) multiplied by number of seconds. Given that HDV is 25 Mbit/s and one hour has 3,600 seconds, non-transcoded it would be:

25 Mbit/s * 3,600 s/hr  =  3.125 MB/s * 3,600 s/hr  =  11,250 MB/hr  ˜  11 GB/hr

Google's calculator can confirm

The same applies with H.264 footage, although the above might not be as accurate (being variable bitrate and such).

I want to archive approximately 100 hours of such content and want to figure out whether I'm looking at a big hard drive, a multi-drive unit like a Drobo, or an enterprise-level storage system.

First, do not buy an "enterprise-level" storage system (you almost certainly don't need things like hot-swap drives and the same level of support - given the costs)..

I would suggest buying two big drives: One would be your main drive, another in a USB enclosure, and would be connected daily and mirror the primary system (as a backup).

Drives are incredibly cheap, using the above calculation of ~11 GB/hour, that's only 1.1 TB of data (for 100 hours, uncompressed). and you can buy 2 TB drives now.

Drobo, or a machine with a few drives and software RAID is an option, but a single large drive plus backups would be simpler.

Storage is almost a non-issue now, but encode time can still be an issue. Encoding H.264 is very resource-intensive. On a quad-core ~2.5 GHz Xeon, I think I got around 60 fps encoding standard-def (DVD) to H.264 (compared to around 300 fps with MPEG 4). I suppose that's only about 50 hours, but it's something worth considering. Also, assuming the HDV is on tapes, it's a 1:1 capture time, so that's 150 hours of straight processing, never mind things like changing tapes, entering metadata, and general delays (sleep) and errors ("opps, wrong tape").

How to overload __init__ method based on argument type?

with python3, you can use Implementing Multiple Dispatch with Function Annotations as Python Cookbook wrote:

import time


class Date(metaclass=MultipleMeta):
    def __init__(self, year:int, month:int, day:int):
        self.year = year
        self.month = month
        self.day = day

    def __init__(self):
        t = time.localtime()
        self.__init__(t.tm_year, t.tm_mon, t.tm_mday)

and it works like:

>>> d = Date(2012, 12, 21)
>>> d.year
2012
>>> e = Date()
>>> e.year
2018

How to check whether a Button is clicked by using JavaScript

if(button.clicked==true) {
    console.log("Button Clicked");
} ==> // This Code Doesn't Work Properly So Please Use Below One // 


function check() { 
    console.log("Button Clicked");
}; // This Code Works Fine // 

var button= document.querySelector("button"); // Accessing The Button // 
button.addEventListener("click", check); // Adding event to call function when clicked // 

How to change pivot table data source in Excel?

right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition

then you can create a new or choose a different connection

Maximum call stack size exceeded error

We recently added a field to an admin site we are working on - contact_type... easy right? Well, if you call the select "type" and try to send that through a jquery ajax call it fails with this error buried deep in jquery.js Don't do this:

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/some_function.php",
    data: { contact_uid:contact_uid, type:type }
});

The problem is that type:type - I believe it is us naming the argument "type" - having a value variable named type isn't the problem. We changed this to:

$.ajax({
    dataType: "json",
    type: "POST",
    url: "/some_function.php",
    data: { contact_uid:contact_uid, contact_type:type }
});

And rewrote some_function.php accordingly - problem solved.

How to change Hash values?

You can collect the values, and convert it from Array to Hash again.

Like this:

config = Hash[ config.collect {|k,v| [k, v.upcase] } ]

How to Convert datetime value to yyyymmddhhmmss in SQL server?

SELECT REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), '-', ''), 'T', ''), ':', '') 

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

Remove all special characters from a string

Update

The solution below has a "SEO friendlier" version:

function hyphenize($string) {
    $dict = array(
        "I'm"      => "I am",
        "thier"    => "their",
        // Add your own replacements here
    );
    return strtolower(
        preg_replace(
          array( '#[\\s-]+#', '#[^A-Za-z0-9. -]+#' ),
          array( '-', '' ),
          // the full cleanString() can be downloaded from http://www.unexpectedit.com/php/php-clean-string-of-utf8-chars-convert-to-similar-ascii-char
          cleanString(
              str_replace( // preg_replace can be used to support more complicated replacements
                  array_keys($dict),
                  array_values($dict),
                  urldecode($string)
              )
          )
        )
    );
}

function cleanString($text) {
    $utf8 = array(
        '/[áàâãªä]/u'   =>   'a',
        '/[ÁÀÂÃÄ]/u'    =>   'A',
        '/[ÍÌÎÏ]/u'     =>   'I',
        '/[íìîï]/u'     =>   'i',
        '/[éèêë]/u'     =>   'e',
        '/[ÉÈÊË]/u'     =>   'E',
        '/[óòôõºö]/u'   =>   'o',
        '/[ÓÒÔÕÖ]/u'    =>   'O',
        '/[úùûü]/u'     =>   'u',
        '/[ÚÙÛÜ]/u'     =>   'U',
        '/ç/'           =>   'c',
        '/Ç/'           =>   'C',
        '/ñ/'           =>   'n',
        '/Ñ/'           =>   'N',
        '/–/'           =>   '-', // UTF-8 hyphen to "normal" hyphen
        '/[’‘‹›‚]/u'    =>   ' ', // Literally a single quote
        '/[“”«»„]/u'    =>   ' ', // Double quote
        '/ /'           =>   ' ', // nonbreaking space (equiv. to 0x160)
    );
    return preg_replace(array_keys($utf8), array_values($utf8), $text);
}

The rationale for the above functions (which I find way inefficient - the one below is better) is that a service that shall not be named apparently ran spelling checks and keyword recognition on the URLs.

After losing a long time on a customer's paranoias, I found out they were not imagining things after all -- their SEO experts [I am definitely not one] reported that, say, converting "Viaggi Economy Perù" to viaggi-economy-peru "behaved better" than viaggi-economy-per (the previous "cleaning" removed UTF8 characters; Bogotà became bogot, Medellìn became medelln and so on).

There were also some common misspellings that seemed to influence the results, and the only explanation that made sense to me is that our URL were being unpacked, the words singled out, and used to drive God knows what ranking algorithms. And those algorithms apparently had been fed with UTF8-cleaned strings, so that "Perù" became "Peru" instead of "Per". "Per" did not match and sort of took it in the neck.

In order to both keep UTF8 characters and replace some misspellings, the faster function below became the more accurate (?) function above. $dict needs to be hand tailored, of course.

Previous answer

A simple approach:

// Remove all characters except A-Z, a-z, 0-9, dots, hyphens and spaces
// Note that the hyphen must go last not to be confused with a range (A-Z)
// and the dot, NOT being special (I know. My life was a lie), is NOT escaped

$str = preg_replace('/[^A-Za-z0-9. -]/', '', $str);

// Replace sequences of spaces with hyphen
$str = preg_replace('/  */', '-', $str);

// The above means "a space, followed by a space repeated zero or more times"
// (should be equivalent to / +/)

// You may also want to try this alternative:
$str = preg_replace('/\\s+/', '-', $str);

// where \s+ means "zero or more whitespaces" (a space is not necessarily the
// same as a whitespace) just to be sure and include everything

Note that you might have to first urldecode() the URL, since %20 and + both are actually spaces - I mean, if you have "Never%20gonna%20give%20you%20up" you want it to become Never-gonna-give-you-up, not Never20gonna20give20you20up . You might not need it, but I thought I'd mention the possibility.

So the finished function along with test cases:

function hyphenize($string) {
    return 
    ## strtolower(
          preg_replace(
            array('#[\\s-]+#', '#[^A-Za-z0-9. -]+#'),
            array('-', ''),
        ##     cleanString(
              urldecode($string)
        ##     )
        )
    ## )
    ;
}

print implode("\n", array_map(
    function($s) {
            return $s . ' becomes ' . hyphenize($s);
    },
    array(
    'Never%20gonna%20give%20you%20up',
    "I'm not the man I was",
    "'Légeresse', dit sa majesté",
    )));


Never%20gonna%20give%20you%20up    becomes  never-gonna-give-you-up
I'm not the man I was              becomes  im-not-the-man-I-was
'Légeresse', dit sa majesté        becomes  legeresse-dit-sa-majeste

To handle UTF-8 I used a cleanString implementation found online (link broken since, but a stripped down copy with all the not-too-esoteric UTF8 characters is at the beginning of the answer; it's also easy to add more characters to it if you need) that converts UTF8 characters to normal characters, thus preserving the word "look" as much as possible. It could be simplified and wrapped inside the function here for performance.

The function above also implements converting to lowercase - but that's a taste. The code to do so has been commented out.

Select all elements with a "data-xxx" attribute without using jQuery

Here is an interesting solution: it uses the browsers CSS engine to to add a dummy property to elements matching the selector and then evaluates the computed style to find matched elements:

It does dynamically create a style rule [...] It then scans the whole document (using the much decried and IE-specific but very fast document.all) and gets the computed style for each of the elements. We then look for the foo property on the resulting object and check whether it evaluates as “bar”. For each element that matches, we add to an array.

What is the easiest way to get current GMT time in Unix timestamp format?

At least in python3, this works:

>>> datetime.strftime(datetime.utcnow(), "%s")
'1587503279'

Is it possible to select the last n items with nth-child?

This will select the last two iems of a list:

_x000D_
_x000D_
li:nth-last-child(-n+2) {color:red;}
_x000D_
<ul>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
  <li>fred</li>
</ul>
_x000D_
_x000D_
_x000D_

Project vs Repository in GitHub

The conceptual difference in my understanding it that a project can contain many repo's and that are independent of each other, while simultaneously a repo may contain many projects. Repo's being just a storage place for code while a project being a collection of tasks for a certain feature.

Does that make sense? A large repo can have many projects being worked on by different people at the same time (lots of difference features being added to a monolith), a large project may have many small repos that are separate but part of the same project that interact with each other - microservices? Its a personal take on what you want to do. I think that repo (storage) vs project (tasks) is the main difference - if i am wrong please let me know / explain! Thanks.

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

MySQL - UPDATE query based on SELECT Query

UPDATE 
  receipt_invoices dest,
  (
    SELECT 
      `receipt_id`,
      CAST((net * 100) / 112 AS DECIMAL (11, 2)) witoutvat 
    FROM
      receipt 
    WHERE CAST((net * 100) / 112 AS DECIMAL (11, 2)) != total 
      AND vat_percentage = 12
  ) src 
SET
  dest.price = src.witoutvat,
  dest.amount = src.witoutvat 
WHERE col_tobefixed = 1 
  AND dest.`receipt_id` = src.receipt_id ;

Hope this will help you in a case where you have to match and update between two tables.

How to add element in List while iterating in java?

You could iterate on a copy (clone) of your original list:

List<String> copy = new ArrayList<String>(list);
for (String s : copy) {
    // And if you have to add an element to the list, add it to the original one:
    list.add("some element");
}

Note that it is not even possible to add a new element to a list while iterating on it, because it will result in a ConcurrentModificationException.

Enable/Disable a dropdownbox in jquery

try this

 <script type="text/javascript">
        $(document).ready(function () {
            $("#chkdwn2").click(function () {
                if (this.checked)
                    $('#dropdown').attr('disabled', 'disabled');
                else
                    $('#dropdown').removeAttr('disabled');
            });
        });
    </script>

where is gacutil.exe?

On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.

Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")

If you need to get the name and PublicKeyToken see this question.

Copying a local file from Windows to a remote server using scp

Drive letter can be used in the source like

scp /c/path/to/file.txt user@server:/dir1/file.txt

How can I override Bootstrap CSS styles?

It should not effect the load time much since you are overriding parts of the base stylesheet.

Here are some best practices I personally follow:

  1. Always load custom CSS after the base CSS file (not responsive).
  2. Avoid using !important if possible. That can override some important styles from the base CSS files.
  3. Always load bootstrap-responsive.css after custom.css if you don't want to lose media queries. - MUST FOLLOW
  4. Prefer modifying required properties (not all).

javascript, is there an isObject function like isArray?

You can use typeof operator.

if( (typeof A === "object" || typeof A === 'function') && (A !== null) )
{
    alert("A is object");
}

Note that because typeof new Number(1) === 'object' while typeof Number(1) === 'number'; the first syntax should be avoided.