Programs & Examples On #Expansion

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

  1. Uninstall all JDKs installed on your computer from the Java Control Panel
  2. Search for C:\ProgramData\Oracle\Java and delete that directory and all files contained within. You can do this from the command line using rmdir /S C:\ProgramData\Oracle\Java
  3. Then search for C:\ProgramData\Oracle and delete the oracle folder. You can do this using rmdir /S C:\ProgramData\Oracle
  4. Now install JDK and set the path.

  5. Run the program.You won't find the same problem anymore.

OpenSSL Command to check if a server is presenting a certificate

I was debugging an SSL issue today which resulted in the same write:errno=104 error. Eventually I found out that the reason for this behaviour was that the server required SNI (servername TLS extensions) to work correctly. Supplying the -servername option to openssl made it connect successfully:

openssl s_client -connect domain.tld:443 -servername domain.tld

Hope this helps.

Batch script to find and replace a string in text file within a minute for files up to 12 MB

Just download fart (find and replace text) from here

use it in CMD (for ease of use I add fart folder to my path variable)

here is an example:

fart -r "C:\myfolder\*.*" findSTR replaceSTR

this command will search in C:\myfolder and all sub-folders and replace findSTR with replaceSTR

-r means process sub-folders recursively.

fart is really fast and easy

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

How can I open a .tex file?

I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.

I have to assume you are using windows because you have mentioned notepad++.

  1. Use notepad++. Right click on the file and choose "edit with notepad++"

  2. Use notepad Change the filename extension to .txt and double click the file.

  3. Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"

If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.

Why is it common to put CSRF prevention tokens in cookies?

Besides the session cookie (which is kind of standard), I don't want to use extra cookies.

I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.

My solution without extra cookies is simple:

Client Side

Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.

The main "index" page contains this JavaScript snippet:

// Intialize global variable CSRF_TOKEN to empty sting. 
// This variable is set after a succesful login
window.CSRF_TOKEN = '';

// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
    jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
}); 

Server Side

On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.

Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.

@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
    resp.sendError(401);
} else
    chain.doFilter(request, response);
}   

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

For Spring Boot RestTemplate:

  • add org.apache.httpcomponents.httpcore dependency
  • use NoopHostnameVerifier for SSL factory:

    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(new URL("file:pathToServerKeyStore"), storePassword)
    //        .loadKeyMaterial(new URL("file:pathToClientKeyStore"), storePassword, storePassword)
            .build();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
    RestTemplate restTemplate = new RestTemplate(factory);
    

How to cd into a directory with space in the name?

Why not put the following in your .cshrc (or .bashrc, or whatever your default shell is):

alias mydoc 'cd "/cygdrive/c/Users/my dir/Documents"'

First time you do this, you have to do

source .cshrc

to update the shell with this new alias, then you can type

mydoc

anytime you want to cd to your directory.

Laziness is the mother of invention...

Batch Extract path and filename from a variable

All of this works for me:

@Echo Off
Echo Directory = %~dp0
Echo Object Name With Quotations=%0
Echo Object Name Without Quotes=%~0
Echo Bat File Drive = %~d0
Echo Full File Name = %~n0%~x0
Echo File Name Without Extension = %~n0
Echo File Extension = %~x0
Pause>Nul

Output:

Directory = D:\Users\Thejordster135\Desktop\Code\BAT\

Object Name With Quotations="D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat"

Object Name Without Quotes=D:\Users\Thejordster135\Desktop\Code\BAT\Path_V2.bat

Bat File Drive = D:

Full File Name = Path.bat

File Name Without Extension = Path

File Extension = .bat

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

I was having similar issue and I think if we simply ignore the ssl verification will work like charm as it worked for me. So connecting to server with https scheme but directing them not to verify the certificate.

Using requests. Just mention verify=False instead of None

    requests.post(url, data=payload, headers=headers, verify=False)

Hoping this will work for those who needs :).

Expansion of variables inside single quotes in a command in Bash

just use printf

instead of

repo forall -c '....$variable'

use printf to replace the variable token with the expanded variable.

For example:

template='.... %s'

repo forall -c $(printf "${template}" "${variable}")

'nuget' is not recognized but other nuget commands working

Retrieve nuget.exe from https://www.nuget.org/downloads. Copy it to a local folder and add that folder to the PATH environment variable.

This is will make nuget available globally, from any project.

How to add a second x-axis in matplotlib

If You want your upper axis to be a function of the lower axis tick-values you can do as below. Please note: sometimes get_xticks() will have a ticks outside of the visible range, which you have to allow for when converting.

import matplotlib.pyplot as plt

fig, ax1 = plt.subplots()

ax1 = fig.add_subplot(111)

ax1.plot(range(5), range(5))

ax1.grid(True)

ax2 = ax1.twiny()
ax2.set_xticks( ax1.get_xticks() )
ax2.set_xbound(ax1.get_xbound())
ax2.set_xticklabels([x * 2 for x in ax1.get_xticks()])

title = ax1.set_title("Upper x-axis ticks are lower x-axis ticks doubled!")
title.set_y(1.1)
fig.subplots_adjust(top=0.85)

fig.savefig("1.png")

Gives:

enter image description here

Why does SSL handshake give 'Could not generate DH keypair' exception?

Try downloading "Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files" from the Java download site and replacing the files in your JRE.

This worked for me and I didn't even need to use BouncyCastle - the standard Sun JCE was able to connect to the server.

PS. I got the same error (ArrayIndexOutOfBoundsException: 64) when I tried using BouncyCastle before changing the policy files, so it seems our situation is very similar.

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

A real problem often exists because any variables set inside will not be exported when that batch file finishes. So its not possible to export, which caused us issues. As a result, I just set the registry to ALWAYS used delayed expansion (I don't know why it's not the default, could be speed or legacy compatibility issue.)

How to expand/collapse a diff sections in Vimdiff?

Aside from the ones you mention, I only use frequently when diffing the following:

  • :diffupdate :diffu -> recalculate the diff, useful when after making several changes vim's isn't showing minimal changes anymore. Note that it only works if the files have been modified inside vimdiff. Otherwise, use:
    • :e to reload the files if they have been modified outside of vimdiff.
  • :set noscrollbind -> temporarily disable simultaneous scrolling on both buffers, reenable by :set scrollbind and scrolling.

Most of what you asked for is folding: vim user manual's chapter on folding. Outside of diffs I sometime use:

  • zo -> open fold.
  • zc -> close fold.

But you'll probably be better served by:

  • zr -> reducing folding level.
  • zm -> one more folding level, please.

or even:

  • zR -> Reduce completely the folding, I said!.
  • zM -> fold Most!.

The other thing you asked for, use n lines of folding, can be found at the vim reference manual section on options, via the section on diff:

  • set diffopt=<TAB>, then update or add context:n.

You should also take a look at the user manual section on diff.

ArithmeticException: "Non-terminating decimal expansion; no exact representable decimal result"

I had this same problem, because my line of code was:

txtTotalInvoice.setText(var1.divide(var2).doubleValue() + "");

I change to this, reading previous Answer, because I was not writing decimal precision:

txtTotalInvoice.setText(var1.divide(var2,4, RoundingMode.HALF_UP).doubleValue() + "");

4 is Decimal Precison

AND RoundingMode are Enum constants, you could choose any of this UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP

In this Case HALF_UP, will have this result:

2.4 = 2   
2.5 = 3   
2.7 = 3

You can check the RoundingMode information here: http://www.javabeat.net/precise-rounding-of-decimals-using-rounding-mode-enumeration/

How to use patterns in a case statement?

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

Here's an example:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

Set the table column width constant regardless of the amount of text in its cells?

Just add <div> tag inside <td> or <th> define width inside <div>. This will help you. Nothing else works.

eg.

<td><div style="width: 50px" >...............</div></td>

bash assign default value

Use a colon:

: ${A:=hello}

The colon is a null command that does nothing and ignores its arguments. It is built into bash so a new process is not created.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

ASP.NET IIS Web.config [Internal Server Error]

I had the same problem. Don't remember where I found it on the web, but here is what I did:

Click "Start button"

in the search box, enter "Turn windows features on or off"

in the features window, Click: "Internet Information Services"

Click: "World Wide Web Services"

Click: "Application Development Features"

Check (enable) the features. I checked all but CGI.

IIS - this configuration section cannot be used at this path (configuration locking?)

MySQL server has gone away - in exactly 60 seconds

I have the same problem with mysqli. My solution is https://www.php.net/manual/en/mysqli.configuration.php

mysqli.reconnect = On

"element.dispatchEvent is not a function" js error caught in firebug of FF3.0

check for this by calling the library jquery after the noconflict.js or that this calling more than once jquery library after the noconflict.js

Inline functions in C#?

Update: Per konrad.kruczynski's answer, the following is true for versions of .NET up to and including 4.0.

You can use the MethodImplAttribute class to prevent a method from being inlined...

[MethodImpl(MethodImplOptions.NoInlining)]
void SomeMethod()
{
    // ...
}

...but there is no way to do the opposite and force it to be inlined.

How to load a jar file at runtime

Reloading existing classes with existing data is likely to break things.

You can load new code into new class loaders relatively easily:

ClassLoader loader = URLClassLoader.newInstance(
    new URL[] { yourURL },
    getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
Class<? extends Runnable> runClass = clazz.asSubclass(Runnable.class);
// Avoid Class.newInstance, for it is evil.
Constructor<? extends Runnable> ctor = runClass.getConstructor();
Runnable doRun = ctor.newInstance();
doRun.run();

Class loaders no longer used can be garbage collected (unless there is a memory leak, as is often the case with using ThreadLocal, JDBC drivers, java.beans, etc).

If you want to keep the object data, then I suggest a persistence mechanism such as Serialisation, or whatever you are used to.

Of course debugging systems can do fancier things, but are more hacky and less reliable.

It is possible to add new classes into a class loader. For instance, using URLClassLoader.addURL. However, if a class fails to load (because, say, you haven't added it), then it will never load in that class loader instance.

How do I iterate over a range of numbers defined by variables in Bash?

Here is why the original expression didn't work.

From man bash:

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.

So, brace expansion is something done early as a purely textual macro operation, before parameter expansion.

Shells are highly optimized hybrids between macro processors and more formal programming languages. In order to optimize the typical use cases, the language is made rather more complex and some limitations are accepted.

Recommendation

I would suggest sticking with Posix1 features. This means using for i in <list>; do, if the list is already known, otherwise, use while or seq, as in:

#!/bin/sh

limit=4

i=1; while [ $i -le $limit ]; do
  echo $i
  i=$(($i + 1))
done
# Or -----------------------
for i in $(seq 1 $limit); do
  echo $i
done


1. Bash is a great shell and I use it interactively, but I don't put bash-isms into my scripts. Scripts might need a faster shell, a more secure one, a more embedded-style one. They might need to run on whatever is installed as /bin/sh, and then there are all the usual pro-standards arguments. Remember shellshock, aka bashdoor?

How can I load the contents of a text file into a batch file variable?

Create a file called "SetFile.bat" that contains the following line with no carriage return at the end of it...

set FileContents=

Then in your batch file do something like this...

   @echo off
   copy SetFile.bat + %1 $tmp$.bat > nul
   call $tmp$.bat
   del $tmp$.bat

%1 is the name of your input file and %FileContents% will contain the contents of the input file after the call. This will only work on a one line file though (i.e. a file containing no carriage returns). You could strip out/replace carriage returns from the file before calling the %tmp%.bat if needed.

Detect end of ScrollView

I went through the solutions on the internet. Mostly solutions didn't work in the project I'm working on. Following solutions work fine for me.

Using onScrollChangeListener (works on API 23):

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollY;

                if(scrollY==0){
                    //top detected
                }
                if(bottom==0){
                    //bottom detected
                }
            }
        });
    }

using scrollChangeListener on TreeObserver

 scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollView.getScrollY();

            if(scrollView.getScrollY()==0){
                //top detected
            }
            if(bottom==0) {
                //bottom detected
            }
        }
    });

Hope this solution helps :)

Is there a MySQL option/feature to track history of changes to records?

The direct way of doing this is to create triggers on tables. Set some conditions or mapping methods. When update or delete occurs, it will insert into 'change' table automatically.

But the biggest part is what if we got lots columns and lots of table. We have to type every column's name of every table. Obviously, It's waste of time.

To handle this more gorgeously, we can create some procedures or functions to retrieve name of columns.

We can also use 3rd-part tool simply to do this. Here, I write a java program Mysql Tracker

ini_set("memory_limit") in PHP 5.3.3 is not working at all

Here's a list of things that are worth checking:

Is Suhosin installed?

ini_set

  • The format is important ini_set('memory_limit', '512'); // DIDN'T WORK ini_set('memory_limit', '512MB'); // DIDN'T WORK ini_set('memory_limit', '512M'); // OK - 512MB ini_set('memory_limit', 512000000); // OK - 512MB

When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.

http://php.net/manual/en/ini.core.php#ini.memory-limit

  • Has php_admin_value been used in .htaccess or virtualhost files?

Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or ini_set(). To clear a previously set value use none as the value.

http://php.net/manual/en/configuration.changes.php

"Proxy server connection failed" in google chrome

Internet explorer has a reset to factory button and luckily so does chrome! try the link below and let us know. the other option is to stop chrome and delete the c:\users\%username%\appdata\local\google folder entirely then reinstall chrome but this will loose all you local settings and data.

Google doc on how to factory reset: https://support.google.com/chrome/answer/3296214?hl=en

Adding git branch on the Bash command prompt

Here is how I configured the prompt to display Git status:

Get git-prompt script:

curl -o ~/.git-prompt.sh https://raw.githubusercontent.com/git/git/master/contrib/completion/git-prompt.sh

And customize your prompt adding the following code in your .bashrc file:

# Load Git functions
source ~/.git-prompt.sh

# Syntactic sugar for ANSI escape sequences
txtblk='\e[0;30m' # Black - Regular
txtred='\e[0;31m' # Red
txtgrn='\e[0;32m' # Green
txtylw='\e[0;33m' # Yellow
txtblu='\e[0;34m' # Blue
txtpur='\e[0;35m' # Purple
txtcyn='\e[0;36m' # Cyan
txtwht='\e[0;37m' # White
bldblk='\e[1;30m' # Black - Bold
bldred='\e[1;31m' # Red
bldgrn='\e[1;32m' # Green
bldylw='\e[1;33m' # Yellow
bldblu='\e[1;34m' # Blue
bldpur='\e[1;35m' # Purple
bldcyn='\e[1;36m' # Cyan
bldwht='\e[1;37m' # White
unkblk='\e[4;30m' # Black - Underline
undred='\e[4;31m' # Red
undgrn='\e[4;32m' # Green
undylw='\e[4;33m' # Yellow
undblu='\e[4;34m' # Blue
undpur='\e[4;35m' # Purple
undcyn='\e[4;36m' # Cyan
undwht='\e[4;37m' # White
bakblk='\e[40m'   # Black - Background
bakred='\e[41m'   # Red
badgrn='\e[42m'   # Green
bakylw='\e[43m'   # Yellow
bakblu='\e[44m'   # Blue
bakpur='\e[45m'   # Purple
bakcyn='\e[46m'   # Cyan
bakwht='\e[47m'   # White
txtrst='\e[0m'    # Text Reset

# Prompt variables
PROMPT_BEFORE="$txtcyn\u@\h $txtwht\w$txtrst"
PROMPT_AFTER="\\n\\\$ "

# Prompt command
PROMPT_COMMAND='__git_ps1 "$PROMPT_BEFORE" "$PROMPT_AFTER"'

# Git prompt features (read ~/.git-prompt.sh for reference)
export GIT_PS1_SHOWDIRTYSTATE="true"
export GIT_PS1_SHOWSTASHSTATE="true"
export GIT_PS1_SHOWUNTRACKEDFILES="true"
export GIT_PS1_SHOWUPSTREAM="auto"
export GIT_PS1_SHOWCOLORHINTS="true"

If you want to find out more, you can get all the dotfiles here: https://github.com/jamming/dotfiles

How can I get the day of a specific date with PHP

$date = '2009-10-22';
$sepparator = '-';
$parts = explode($sepparator, $date);
$dayForDate = date("l", mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]));

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

Calculate percentage Javascript

_x000D_
_x000D_
function calculate() {_x000D_
    // amount_x000D_
        var salary = parseInt($('#salary').val());_x000D_
    // percent    _x000D_
        var incentive_rate = parseInt($('#incentive_rate').val());_x000D_
        var perc = "";_x000D_
        if (isNaN(salary) || isNaN(incentive_rate)) {_x000D_
            perc = " ";_x000D_
        } else {_x000D_
            perc =  (incentive_rate/100) * salary;_x000D_
          _x000D_
_x000D_
        } $('#total_income').val(perc);_x000D_
    }
_x000D_
_x000D_
_x000D_

Better naming in Tuple classes than "Item1", "Item2"

I would write the Item names in the summay.. so by hovering over the function helloworld() the text will say hello = Item1 and world = Item2

 helloworld("Hi1,Hi2");

/// <summary>
/// Return hello = Item1 and world Item2
/// </summary>
/// <param name="input">string to split</param>
/// <returns></returns>
private static Tuple<bool, bool> helloworld(string input)
{
    bool hello = false;
    bool world = false;
    foreach (var hw in input.Split(','))
    {
        switch (hw)
        {
            case "Hi1":
                hello= true;
                break;
            case "Hi2":
                world= true;
                break;
        }

    }
    return new Tuple<bool, bool>(hello, world);
}

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

I had the same problem in my code. I was concatenating a string to create a string. Below is the part of code.

int scannerId = 1;
std:strring testValue;
strInXml = std::string(std::string("<inArgs>" \
                        "<scannerID>" + scannerId) + std::string("</scannerID>" \
                        "<cmdArgs>" \
                        "<arg-string>" + testValue) + "</arg-string>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "<arg-bool>FALSE</arg-bool>" \
                        "</cmdArgs>"\
                        "</inArgs>");

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

I think you are using the 64-bit version of the tool to install a 32-bit application. I've also faced this issue today and used this Framework path to cater .

C:\Windows\Microsoft.NET\Framework\v4.0.30319

and it should install your 32-bit application just fine.

What is Java String interning?

Since strings are objects and since all objects in Java are always stored only in the heap space, all strings are stored in the heap space. However, Java keeps strings created without using the new keyword in a special area of the heap space, which is called "string pool". Java keeps the strings created using the new keyword in the regular heap space.

The purpose of the string pool is to maintain a set of unique strings. Any time you create a new string without using the new keyword, Java checks whether the same string already exists in the string pool. If it does, Java returns a reference to the same String object and if it does not, Java creates a new String object in the string pool and returns its reference. So, for example, if you use the string "hello" twice in your code as shown below, you will get a reference to the same string. We can actually test this theory out by comparing two different reference variables using the == operator as shown in the following code:

String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2); //prints true

String str3 = new String("hello");
String str4 = new String("hello");

System.out.println(str1 == str3); //prints false
System.out.println(str3 == str4); //prints false 

== operator is simply checks whether two references point to the same object or not and returns true if they do. In the above code, str2 gets the reference to the same String object which was created earlier. However, str3 and str4 get references to two entirely different String objects. That is why str1 == str2 returns true but str1 == str3 and str3 == str4 return false . In fact, when you do new String("hello"); two String objects are created instead of just one if this is the first time the string "hello" is used in the anywhere in program - one in the string pool because of the use of a quoted string, and one in the regular heap space because of the use of new keyword.

String pooling is Java's way of saving program memory by avoiding the creation of multiple String objects containing the same value. It is possible to get a string from the string pool for a string created using the new keyword by using String's intern method. It is called "interning" of string objects. For example,

String str1 = "hello";
String str2 = new String("hello");
String str3 = str2.intern(); //get an interned string obj

System.out.println(str1 == str2); //prints false
System.out.println(str1 == str3); //prints true

OCP Java SE 11 Programmer, Deshmukh

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

After trying almost every post on this thread and reading through apple developer forums I found only one solution worked for me.

I am building a universal framework that is consumed in a swift app. I was unable to build to the Simulator without architecture errors.

In my Framework project I have a Universal Framework task in my build phases, if this is the case for you

  • Add the following to your xcodebuild task inside the build phase: EXCLUDED_ARCHS="arm64"

Next you have to change the following project Build Settings:

  • Delete the VALID_ARCHS user defined setting
  • Set ONLY_ACTIVE_ARCH to YES ***

*** If you are developing a framework and have a demo app as well, this setting has to be turned on in both projects.

UICollectionView cell selection and cell reuse

I had a horizontal scrolling collection view (I use collection view in Tableview) and I too faced problems withcell reuse, whenever I select one item and scroll towards right, some other cells in the next visible set gets select automatically. Trying to solve this using any custom cell properties like "selected", highlighted etc didnt help me so I came up with the below solution and this worked for me.

Step1:

Create a variable in the collectionView to store the selected index, here I have used a class level variable called selectedIndex

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    MyCVCell *cell = (MyCVCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"MyCVCell" forIndexPath:indexPath];    

// When scrolling happens, set the selection status only if the index matches the selected Index

if (selectedIndex == indexPath.row) {

        cell.layer.borderWidth = 1.0;

        cell.layer.borderColor = [[UIColor redColor] CGColor];

    }
    else
    {
        // Turn off the selection
        cell.layer.borderWidth = 0.0;

    }
    return cell;

}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{
    MyCVCell *cell = (MyCVCell *)[collectionView cellForItemAtIndexPath:indexPath];
    // Set the index once user taps on a cell
    selectedIndex = indexPath.row;
    // Set the selection here so that selection of cell is shown to ur user immediately
    cell.layer.borderWidth = 1.0;
    cell.layer.borderColor = [[UIColor redColor] CGColor];
    [cell setNeedsDisplay];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath

{

    MyCVCell *cell = (MyCVCell *)[collectionView cellForItemAtIndexPath:indexPath];

    // Set the index to an invalid value so that the cells get deselected
    selectedIndex = -1;
    cell.layer.borderWidth = 0.0;
    [cell setNeedsDisplay];

}

-anoop

Input jQuery get old value before onchange and get value after on change

If you only need a current value and above options don't work, you can use it this way.

$('#input').on('change', () => {
  const current = document.getElementById('input').value;
}

Choosing line type and color in Gnuplot 4.0

You need to use linecolor instead of lc, like:

set style line 1 lt 1 lw 3 pt 3 linecolor rgb "red"

"help set style line" gives you more info.

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

In addition to Tim's answer, which is very appropriate to your specific example, it's worth mentioning collections.defaultdict, which lets you do stuff like this:

>>> d = defaultdict(int)
>>> d[0] += 1
>>> d
{0: 1}
>>> d[4] += 1
>>> d
{0: 1, 4: 1}

For mapping [1, 2, 3, 4] as in your example, it's a fish out of water. But depending on the reason you asked the question, this may end up being a more appropriate technique.

Best Practice to Organize Javascript Library & CSS Folder Structure

 root/
   assets/
      lib/-------------------------libraries--------------------
          bootstrap/--------------Libraries can have js/css/images------------
              css/
              js/
              images/  
          jquery/
              js/
          font-awesome/
              css/
              images/
     common/--------------------common section will have application level resources             
          css/
          js/
          img/

 index.html

This is how I organized my application's static resources.

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

Joining pairs of elements of a list

Well I would do it this way as I am no good with Regs..

CODE

t = '1. eat, food\n\
7am\n\
2. brush, teeth\n\
8am\n\
3. crack, eggs\n\
1pm'.splitlines()

print [i+j for i,j in zip(t[::2],t[1::2])]

output:

['1. eat, food   7am', '2. brush, teeth   8am', '3. crack, eggs   1pm']  

Hope this helps :)

How to find a value in an array and remove it by using PHP array functions?

The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)

What is the http-header "X-XSS-Protection"?

TL;DR: All well written web sites (/apps) must emit the header X-XSS-Protection: 0 and just forget about this feature. If you want to have extra security that better user agents can provide, use a strict Content-Security-Policy header.

Long answer:

HTTP header X-XSS-Protection is one of those things that Microsoft introduced in Internet Explorer 8.0 (MSIE 8) that was supposed to improve security of incorrectly written web sites.

The idea is to apply some kind of heuristics to try to detect reflection XSS attack and automatically neuter the attack.

The problematic part of this is "heuristics" and "neutering". The heuristics causes false positives and neutering cannot be safely done because it causes side-effects that can be used to implement XSS attacks and DoS attacks on perfectly safe web sites.

The bad part is that if a web site does not emit the header X-XSS-Protection then the browser will behave as if the header X-XSS-Protection: 1 had been emitted. The worst part is that this value is the least-safe value of all possible values for this header!

For a given secure web site (that is, the site does not have reflected XSS vulnerabilities) this "XSS protection" feature allows following attacks:

X-XSS-Protection: 1 allows attacker to selectively block parts of JavaScript and keep rest of the scripts running. This is possible because the heuristics of this feature are simply "if value of any GET parameter is found in the scripting part of the page source, the script will be automatically modified in user agent dependant way". In practice, the attacker can e.g. add parameter disablexss=<script src="framebuster.js" and the browser will automatically remove the string <script src="framebuster.js" from the actual page source. Note that the rest of the page continues run and the attacker just removed this part of page security. In practice, any JS in the page source can be modified. For some cases, a page without XSS vulnerability having reflected content can be used to run selected JavaScript on page due the neutering incorrectly turning plain text data into executable JavaScript code. (That is, turn textual data within a normal DOM text node into content of <script> tag and execute it!)

X-XSS-Protection: 1; mode=block allows attacker to leak data from the page source by using the behavior of the page as side-channel. For example, if the page contains JavaScript code along the lines of var csrf_secret="521231347843", the attacker simply adds an extra parameter e.g. leak=var%20csrf_secret="3 and if the page is NOT blocked, the 3 was incorrect first digit. The attacker tries again, this time leak=var%20csrf_secret="5 and the page loading will be aborted. This allows the attacker to know that the first digit of the secret is 5. The attacker then continues to guess the next digit. This allows easily brute-forcing of CSRF secrets or any other secret value in the <script> source.

In the end, if your site is full of XSS reflection attacks, using the default value of 1 will reduce the attack surface a little bit. However, if your site is secure and you don't emit X-XSS-Protection: 0, your site will be vulnerable with any browser that supports this feature. If you want defense in depth support from browsers against yet-unknown XSS vulnerabilities on your site, use a strict Content-Security-Policy header and keep sending 0 for this mis-feature. That doesn't open your site to any known vulnerabilities.

Currently this feature is enabled by default in MSIE, Safari and Google Chrome. This used to be enabled in Edge but Microsoft already removed this mis-feature from Edge. Mozilla Firefox never implemented this.

See also:

https://homakov.blogspot.com/2013/02/hacking-facebook-with-oauth2-and-chrome.html https://blog.innerht.ml/the-misunderstood-x-xss-protection/ http://p42.us/ie8xss/Abusing_IE8s_XSS_Filters.pdf https://www.slideshare.net/masatokinugawa/xxn-en https://bugs.chromium.org/p/chromium/issues/detail?id=396544 https://bugs.chromium.org/p/chromium/issues/detail?id=498982

Encrypt Password in Configuration Files?

See what is available in Jetty for storing password (or hashes) in configuration files, and consider if the OBF encoding might be useful for you. Then see in the source how it is done.

http://www.eclipse.org/jetty/documentation/current/configuring-security-secure-passwords.html

How to find whether a ResultSet is empty or not in Java?

Definitely this gives good solution,

ResultSet rs = stmt.execute("SQL QUERY");
// With the above statement you will not have a null ResultSet 'rs'.
// In case, if any exception occurs then next line of code won't execute.
// So, no problem if I won't check rs as null.

if (rs.next()) {
    do {
      // Logic to retrieve the data from the resultset.
      // eg: rs.getString("abc");
    } while(rs.next());
} else {
    // No data
}

Pods stuck in Terminating status

Before doing a force deletion i would first do some checks. 1- node state: get the node name where your node is running, you can see this with the following command:

"kubectl -n YOUR_NAMESPACE describe pod YOUR_PODNAME"

Under the "Node" label you will see the node name. With that you can do:

kubectl describe node NODE_NAME

Check the "conditions" field if you see anything strange. If this is fine then you can move to the step, redo:

"kubectl -n YOUR_NAMESPACE describe pod YOUR_PODNAME"

Check the reason why it is hanging, you can find this under the "Events" section. I say this because you might need to take preliminary actions before force deleting the pod, force deleting the pod only deletes the pod itself not the underlying resource (a stuck docker container for example).

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

WPF MVVM ComboBox SelectedItem or SelectedValue not working

I had this problem with a ComboBox displaying a list of colors ( List<Brush> ).
Selecting a color was possible but it wasnt displayed when the selection closed (although the property was changed!)

The fix was overwriting the Equals(object obj) method for the type selected in the ComboBox (Brush), which wasnt simple because Brush is sealed. So i wrote a class EqualityBrush containing a Brush and implementing Equals:

public class EqualityBrush
{
    public SolidColorBrush Brush { get; set; }

    public override bool Equals(object o)
    {
        if (o is EqualityBrush)
        {
            SolidColorBrush b = ((EqualityBrush)o).Brush;
            return b.Color.R == this.Brush.Color.R && b.Color.G == this.Brush.Color.G && b.Color.B == this.Brush.Color.B;
        }
        else
            return false;
    }
}

Using a List of my new EqualityBrush class instead of normal Brush class fixed the problem!

My Combobox XAML looks like this:

<ComboBox ItemsSource="{Binding BuerkertBrushes}" SelectedItem="{Binding Brush, Mode=TwoWay}" Width="40">
    <ComboBox.Resources>
        <DataTemplate DataType="{x:Type tree:EqualityBrush}">
            <Rectangle Width="20" Height="12" Fill="{Binding Brush}"/>
        </DataTemplate>
    </ComboBox.Resources>
</ComboBox>

Remember that my "Brush"-Property in the ViewModel now has to be of Type EqualityBrush!

Double % formatting question for printf in Java

Yes, %d means decimal, but it means decimal number system, not decimal point.

Further, as a complement to the former post, you can also control the number of decimal points to show. Try this,

System.out.printf("%.2f %.1f",d,f); // prints 1.20 1.2

For more please refer to the API docs.

(change) vs (ngModelChange) in angular

As I have found and wrote in another topic - this applies to angular < 7 (not sure how it is in 7+)

Just for the future

we need to observe that [(ngModel)]="hero.name" is just a short-cut that can be de-sugared to: [ngModel]="hero.name" (ngModelChange)="hero.name = $event".

So if we de-sugar code we would end up with:

<select (ngModelChange)="onModelChange()" [ngModel]="hero.name" (ngModelChange)="hero.name = $event">

or

<[ngModel]="hero.name" (ngModelChange)="hero.name = $event" select (ngModelChange)="onModelChange()">

If you inspect the above code you will notice that we end up with 2 ngModelChange events and those need to be executed in some order.

Summing up: If you place ngModelChange before ngModel, you get the $event as the new value, but your model object still holds previous value. If you place it after ngModel, the model will already have the new value.

SOURCE

Adjust list style image position?

Another workaround is just to set the li item to flex or inline-flex. Depending on the circumstances that may suit you better. In case you have a real icon / image placed in the HTML the default flex position is on the central horizontal line.

Sending GET request with Authentication headers using restTemplate

A simple solution would be to configure static http headers needed for all calls in the bean configuration of the RestTemplate:

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate getRestTemplate(@Value("${did-service.bearer-token}") String bearerToken) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getInterceptors().add((request, body, clientHttpRequestExecution) -> {
            HttpHeaders headers = request.getHeaders();
            if (!headers.containsKey("Authorization")) {
                String token = bearerToken.toLowerCase().startsWith("bearer") ? bearerToken : "Bearer " + bearerToken;
                request.getHeaders().add("Authorization", token);
            }
            return clientHttpRequestExecution.execute(request, body);
        });
        return restTemplate;
    }
}

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

To improve the effectiveness of class='ng-cloak' approach when scripts are loaded last, make sure the following css is loaded in the head of the document:

.ng-cloak { display:none; }

MVC razor form with multiple different submit buttons?

This answer will show you that how to work in asp.net with razor, and to control multiple submit button event. Lets for example we have two button, one button will redirect us to "PageA.cshtml" and other will redirect us to "PageB.cshtml".

@{
  if (IsPost)
    {
       if(Request["btn"].Equals("button_A"))
        {
          Response.Redirect("PageA.cshtml");
        }
      if(Request[&quot;btn"].Equals("button_B"))
        {
          Response.Redirect(&quot;PageB.cshtml&quot;);
        }
  }
}
<form method="post">
   <input type="submit" value="button_A" name="btn"/>;
   <input type="submit" value="button_B" name="btn"/>;          
</form>

How to randomize Excel rows

Here's a macro that allows you to shuffle selected cells in a column:

Option Explicit

Sub ShuffleSelectedCells()
  'Do nothing if selecting only one cell
  If Selection.Cells.Count = 1 Then Exit Sub
  'Save selected cells to array
  Dim CellData() As Variant
  CellData = Selection.Value
  'Shuffle the array
  ShuffleArrayInPlace CellData
  'Output array to spreadsheet
  Selection.Value = CellData
End Sub

Sub ShuffleArrayInPlace(InArray() As Variant)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' ShuffleArrayInPlace
' This shuffles InArray to random order, randomized in place.
' Source: http://www.cpearson.com/excel/ShuffleArray.aspx
' Modified by Tom Doan to work with Selection.Value two-dimensional arrays.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
  Dim J As Long, _
    N As Long, _
    Temp As Variant
  'Randomize
  For N = LBound(InArray) To UBound(InArray)
    J = CLng(((UBound(InArray) - N) * Rnd) + N)
    If J <> N Then
      Temp = InArray(N, 1)
      InArray(N, 1) = InArray(J, 1)
      InArray(J, 1) = Temp
    End If
  Next N
End Sub

You can read the comments to see what the macro is doing. Here's how to install the macro:

  1. Open the VBA editor (Alt + F11).
  2. Right-click on "ThisWorkbook" under your currently open spreadsheet (listed in parentheses after "VBAProject") and select Insert / Module.
  3. Paste the code above and save the spreadsheet.

Now you can assign the "ShuffleSelectedCells" macro to an icon or hotkey to quickly randomize your selected rows (keep in mind that you can only select one column of rows).

Difference between ref and out parameters in .NET

They're pretty much the same - the only difference is that a variable you pass as an out parameter doesn't need to be initialized but passing it as a ref parameter it has to be set to something.

int x;
Foo(out x); // OK

int y;
Foo(ref y); // Error: y should be initialized before calling the method

Ref parameters are for data that might be modified, out parameters are for data that's an additional output for the function (eg int.TryParse) that are already using the return value for something.

Parsing command-line arguments in C

Use getopt(), or perhaps getopt_long().

int iflag = 0;
enum { WORD_MODE, LINE_MODE } op_mode = WORD_MODE;  // Default set
int opt;

while ((opt = getopt(argc, argv, "ilw") != -1)
{
    switch (opt)
    {
    case 'i':
        iflag = 1;
        break;
    case 'l':
        op_mode = LINE_MODE;
        break;
    case 'w':
        op_mode = WORD_MODE;
        break;
    default:
        fprintf(stderr, "Usage: %s [-ilw] [file ...]\n", argv[0]);
        exit(EXIT_FAILURE);
    }
}

/* Process file names or stdin */
if (optind >= argc)
    process(stdin, "(standard input)", op_mode);
else
{
    int i;
    for (i = optind; i < argc; i++)
    {
        FILE *fp = fopen(argv[i], "r");
        if (fp == 0)
            fprintf(stderr, "%s: failed to open %s (%d %s)\n",
                    argv[0], argv[i], errno, strerror(errno));
        else
        {
            process(fp, argv[i], op_mode);
            fclose(fp);
        }
    }
 }

Note that you need to determine which headers to include (I make it 4 that are required), and the way I wrote the op_mode type means you have a problem in the function process() - you can't access the enumeration down there. It's best to move the enumeration outside the function; you might even make op_mode a file-scope variable without external linkage (a fancy way of saying static) to avoid passing it to the function. This code does not handle - as a synonym for standard input, another exercise for the reader. Note that getopt() automatically takes care of -- to mark the end of options for you.

I've not run any version of the typing above past a compiler; there could be mistakes in it.


For extra credit, write a (library) function:

int filter(int argc, char **argv, int idx, int (*function)(FILE *fp, const char *fn));

which encapsulates the logic for processing file name options after the getopt() loop. It should handle - as standard input. Note that using this would indicate that op_mode should be a static file scope variable. The filter() function takes argc, argv, optind and a pointer to the processing function. It should return 0 (EXIT_SUCCESS) if it was able to open all the files and all invocations of the function reported 0, otherwise 1 (or EXIT_FAILURE). Having such a function simplifies writing Unix-style 'filter' programs that read files specified on the command line or standard input.

Netbeans 8.0.2 The module has not been deployed

Try to change Tomcat version, in my case tomcat "8.0.41" and "8.5.8" didn't work. But "8.5.37" worked fine.

What is difference between arm64 and armhf?

armhf stands for "arm hard float", and is the name given to a debian port for arm processors (armv7+) that have hardware floating point support.

On the beaglebone black, for example:

:~$ dpkg --print-architecture
armhf

Although other commands (such as uname -a or arch) will just show armv7l

:~$ cat /proc/cpuinfo 
processor       : 0
model name      : ARMv7 Processor rev 2 (v7l)
BogoMIPS        : 995.32
Features        : half thumb fastmult vfp edsp thumbee neon vfpv3 tls
...

The vfpv3 listed under Features is what refers to the floating point support.

Incidentally, armhf, if your processor supports it, basically supersedes Raspbian, which if I understand correctly was mainly a rebuild of armhf with work arounds to deal with the lack of floating point support on the original raspberry pi's. Nowdays, of course, there's a whole ecosystem build up around Raspbian, so they're probably not going to abandon it. However, this is partly why the beaglebone runs straight debian, and that's ok even if you're used to Raspbian, unless you want some of the special included non-free software such as Mathematica.

sql like operator to get the numbers only

You can use the following to only include valid characters:

SQL

SELECT * FROM @Table
WHERE Col NOT LIKE '%[^0-9.]%'

Results

Col
---------
234.62
6435.23
2

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

PostgreSQL Error: Relation already exists

In my case, I had a sequence with the same name.

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

How to submit a form using PhantomJS

I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:

var page = new WebPage(), testindex = 0, loadInProgress = false;

page.onConsoleMessage = function(msg) {
  console.log(msg);
};

page.onLoadStarted = function() {
  loadInProgress = true;
  console.log("load started");
};

page.onLoadFinished = function() {
  loadInProgress = false;
  console.log("load finished");
};

var steps = [
  function() {
    //Load Login Page
    page.open("https://website.com/theformpage/");
  },
  function() {
    //Enter Credentials
    page.evaluate(function() {

      var arr = document.getElementsByClassName("login-form");
      var i;

      for (i=0; i < arr.length; i++) { 
        if (arr[i].getAttribute('method') == "POST") {

          arr[i].elements["email"].value="mylogin";
          arr[i].elements["password"].value="mypassword";
          return;
        }
      }
    });
  }, 
  function() {
    //Login
    page.evaluate(function() {
      var arr = document.getElementsByClassName("login-form");
      var i;

      for (i=0; i < arr.length; i++) {
        if (arr[i].getAttribute('method') == "POST") {
          arr[i].submit();
          return;
        }
      }

    });
  }, 
  function() {
    // Output content of page to stdout after form has been submitted
    page.evaluate(function() {
      console.log(document.querySelectorAll('html')[0].outerHTML);
    });
  }
];


interval = setInterval(function() {
  if (!loadInProgress && typeof steps[testindex] == "function") {
    console.log("step " + (testindex + 1));
    steps[testindex]();
    testindex++;
  }
  if (typeof steps[testindex] != "function") {
    console.log("test complete!");
    phantom.exit();
  }
}, 50);

Reading JSON from a file?

You can use pandas library to read the JSON file.

import pandas as pd
df = pd.read_json('strings.json',lines=True)
print(df)

How abstraction and encapsulation differ?

As I knowit, encapsulation is hiding data of classes in themselves, and only making it accessible via setters / getters, if they must be accessed from the outer world.

Abstraction is the class design for itself.

Means, how You create Your class tree, which methods are general ones, which are inherited, which can be overridden,which attributes are only on private level, or on protected, how Do You build up Your class inheritance tree, Do You use final classes, abtract classes, interface-implementation.

Abstraction is more placed the oo-design phase, while encapsulation also enrolls into developmnent-phase.

Copy and Paste a set range in the next empty row

Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):

EDIT: edited for pasting values only based on comments below.

Private Sub CommandButton1_Click()
  Application.ScreenUpdating = False
  Dim copySheet As Worksheet
  Dim pasteSheet As Worksheet

  Set copySheet = Worksheets("Sheet1")
  Set pasteSheet = Worksheets("Sheet2")

  copySheet.Range("A3:E3").Copy
  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
  Application.CutCopyMode = False
  Application.ScreenUpdating = True
End Sub

Get element from within an iFrame

You can use this function to query for any element on the page, regardless of if it is nested inside of an iframe (or many iframes):

function querySelectorAllInIframes(selector) {
  let elements = [];

  const recurse = (contentWindow = window) => {

    const iframes = contentWindow.document.body.querySelectorAll('iframe');
    iframes.forEach(iframe => recurse(iframe.contentWindow));
    
    elements = elements.concat(contentWindow.document.body.querySelectorAll(selector));
  }

  recurse();

  return elements;
};

querySelectorAllInIframes('#elementToBeFound');

Note: Keep in mind that each of the iframes on the page will need to be of the same-origin, or this function will throw an error.

Where can I find my Facebook application id and secret key?

I had a hard time finding where it is so here the image depicting it in 2019.  the location of app secret and app id in 2019.

How to create a temporary directory?

Use mktemp -d. It creates a temporary directory with a random name and makes sure that file doesn't already exist. You need to remember to delete the directory after using it though.

Empty responseText from XMLHttpRequest

PROBLEM RESOLVED

In my case the problem was that I do the ajax call (with $.ajax, $.get or $.getJSON methods from jQuery) with full path in the url param:

url: "http://mydomain.com/site/cgi-bin/serverApp.php"

But the correct way is to pass the value of url as:

url: "site/cgi-bin/serverApp.php"

Some browser don't conflict and make no distiction between one text or another, but in Firefox 3.6 for Mac OS take this full path as "cross site scripting"... another thing, in the same browser there is a distinction between:

http://mydomain.com/site/index.html

And put

http://www.mydomain.com/site/index.html

In fact it is the correct point view, but most implementations make no distinction, so the solution was to remove all the text that specify the full path to the script in the methods that do the ajax request AND.... remove any BASE tag in the index.html file

base href="http://mydomain.com/" <--- bad idea, remove it!

If you don't remove it, this version of browser for this system may take your ajax request like if it is a cross site request!

I have the same problem but only on the Mac OS machine. The problem is that Firefox treat the ajax response as an "cross site" call, in any other machine/browser it works fine. I didn't found any help about this (I think that is a firefox implementation issue), but I'm going to prove the next code at the server side:

header('Content-type: application/json');

to ensure that browser get the data as "json data" ...

Deserialize JSON to ArrayList<POJO> using Jackson

This works for me.

@Test
public void cloneTest() {
    List<Part> parts = new ArrayList<Part>();
    Part part1 = new Part(1);
    parts.add(part1);
    Part part2 = new Part(2);
    parts.add(part2);
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = objectMapper.writeValueAsString(parts);

        List<Part> cloneParts = objectMapper.readValue(jsonStr, new TypeReference<ArrayList<Part>>() {});
    } catch (Exception e) {
        //fail("failed.");
        e.printStackTrace();
    }

    //TODO: Assert: compare both list values.
}

Aliases in Windows command prompt

To add to josh's answer,

you may make the alias(es) persistent with the following steps,

  1. Create a .bat or .cmd file with your DOSKEY commands.
  2. Run regedit and go to HKEY_CURRENT_USER\Software\Microsoft\Command Processor
  3. Add String Value entry with the name AutoRun and the full path of your .bat/.cmd file.

    For example, %USERPROFILE%\alias.cmd, replacing the initial segment of the path with %USERPROFILE% is useful for syncing among multiple machines.

This way, every time cmd is run, the aliases are loaded.

For Windows 10, add the entry to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor instead.

For completeness, here is a template to illustrate the kind of aliases one may find useful.

@echo off

:: Temporary system path at cmd startup

set PATH=%PATH%;"C:\Program Files\Sublime Text 2\"

:: Add to path by command

DOSKEY add_python26=set PATH=%PATH%;"C:\Python26\"
DOSKEY add_python33=set PATH=%PATH%;"C:\Python33\"

:: Commands

DOSKEY ls=dir /B
DOSKEY sublime=sublime_text $*  
    ::sublime_text.exe is name of the executable. By adding a temporary entry to system path, we don't have to write the whole directory anymore.
DOSKEY gsp="C:\Program Files (x86)\Sketchpad5\GSP505en.exe"
DOSKEY alias=notepad %USERPROFILE%\Dropbox\alias.cmd

:: Common directories

DOSKEY dropbox=cd "%USERPROFILE%\Dropbox\$*"
DOSKEY research=cd %USERPROFILE%\Dropbox\Research\

  • Note that the $* syntax works after a directory string as well as an executable which takes in arguments. So in the above example, the user-defined command dropbox research points to the same directory as research.
  • As Rivenfall pointed out, it is a good idea to include a command that allows for convenient editing of the alias.cmd file. See alias above. If you are in a cmd session, enter cmd to restart cmd and reload the alias.cmd file.

When I searched the internet for an answer to the question, somehow the discussions were either focused on persistence only or on some usage of DOSKEY only. I hope someone will benefit from these two aspects being together here!


Here's a .reg file to help you install the alias.cmd. It's set now as an example to a dropbox folder as suggested above.

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"AutoRun"="%USERPROFILE%\\alias.cmd"

For single-user applications, the above will do. Nevertheless, there are situations where it is necessary to check whether alias.cmd exists first in the registry key. See example below.

In a C:\Users\Public\init.cmd file hosting potentially cross-user configurations:

@ECHO OFF
REM Add other configurations as needed
IF EXIST "%USERPROFILE%\alias.cmd" ( CALL "%USERPROFILE%\alias.cmd" )

The registry key should be updated correspondly to C:\Users\Public\init.cmd or, using the .reg file:

Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
"AutoRun"="C:\\Users\\Public\\init.cmd"

Datagridview: How to set a cell in editing mode?

Setting the CurrentCell and then calling BeginEdit(true) works well for me.

The following code shows an eventHandler for the KeyDown event that sets a cell to be editable.

My example only implements one of the required key press overrides but in theory the others should work the same. (and I'm always setting the [0][0] cell to be editable but any other cell should work)

    private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Tab && dataGridView1.CurrentCell.ColumnIndex == 1)
        {
            e.Handled = true;
            DataGridViewCell cell = dataGridView1.Rows[0].Cells[0];
            dataGridView1.CurrentCell = cell;
            dataGridView1.BeginEdit(true);               
        }
    }

If you haven't found it previously, the DataGridView FAQ is a great resource, written by the program manager for the DataGridView control, which covers most of what you could want to do with the control.

One command to create a directory and file inside it linux command

add this to ~/.bashrc:

function mkfile() { 
    mkdir -p  "$1" && touch  "$1"/"$2" 
}

save and then to make it available without a reboot or logout execute: $ source ~/.bashrc or you can just do:

$ mkdir folder && touch $_/file.txt

note that $_ = folder

Finding three elements in an array whose sum is closest to a given number

How about something like this, which is O(n^2)

for(each ele in the sorted array)
{
    ele = arr[i] - YOUR_NUMBER;
    let front be the pointer to the front of the array;
    let rear be the pointer to the rear element of the array.;

    // till front is not greater than rear.                    
    while(front <= rear)
    {
        if(*front + *rear == ele)
        {
            print "Found triplet "<<*front<<","<<*rear<<","<<ele<<endl;
            break;
        }
        else
        {
            // sum is > ele, so we need to decrease the sum by decrementing rear pointer.
            if((*front + *rear) > ele)
                decrement rear pointer.
            // sum is < ele, so we need to increase the sum by incrementing the front pointer.
            else
                increment front pointer.
        }
    }

This finds if sum of 3 elements is exactly equal to your number. If you want closest, you can modify it to remember the smallest delta(difference between your number of current triplet) and at the end print the triplet corresponding to smallest delta.

List comprehension vs map

I consider that the most Pythonic way is to use a list comprehension instead of map and filter. The reason is that list comprehensions are clearer than map and filter.

In [1]: odd_cubes = [x ** 3 for x in range(10) if x % 2 == 1] # using a list comprehension

In [2]: odd_cubes_alt = list(map(lambda x: x ** 3, filter(lambda x: x % 2 == 1, range(10)))) # using map and filter

In [3]: odd_cubes == odd_cubes_alt
Out[3]: True

As you an see, a comprehension does not require extra lambda expressions as map needs. Furthermore, a comprehension also allows filtering easily, while map requires filter to allow filtering.

SQL Server 2008- Get table constraints

You should use the current sys catalog views (if you're on SQL Server 2005 or newer - the sysobjects views are deprecated and should be avoided) - check out the extensive MSDN SQL Server Books Online documentation on catalog views here.

There are quite a few views you might be interested in:

  • sys.default_constraints for default constraints on columns
  • sys.check_constraints for check constraints on columns
  • sys.key_constraints for key constraints (e.g. primary keys)
  • sys.foreign_keys for foreign key relations

and a lot more - check it out!

You can query and join those views to get the info needed - e.g. this will list the tables, columns and all default constraints defined on them:

SELECT 
    TableName = t.Name,
    ColumnName = c.Name,
    dc.Name,
    dc.definition
FROM sys.tables t
INNER JOIN sys.default_constraints dc ON t.object_id = dc.parent_object_id
INNER JOIN sys.columns c ON dc.parent_object_id = c.object_id AND c.column_id = dc.parent_column_id
ORDER BY t.Name

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

How to get the number of characters in a string

Depends a lot on your definition of what a "character" is. If "rune equals a character " is OK for your task (generally it isn't) then the answer by VonC is perfect for you. Otherwise, it should be probably noted, that there are few situations where the number of runes in a Unicode string is an interesting value. And even in those situations it's better, if possible, to infer the count while "traversing" the string as the runes are processed to avoid doubling the UTF-8 decode effort.

How can I add an item to a ListBox in C# and WinForms?

If you are adding integers, as you say in your question, this will add 50 (from 1 to 50):

for (int x = 1; x <= 50; x++)
{
   list.Items.Add(x);
}

You do not need to set DisplayMember and ValueMember unless you are adding objects that have specific properties that you want to display to the user. In your example:

listbox1.Items.Add(new { clan = "Foo", sifOsoba = 1234 });

When to encode space to plus (+) or %20?

So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.

The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.

Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').

But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.

Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)

But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.

How do I get an OAuth 2.0 authentication token in C#

https://github.com/IdentityModel/IdentityModel adds extensions to HttpClient to acquire tokens using different flows and the documentation is great too. It's very handy because you don't have to think how to implement it yourself. I'm not aware if any official MS implementation exists.

How to ignore SSL certificate errors in Apache HttpClient 4.0

fwiw, an example using "RestEasy" implementation of JAX-RS 2.x to build a special "trust all" client...

    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.security.GeneralSecurityException;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.Arrays;
    import javax.ejb.Stateless;
    import javax.net.ssl.SSLContext;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    import org.apache.http.config.Registry;
    import org.apache.http.config.RegistryBuilder;
    import org.apache.http.conn.HttpClientConnectionManager;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.jboss.resteasy.client.jaxrs.ResteasyClient;
    import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
    import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
    import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
    import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
    import org.apache.http.conn.socket.ConnectionSocketFactory;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.ssl.SSLContexts;

    @Stateless
    @Path("/postservice")
    public class PostService {

        private static final Logger LOG = LogManager.getLogger("PostService");

        public PostService() {
        }

        @GET
        @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
        public PostRespDTO get() throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException, GeneralSecurityException {

            //...object passed to the POST method...
            PostDTO requestObject = new PostDTO();
            requestObject.setEntryAList(new ArrayList<>(Arrays.asList("ITEM0000A", "ITEM0000B", "ITEM0000C")));
            requestObject.setEntryBList(new ArrayList<>(Arrays.asList("AAA", "BBB", "CCC")));

            //...build special "trust all" client to call POST method...
            ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(createTrustAllClient());

            ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
            ResteasyWebTarget target = client.target("https://localhost:7002/postRespWS").path("postrespservice");
            Response response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(requestObject, MediaType.APPLICATION_JSON));

            //...object returned from the POST method...
            PostRespDTO responseObject = response.readEntity(PostRespDTO.class);

            response.close();

            return responseObject;
        }


        //...get special "trust all" client...
        private static CloseableHttpClient createTrustAllClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, TRUSTALLCERTS).useProtocol("TLS").build();
            HttpClientBuilder builder = HttpClientBuilder.create();
            NoopHostnameVerifier noop = new NoopHostnameVerifier();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, noop);
            builder.setSSLSocketFactory(sslConnectionSocketFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory).build();
            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
            builder.setConnectionManager(ccm);

            return builder.build();
        }


        private static final TrustStrategy TRUSTALLCERTS = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
                return true;
            }
        };
    }

related Maven dependencies

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.0.10.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>jaxrs-api</artifactId>
        <version>3.0.10.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson2-provider</artifactId>
        <version>3.0.10.Final</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency> 

Applying a single font to an entire website with CSS

in Bootstrap, web inspector says the Headings are set to 'inherit'

all i needed to set my page to the new font was

div, p {font-family: Algerian}

that's in .scss

How do you round to 1 decimal place in Javascript?

Math.round( mul/count * 10 ) / 10

Math.round(Math.sqrt(sqD/y) * 10 ) / 10

Thanks

Accessing members of items in a JSONArray with Java

In case it helps someone else, I was able to convert to an array by doing something like this,

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...or you should be able to get the length

((JSONArray) myJsonArray).toArray().length

Change IPython/Jupyter notebook working directory

As MrFancypants mentioned in the comments, if you are using Jupyter (which you should, since it currently supersedes the older IPython Notebook project), things are a little different. For one, there are no profiles any more.

After installing Jupyter, first check your ~/.jupyter folder to see its content. If no config files were migrated from the default IPython profile (as they weren't in my case), create a new one for Jupyter Notebook:

jupyter notebook --generate-config

This generates ~/.jupyter/jupyter_notebook_config.py file with some helpfully commented possible options. To set the default directory add:

c.NotebookApp.notebook_dir = u'/absolute/path/to/notebook/directory'

As I switch between Linux and OS X, I wanted to use a path relative to my home folder (as they differ – /Users/username and /home/username), so I set something like:

import os
c.NotebookApp.notebook_dir = os.path.expanduser('~/Dropbox/dev/notebook')

Now, whenever I run jupyter notebook, it opens my desired notebook folder. I also version the whole ~/.jupyter folder in my dotfiles repository that I deploy to every new work machine.


As an aside, you can still use the --notebook-dir command line option, so maybe a simple alias would suit your needs better.

jupyter notebook --notebook-dir=/absolute/path/to/notebook/directory

How to take character input in java

You can simply use (char) System.in.read(); casting to char is necessary to convert int to char

How to parse a string into a nullable int

You can do this in one line, using the conditional operator and the fact that you can cast null to a nullable type (two lines, if you don't have a pre-existing int you can reuse for the output of TryParse):

Pre C#7:

int tempVal;
int? val = Int32.TryParse(stringVal, out tempVal) ? Int32.Parse(stringVal) : (int?)null;

With C#7's updated syntax that allows you to declare an output variable in the method call, this gets even simpler.

int? val = Int32.TryParse(stringVal, out var tempVal) ? tempVal : (int?)null;

Https Connection Android

I'm making a guess, but if you want an actual handshake to occur, you have to let android know of your certificate. If you want to just accept no matter what, then use this pseudo-code to get what you need with the Apache HTTP Client:

SchemeRegistry schemeRegistry = new SchemeRegistry ();

schemeRegistry.register (new Scheme ("http",
    PlainSocketFactory.getSocketFactory (), 80));
schemeRegistry.register (new Scheme ("https",
    new CustomSSLSocketFactory (), 443));

ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager (
    params, schemeRegistry);


return new DefaultHttpClient (cm, params);

CustomSSLSocketFactory:

public class CustomSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory
{
private SSLSocketFactory FACTORY = HttpsURLConnection.getDefaultSSLSocketFactory ();

public CustomSSLSocketFactory ()
    {
    super(null);
    try
        {
        SSLContext context = SSLContext.getInstance ("TLS");
        TrustManager[] tm = new TrustManager[] { new FullX509TrustManager () };
        context.init (null, tm, new SecureRandom ());

        FACTORY = context.getSocketFactory ();
        }
    catch (Exception e)
        {
        e.printStackTrace();
        }
    }

public Socket createSocket() throws IOException
{
    return FACTORY.createSocket();
}

 // TODO: add other methods like createSocket() and getDefaultCipherSuites().
 // Hint: they all just make a call to member FACTORY 
}

FullX509TrustManager is a class that implements javax.net.ssl.X509TrustManager, yet none of the methods actually perform any work, get a sample here.

Good Luck!

How to set up devices for VS Code for a Flutter emulator

From version 2.13.0 of Dart Code, emulators can be launched directly from within Code but This feature relies on support from the Flutter tools which means it will only show emulators when using a very recent Flutter SDK. Flutter’s master channel already has this change, but it may take a little longer to filter through to the dev and beta channels.

I tested this feature and worked very well on flutter version 0.5.6-pre.61 (master channel)

enter image description here

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

For Go 1.13+:

go env -w GOPATH=$HOME/go

To set the GOPATH regardless of the GO version add the following line to your ~/.bashrc:

export GOPATH=$HOME/go

and don't forget to source your .bashrc file:

source ~/.bashrc

More options on the golang official wiki: https://github.com/golang/go/wiki/SettingGOPATH

Get the records of last month in SQL server

If you are looking for previous month data:

date(date_created)>=date_sub(date_format(curdate(),"%Y-%m-01"),interval 1 month) and 
date(date_created)<=date_sub(date_format(curdate(),'%Y-%m-01'),interval 1 day)

This will also work when the year changes. It will also work on MySQL.

How to wait for a number of threads to complete?

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DoSomethingInAThread implements Runnable
{
   public static void main(String[] args) throws ExecutionException, InterruptedException
   {
      //limit the number of actual threads
      int poolSize = 10;
      ExecutorService service = Executors.newFixedThreadPool(poolSize);
      List<Future<Runnable>> futures = new ArrayList<Future<Runnable>>();

      for (int n = 0; n < 1000; n++)
      {
         Future f = service.submit(new DoSomethingInAThread());
         futures.add(f);
      }

      // wait for all tasks to complete before continuing
      for (Future<Runnable> f : futures)
      {
         f.get();
      }

      //shut down the executor service so that this thread can exit
      service.shutdownNow();
   }

   public void run()
   {
      // do something here
   }
}

What is size_t in C?

size_t and int are not interchangeable. For instance on 64-bit Linux size_t is 64-bit in size (i.e. sizeof(void*)) but int is 32-bit.

Also note that size_t is unsigned. If you need signed version then there is ssize_t on some platforms and it would be more relevant to your example.

As a general rule I would suggest using int for most general cases and only use size_t/ssize_t when there is a specific need for it (with mmap() for example).

How to build and run Maven projects after importing into Eclipse IDE

  1. Right Click on your project
  2. Go to Maven>Update Project
  3. Check the Force Update of Snapshots/Releases Checkbox
  4. Click Ok

That's all. You can see progression of build in left below corner.

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

jquery getting post action url

Clean and Simple:

$('#signup').submit(function(event) {

      alert(this.action);
});

Sorting an IList in C#

Is this a valid solution?

        IList<string> ilist = new List<string>();
        ilist.Add("B");
        ilist.Add("A");
        ilist.Add("C");

        Console.WriteLine("IList");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

        List<string> list = (List<string>)ilist;
        list.Sort();
        Console.WriteLine("List");
        foreach (string val in list)
            Console.WriteLine(val);
        Console.WriteLine();

        list = null;

        Console.WriteLine("IList again");
        foreach (string val in ilist)
            Console.WriteLine(val);
        Console.WriteLine();

The result was: IList B A C

List A B C

IList again A B C

Fastest way to add an Item to an Array

Case C) is the fastest. Having this as an extension:

Public Module MyExtensions
    <Extension()> _
    Public Sub Add(Of T)(ByRef arr As T(), item As T)
        Array.Resize(arr, arr.Length + 1)
        arr(arr.Length - 1) = item
    End Sub
End Module

Usage:

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr.Add(newItem)

' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec

Generating a random hex color code with PHP

Shortest way:

echo substr(uniqid(),-6); // result: 5ebf06

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

Using "like" wildcard in prepared statement

String fname = "Sam\u0025";

PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");

ps.setString(1, fname);

APK signing error : Failed to read key from keystore

For someone not using the signing configs and trying to test out the Cordova Release command by typing all the parameters at command line, you may need to enclose your passwords with single quotes if you have special characters in your password

cordova run android --release -- --keystore=../my-release-key.keystore --storePassword='password' --alias=alias_name --password='password'

Which .NET Dependency Injection frameworks are worth looking into?

edit (not by the author): There is a comprehensive list of IoC frameworks available at https://github.com/quozd/awesome-dotnet/blob/master/README.md#ioc:

  • Castle Windsor - Castle Windsor is best of breed, mature Inversion of Control container available for .NET and Silverlight
  • Unity - Lightweight extensible dependency injection container with support for constructor, property, and method call injection
  • Autofac - An addictive .NET IoC container
  • DryIoc - Simple, fast all fully featured IoC container.
  • Ninject - The ninja of .NET dependency injectors
  • StructureMap - The original IoC/DI Container for .Net
  • Spring.Net - Spring.NET is an open source application framework that makes building enterprise .NET applications easier
  • LightInject - A ultra lightweight IoC container
  • Simple Injector - Simple Injector is an easy-to-use Dependency Injection (DI) library for .NET 4+ that supports Silverlight 4+, Windows Phone 8, Windows 8 including Universal apps and Mono.
  • Microsoft.Extensions.DependencyInjection - The default IoC container for ASP.NET Core applications.
  • Scrutor - Assembly scanning extensions for Microsoft.Extensions.DependencyInjection.
  • VS MEF - Managed Extensibility Framework (MEF) implementation used by Visual Studio.
  • TinyIoC - An easy to use, hassle free, Inversion of Control Container for small projects, libraries and beginners alike.

Original answer follows.


I suppose I might be being a bit picky here but it's important to note that DI (Dependency Injection) is a programming pattern and is facilitated by, but does not require, an IoC (Inversion of Control) framework. IoC frameworks just make DI much easier and they provide a host of other benefits over and above DI.

That being said, I'm sure that's what you were asking. About IoC Frameworks; I used to use Spring.Net and CastleWindsor a lot, but the real pain in the behind was all that pesky XML config you had to write! They're pretty much all moving this way now, so I have been using StructureMap for the last year or so, and since it has moved to a fluent config using strongly typed generics and a registry, my pain barrier in using IoC has dropped to below zero! I get an absolute kick out of knowing now that my IoC config is checked at compile-time (for the most part) and I have had nothing but joy with StructureMap and its speed. I won't say that the others were slow at runtime, but they were more difficult for me to setup and frustration often won the day.

Update

I've been using Ninject on my latest project and it has been an absolute pleasure to use. Words fail me a bit here, but (as we say in the UK) this framework is 'the Dogs'. I would highly recommend it for any green fields projects where you want to be up and running quickly. I got all I needed from a fantastic set of Ninject screencasts by Justin Etheredge. I can't see that retro-fitting Ninject into existing code being a problem at all, but then the same could be said of StructureMap in my experience. It'll be a tough choice going forward between those two, but I'd rather have competition than stagnation and there's a decent amount of healthy competition out there.

Other IoC screencasts can also be found here on Dimecasts.

Pushing an existing Git repository to SVN

What if you don't want to commit every commit that you make in Git, to the SVN repository? What if you just want to selectively send commits up the pipe? Well, I have a better solution.

I keep one local Git repository where all I ever do is fetch and merge from SVN. That way I can make sure I'm including all the same changes as SVN, but I keep my commit history separate from the SVN entirely.

Then I keep a separate SVN local working copy that is in a separate folder. That's the one I make commits back to SVN from, and I simply use the SVN command line utility for that.

When I'm ready to commit my local Git repository's state to SVN, I simply copy the whole mess of files over into the local SVN working copy and commit it from there using SVN rather than Git.

This way I never have to do any rebasing, because rebasing is like freebasing.

How to copy file from one location to another location?

Using Stream

private static void copyFileUsingStream(File source, File dest) throws IOException {
    InputStream is = null;
    OutputStream os = null;
    try {
        is = new FileInputStream(source);
        os = new FileOutputStream(dest);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
    } finally {
        is.close();
        os.close();
    }
}

Using Channel

private static void copyFileUsingChannel(File source, File dest) throws IOException {
    FileChannel sourceChannel = null;
    FileChannel destChannel = null;
    try {
        sourceChannel = new FileInputStream(source).getChannel();
        destChannel = new FileOutputStream(dest).getChannel();
        destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
       }finally{
           sourceChannel.close();
           destChannel.close();
       }
}

Using Apache Commons IO lib:

private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
    FileUtils.copyFile(source, dest);
}

Using Java SE 7 Files class:

private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
    Files.copy(source.toPath(), dest.toPath());
}

Or try Googles Guava :

https://github.com/google/guava

docs: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html

Compare time:

    File source = new File("/Users/sidikov/tmp/source.avi");
    File dest = new File("/Users/sidikov/tmp/dest.avi");


    //copy file conventional way using Stream
    long start = System.nanoTime();
    copyFileUsingStream(source, dest);
    System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
     
    //copy files using java.nio FileChannel
    source = new File("/Users/sidikov/tmp/sourceChannel.avi");
    dest = new File("/Users/sidikov/tmp/destChannel.avi");
    start = System.nanoTime();
    copyFileUsingChannel(source, dest);
    System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
     
    //copy files using apache commons io
    source = new File("/Users/sidikov/tmp/sourceApache.avi");
    dest = new File("/Users/sidikov/tmp/destApache.avi");
    start = System.nanoTime();
    copyFileUsingApacheCommonsIO(source, dest);
    System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
     
    //using Java 7 Files class
    source = new File("/Users/sidikov/tmp/sourceJava7.avi");
    dest = new File("/Users/sidikov/tmp/destJava7.avi");
    start = System.nanoTime();
    copyFileUsingJava7Files(source, dest);
    System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));

Get the string within brackets in Python

You can also use

re.findall(r"\[([A-Za-z0-9_]+)\]", string)

if there are many occurrences that you would like to find.

See also for more info: How can I find all matches to a regular expression in Python?

Not able to access adb in OS X through Terminal, "command not found"

For Mac OS Catalina or Mojave

Enter command to open nano editor

nano $HOME/.zshrc

Set PATH variable, means append more path as shown here

FLUTTER_HOME="/Users/pankaj/Library/Android/flutter-sdk/flutter/bin"
DART_HOME="/Users/pankaj/Library/Android/flutter-sdk/flutter/bin/cache/dart-sdk/bin"
ANDROID_SDK_HOME="/Users/pankaj/Library/Android/sdk"
ANDROID_ADB_HOME="/Users/pankaj/Library/Android/sdk/platform-tools"

PATH="$PATH:$FLUTTER_HOME"
PATH="$PATH:$DART_HOME"
PATH="$PATH:$ANDROID_SDK_HOME"
PATH="$PATH:$ANDROID_ADB_HOME"

Now press Command + X to save file in editor,Enter Yes or No and hit Enter key.

Chart.js canvas resize

 let canvasBox = ReactDOM.findDOMNode(this.refs.canvasBox);
 let width = canvasBox.clientWidth;
 let height = canvasBox.clientHeight;
 let charts = ReactDOM.findDOMNode(this.refs.charts);
 let ctx = charts.getContext('2d');
 ctx.canvas.width = width;
 ctx.canvas.height = height;
 this.myChart = new Chart(ctx);

Scrolling a flexbox with overflowing content

One issue that I've come across is that to have a scrollbar a n element needs a height to be specified (and not as a %).

The trick is to nest another set of divs within each column, and set the column parent's display to flex with flex-direction: column.

<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0;
    }

    body {
        overflow-y: hidden;
        overflow-x: hidden;
        color: white;
    }

    .base-container {
        display: flex;
        flex: 1;
        flex-direction: column;
        width: 100%;
        height: 100%;
        overflow-y: hidden;
        align-items: stretch;
    }

    .title {
        flex: 0 0 50px;
        color: black;
    }

    .container {
        flex: 1 1 auto;
        display: flex;
        flex-direction: column;
    }

        .container .header {
            flex: 0 0 50px;
            background-color: red;
        }

        .container .body {
            flex: 1 1 auto;
            display: flex;
            flex-direction: row;
        }

            .container .body .left {
                display: flex;
                flex-direction: column;
                flex: 0 0 80px;
                background-color: blue;
            }
                .container .body .left .content,
                .container .body .main .content,
                .container .body .right .content {
                    flex: 1 1 auto;
                    overflow-y: auto;
                    height: 100px;
                }
                .container .body .main .content.noscrollbar {
                    overflow-y: hidden;
                }

            .container .body .main {
                display: flex;
                flex-direction: column;
                flex: 1 1 auto;
                background-color: green;
            }

            .container .body .right {
                display: flex;
                flex-direction: column;
                flex: 0 0 300px;
                background-color: yellow;
                color: black;
            }

    .test {
        margin: 5px 5px;
        border: 1px solid white;
        height: calc(100% - 10px);
    }
</style>

And here's the html:

<div class="base-container">
    <div class="title">
        Title
    </div>
    <div class="container">
        <div class="header">
            Header
        </div>
        <div class="body">
            <div class="left">
                <div class="content">
                    <ul>
                        <li>1</li>
                        <li>2</li>
                        <li>3</li>
                        <li>4</li>
                        <li>5</li>
                        <li>6</li>
                        <li>7</li>
                        <li>8</li>
                        <li>9</li>
                        <li>10</li>
                        <li>12</li>
                        <li>13</li>
                        <li>14</li>
                        <li>15</li>
                        <li>16</li>
                        <li>17</li>
                        <li>18</li>
                        <li>19</li>
                        <li>20</li>
                        <li>21</li>
                        <li>22</li>
                        <li>23</li>
                        <li>24</li>
                    </ul>
                </div>
            </div>
            <div class="main">
                <div class="content noscrollbar">
                    <div class="test">Test</div>
                </div>
            </div>
            <div class="right">
                <div class="content">
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>Right</div>
                    <div>End</div>
                </div>
            </div>
        </div>
    </div>
</div>

https://jsfiddle.net/LiamFlavelle/czpjdfr4/

Strangest language feature

In C++, the ability to create a protected abstract virtual base pure virtual private destructor.

This is a pure virtual private destructor that is inherited from a protected abstract virtual base.

IOW, a destructor that can only be called by members or friends of the class (private), and which is assigned a 0 (pure virtual) in the base class (abstract base) that declares it, and which will be defined later/overriden in a derived class that shares the multiple-inherited base (virtual base) in a protected way.

How to get old Value with onchange() event in text box

I would suggest:

function onChange(field){
  field.old=field.recent;
  field.recent=field.value;

  //we have available old value here;
}

Is there a way to automatically build the package.json file for Node.js projects

First off, run

npm init

...will ask you a few questions (read this first) about your project/package and then generate a package.json file for you.

Then, once you have a package.json file, use

npm install <pkg> --save

or

npm install <pkg> --save-dev

...to install a dependency and automatically append it to your package.json's dependencies list.

(Note: You may need to manually tweak the version ranges for your dependencies.)

CSS I want a div to be on top of everything

Yes, in order for the z-index to work, you'll need to give the element a position: absolute or a position: relative property.

But... pay attention to parents!

You have to go up the nodes of the elements to check if at the level of the common parent the first descendants have a defined z-index.

All other descendants can never be in the foreground if at the base there is a lower definite z-index.

In this snippet example, div1-2-1 has a z-index of 1000 but is nevertheless under the div1-1-1 which has a z-index of 3.

This is because div1-1 has a z-index greater than div1-2.

enter image description here

_x000D_
_x000D_
.div {
  
}

#div1 {
  z-index: 1;
  position: absolute;
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

#div1-1 {
  z-index: 2;
  position: absolute;
  left: 230px;
  width: 200px;
  height: 200px;
  top: 31px;
  background-color: indianred;
}

#div1-1-1 {
  z-index: 3;
  position: absolute;
  top: 50px;
  width: 100px;
  height: 100px;
  background-color: burlywood;
}

#div1-2 {
  z-index: 1;
  position: absolute;
  width: 200px;
  height: 200px;
  left: 80px;
  top: 5px;
  background-color: red;
}

#div1-2-1 {
  z-index: 1000;
  position: absolute;
  left: 70px;
  width: 120px;
  height: 100px;
  top: 10px;
  color: red;
  background-color: lightyellow;
}

.blink {
  animation: blinker 1s linear infinite;
}

@keyframes blinker {
  50% {
    opacity: 0;
  }
}

.rotate {
  writing-mode: vertical-rl;
  padding-left: 50px;
  font-weight: bold;
  font-size: 20px;
}
_x000D_
<div class="div" id="div1">div1</br>z-index: 1
  <div class="div" id="div1-1">div1-1</br>z-index: 2
    <div class="div" id="div1-1-1">div1-1-1</br>z-index: 3</div>
  </div>
  
  <div class="div" id="div1-2">div1-2</br>z-index: 1</br><span class='rotate blink'><=</span>
    <div class="div" id="div1-2-1"><span class='blink'>z-index: 1000!!</span></br>div1-2-1</br><span class='blink'> because =></br>(same</br>   parent)</span></div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

What are the performance characteristics of sqlite with very large database files?

I think the main complaints about sqlite scaling is:

  1. Single process write.
  2. No mirroring.
  3. No replication.

How to install a node.js module without using npm?

You can clone the module directly in to your local project.

Start terminal. cd in to your project and then:

npm install https://github.com/repo/npm_module.git --save

CSS rotate property in IE

Just a hint... think twice before using "transform: rotate()", or even "-ms-transform :rotate()" (IE9) with mobiles!

I've been knocking hard to the wall for days. I have a 'kinetic' system going on, that slides images and, on top of it, a command area. I did "transform" on an arrow button so it simulates pointing up and down... I've reviewd the 1.000 plus code lines for ages!!! ;-)

All ok, once I removed transform:rotate from the CSS. It's a bit (not to use bad words) tricky the way IE handles it, comparing to other borwsers.

Great answer @Spudley! Thanks for writing it!

How to get the request parameters in Symfony 2?

public function indexAction(Request $request)
{
   $data = $request->get('corresponding_arg');
   // this also works
   $data1 = $request->query->get('corresponding_arg1');
}

matplotlib savefig() plots different from show()

savefig specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the dpi kwarg to savefig). It doesn't inheret it from the DPI of the original figure.

The DPI affects the relative size of the text and width of the stroke on lines, etc. If you want things to look identical, then pass fig.dpi to fig.savefig.

E.g.

import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', dpi=fig.dpi)

How to stretch the background image to fill a div

Add

background-size:100% 100%;

to your css underneath background-image.

You can also specify exact dimensions, i.e.:

background-size: 30px 40px;

Here: JSFiddle

Printing the value of a variable in SQL Developer

Go to the DBMS Output window (View->DBMS Output).

Python - Passing a function into another function

For passing both a function, and any arguments to the function:

from typing import Callable    

def looper(fn: Callable, n:int, *args, **kwargs):
    """
    Call a function `n` times

    Parameters
    ----------
    fn: Callable
        Function to be called.
    n: int
        Number of times to call `func`.
    *args
        Positional arguments to be passed to `func`.
    **kwargs
        Keyword arguments to be passed to `func`.

    Example
    -------
    >>> def foo(a:Union[float, int], b:Union[float, int]):
    ...    '''The function to pass'''
    ...    print(a+b)
    >>> looper(foo, 3, 2, b=4)
    6
    6
    6       
    """
    for i in range(n):
        fn(*args, **kwargs)

Depending on what you are doing, it could make sense to define a decorator, or perhaps use functools.partial.

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

CREATE DATABASE permission denied in database 'master' (EF code-first)

Run Visual Studio as Administrator and put your SQL SERVER authentication login (who has the permission to create a DB) and password in the connection string, it worked for me

Developing C# on Linux

This is an old question but it has a high view count, so I think some new information should be added: In the mean time a lot has changed, and you can now also use Microsoft's own .NET Core on linux. It's also available in ARM builds, 32 and 64 bit.

Which regular expression operator means 'Don't' match this character?

You can use negated character classes to exclude certain characters: for example [^abcde] will match anything but a,b,c,d,e characters.

Instead of specifying all the characters literally, you can use shorthands inside character classes: [\w] (lowercase) will match any "word character" (letter, numbers and underscore), [\W] (uppercase) will match anything but word characters; similarly, [\d] will match the 0-9 digits while [\D] matches anything but the 0-9 digits, and so on.

If you use PHP you can take a look at the regex character classes documentation.

Concatenate multiple result rows of one column into one, group by another column

Simpler with the aggregate function string_agg() (Postgres 9.0 or later):

SELECT movie, string_agg(actor, ', ') AS actor_list
FROM   tbl
GROUP  BY 1;

The 1 in GROUP BY 1 is a positional reference and a shortcut for GROUP BY movie in this case.

string_agg() expects data type text as input. Other types need to be cast explicitly (actor::text) - unless an implicit cast to text is defined - which is the case for all other character types (varchar, character, "char"), and some other types.

As isapir commented, you can add an ORDER BY clause in the aggregate call to get a sorted list - should you need that. Like:

SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM   tbl
GROUP  BY 1;

But it's typically faster to sort rows in a subquery. See:

Very simple log4j2 XML configuration file using Console and File appender

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        </Console>
        <File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
            <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
        </File>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="Console" />
            <AppenderRef ref="MyFile"/>
        </Root>
    </Loggers>
</Configuration>

Notes:

  • Put the following content in your configuration file.
  • Name the configuration file log4j2.xml
  • Put the log4j2.xml in a folder which is in the class-path (i.e. your source folder "src")
  • Use Logger logger = LogManager.getLogger(); to initialize your logger
  • I did set the immediateFlush="false" since this is better for SSD lifetime. If you need the log right away in your log-file remove the parameter or set it to true

How to search in a List of Java object

Using Java 8

With Java 8 you can simply convert your list to a stream allowing you to write:

import java.util.List;
import java.util.stream.Collectors;

List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
    .filter(a -> Objects.equals(a.value3, "three"))
    .collect(Collectors.toList());

Note that

  • a -> Objects.equals(a.value3, "three") is a lambda expression
  • result is a List with a Sample type
  • It's very fast, no cast at every iteration
  • If your filter logic gets heavier, you can do list.parallelStream() instead of list.stream() (read this)


Apache Commons

If you can't use Java 8, you can use Apache Commons library and write:

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

Collection result = CollectionUtils.select(list, new Predicate() {
     public boolean evaluate(Object a) {
         return Objects.equals(((Sample) a).value3, "three");
     }
 });

// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);

Note that:

  • There is a cast from Object to Sample at each iteration
  • If you need your results to be typed as Sample[], you need extra code (as shown in my sample)



Bonus: A nice blog article talking about how to find element in list.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

SQl Management Studio data import looks at the first few rows to determine source data specs..

shift your records around so that the longest text is at top.

Deleting rows with MySQL LEFT JOIN

This script worked for me:

DELETE t
FROM table t
INNER JOIN join_table jt ON t.fk_column = jt.id
WHERE jt.comdition_column…;

How to mute an html5 video player using jQuery

If you don't want to jQuery, here's the vanilla JavaScript:

///Mute
var video = document.getElementById("your-video-id");
video.muted= true;

//Unmute
var video = document.getElementById("your-video-id");
video.muted= false;

It will work for audio too, just put the element's id and it will work (and change the var name if you want, to 'media' or something suited for both audio/video as you like).

Use of ~ (tilde) in R programming Language

The thing on the right of <- is a formula object. It is often used to denote a statistical model, where the thing on the left of the ~ is the response and the things on the right of the ~ are the explanatory variables. So in English you'd say something like "Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width".

The myFormula <- part of that line stores the formula in an object called myFormula so you can use it in other parts of your R code.


Other common uses of formula objects in R

The lattice package uses them to specify the variables to plot.
The ggplot2 package uses them to specify panels for plotting.
The dplyr package uses them for non-standard evaulation.

Get to UIViewController from UIView?

I would suggest a more lightweight approach for traversing the complete responder chain without having to add a category on UIView:

@implementation MyUIViewSubclass

- (UIViewController *)viewController {
    UIResponder *responder = self;
    while (![responder isKindOfClass:[UIViewController class]]) {
        responder = [responder nextResponder];
        if (nil == responder) {
            break;
        }
    }
    return (UIViewController *)responder;
}

@end

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

How to scale a BufferedImage

scale(..) works a bit differently. You can use bufferedImage.getScaledInstance(..)

Qt Creator color scheme

I found some trick for your problem! Here you can see it: Habrahabr -- Redesigning Qt Creator by your hands (russian lang.)

According to that article, that trick is kind of not so dirty, but "hack" (probably it wouldn't harm your system, but it can leave some artifacts on your interface).

You don't need to patch something (there is possibility, but I don't recommend).

Main idea is to use stylesheet like this stylesheet.css:

// on Linux
qtcreator -stylesheet='.qt-stylesheet.css' 
// on Windows
[pathToQt]\QtCreator\bin\qtcreator.exe -stylesheet [pathToStyleSheet]

To get such effect: QtCreator before and after

To customize by your needs, you may need to read documentation: Qt Style Sheets Reference, Qt Style Sheets Examples and so on.

This wiki page is dedicated to custom Qt Creator styling.

P.S. If you'll got better stylesheet, share it, I'll be happy! :)


UPD (10.12.2014): Hopefully, now we can close this topic. Thanks, Simon G., Things have changed once again. Users may use custom themes since QtCreator 3.3. So hacky stylesheets are no longer needed.

Everyone can take a look at todays update: Qt 5.4 released. There you can find information that Qt 5.4, also comes with a brand new version of Qt Creator 3.3. Just take a look at official video at Youtube.

So, to apply dark theme you need go to "Tools" -> "Options" -> "Environment" -> "General" tab, and there you need to change "Theme".

See more information about its configuring here: Configuring Qt Creator.

Java Garbage Collection Log messages

  1. PSYoungGen refers to the garbage collector in use for the minor collection. PS stands for Parallel Scavenge.
  2. The first set of numbers are the before/after sizes of the young generation and the second set are for the entire heap. (Diagnosing a Garbage Collection problem details the format)
  3. The name indicates the generation and collector in question, the second set are for the entire heap.

An example of an associated full GC also shows the collectors used for the old and permanent generations:

3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)] 
            [ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K) 
            [PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]

Finally, breaking down one line of your example log output:

8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]
  • 107Mb used before GC, 14Mb used after GC, max young generation size 137Mb
  • 675Mb heap used before GC, 581Mb heap used after GC, 1Gb max heap size
  • minor GC occurred 8109.128 seconds since the start of the JVM and took 0.04 seconds

ValueError: setting an array element with a sequence

When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.

import numpy as np

# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32)  # error
arr2 = np.array([[10, 20.], [30], [40]])  # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello'])     # OK, and the dtype is also object

``

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

Ignore duplicates when producing map using streams

I have encountered such a problem when grouping object, i always resolved them by a simple way: perform a custom filter using a java.util.Set to remove duplicate object with whatever attribute of your choice as bellow

Set<String> uniqueNames = new HashSet<>();
Map<String, String> phoneBook = people
                  .stream()
                  .filter(person -> person != null && !uniqueNames.add(person.getName()))
                  .collect(toMap(Person::getName, Person::getAddress));

Hope this helps anyone having the same problem !

Port 80 is being used by SYSTEM (PID 4), what is that?

In my case, it happened after installing Microsoft Web Matrix. Uninstalling this trash along with "Microsoft Web Deploy" fixed the issue.

Hide element by class in pure Javascript

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').fadeOut('slow');

        });
    </script>

or

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').hide();

        });
    </script>

Remove border from buttons

Add

padding: 0;
border: none;
background: none;

to your buttons.

Demo:

https://jsfiddle.net/Vestride/dkr9b/

Decoding JSON String in Java

This is the best and easiest code:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

Bootstrap: align input with button

Just the heads up, there seems to be special CSS class for this called form-horizontal

input-append has another side effect, that it drops font-size to zero

Automated testing for REST Api

Frisby is a REST API testing framework built on node.js and Jasmine that makes testing API endpoints easy, fast, and fun. http://frisbyjs.com

Example:

var frisby = require('../lib/frisby');

var URL = 'http://localhost:3000/';
var URL_AUTH = 'http://username:password@localhost:3000/';

frisby.globalSetup({ // globalSetup is for ALL requests
  request: {
    headers: { 'X-Auth-Token': 'fa8426a0-8eaf-4d22-8e13-7c1b16a9370c' }
  }
});

frisby.create('GET user johndoe')
  .get(URL + '/users/3.json')
  .expectStatus(200)
  .expectJSONTypes({
    id: Number,
    username: String,
    is_admin: Boolean
  })
  .expectJSON({
    id: 3,
    username: 'johndoe',
    is_admin: false
  })
  // 'afterJSON' automatically parses response body as JSON and passes it as an argument
  .afterJSON(function(user) {
    // You can use any normal jasmine-style assertions here
    expect(1+1).toEqual(2);

    // Use data from previous result in next test
    frisby.create('Update user')
      .put(URL_AUTH + '/users/' + user.id + '.json', {tags: ['jasmine', 'bdd']})
      .expectStatus(200)
    .toss();
  })
.toss();

Rounding numbers to 2 digits after comma

use the below code.

alert(+(Math.round(number + "e+2")  + "e-2"));

Parsing huge logfiles in Node.js - read in line-by-line

node-byline uses streams, so i would prefer that one for your huge files.

for your date-conversions i would use moment.js.

for maximising your throughput you could think about using a software-cluster. there are some nice-modules which wrap the node-native cluster-module quite well. i like cluster-master from isaacs. e.g. you could create a cluster of x workers which all compute a file.

for benchmarking splits vs regexes use benchmark.js. i havent tested it until now. benchmark.js is available as a node-module

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

PowerShell script to return versions of .NET Framework on a machine?

Here's the general idea:

Get child items in the .NET Framework directory that are containers whose names match the pattern v number dot number. Sort them by descending name, take the first object, and return its name property.

Here's the script:

(Get-ChildItem -Path $Env:windir\Microsoft.NET\Framework | Where-Object {$_.PSIsContainer -eq $true } | Where-Object {$_.Name -match 'v\d\.\d'} | Sort-Object -Property Name -Descending | Select-Object -First 1).Name

How can I have a newline in a string in sh?

Disclaimer: I first wrote this and then stumbled upon this question. I thought this solution wasn't yet posted, and saw that tlwhitec did post a similar answer. Still I'm posting this because I hope it's a useful and thorough explanation.

Short answer:

This seems quite a portable solution, as it works on quite some shells (see comment).
This way you can get a real newline into a variable.

The benefit of this solution is that you don't have to use newlines in your source code, so you can indent your code any way you want, and the solution still works. This makes it robust. It's also portable.

# Robust way to put a real newline in a variable (bash, dash, ksh, zsh; indentation-resistant).
nl="$(printf '\nq')"
nl=${nl%q}

Longer answer:

Explanation of the above solution:

The newline would normally lost due to command substitution, but to prevent that, we add a 'q' and remove it afterwards. (The reason for the double quotes is explained further below.)

We can prove that the variable contains an actual newline character (0x0A):

printf '%s' "$nl" | hexdump -C
00000000  0a  |.|
00000001

(Note that the '%s' was needed, otherwise printf will translate a literal '\n' string into an actual 0x0A character, meaning we would prove nothing.)

Of course, instead of the solution proposed in this answer, one could use this as well (but...):

nl='
'

... but that's less robust and can be easily damaged by accidentally indenting the code, or by forgetting to dedent it afterwards, which makes it inconvenient to use in (indented) functions, whereas the earlier solution is robust.

Now, as for the double quotes:
The reason for the double quotes " surrounding the command substitution as in nl="$(printf '\nq')" is that you can then even prefix the variable assignment with the local keyword or builtin (such as in functions), and it will still work on all shells, whereas otherwise the dash shell would have trouble, in the sense that dash would otherwise lose the 'q' and you'd end up with an empty 'nl' variable (again, due to command substitution).
That issue is better illustrated with another example:

dash_trouble_example() {
    e=$(echo hello world) # Not using 'local'.
    echo "$e" # Fine. Outputs 'hello world' in all shells.

    local e=$(echo hello world) # But now, when using 'local' without double quotes ...:
    echo "$e" # ... oops, outputs just 'hello' in dash,
              # ... but 'hello world' in bash and zsh.

    local f="$(echo hello world)" # Finally, using 'local' and surrounding with double quotes.
    echo "$f" # Solved. Outputs 'hello world' in dash, zsh, and bash.

    # So back to our newline example, if we want to use 'local', we need
    # double quotes to surround the command substitution:
    # (If we didn't use double quotes here, then in dash the 'nl' variable
    # would be empty.)
    local nl="$(printf '\nq')"
    nl=${nl%q}
}

Practical example of the above solution:

# Parsing lines in a for loop by setting IFS to a real newline character:

nl="$(printf '\nq')"
nl=${nl%q}

IFS=$nl

for i in $(printf '%b' 'this is line 1\nthis is line 2'); do
    echo "i=$i"
done

# Desired output:
# i=this is line 1
# i=this is line 2

# Exercise:
# Try running this example without the IFS=$nl assignment, and predict the outcome.

Put content in HttpResponseMessage object?

Inspired by Simon Mattes' answer, I needed to satisfy IHttpActionResult required return type of ResponseMessageResult. Also using nashawn's JsonContent, I ended up with...

        return new System.Web.Http.Results.ResponseMessageResult(
            new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.OK)
            {
                Content = new JsonContent(JsonConvert.SerializeObject(contact, Formatting.Indented))
            });

See nashawn's answer for JsonContent.

How can I symlink a file in Linux?

This is Stack Overflow so I assume you want code:

All following code assumes that you want to create a symbolic link named /tmp/link that links to /tmp/realfile.

CAUTION: Although this code checks for errors, it does NOT check if /tmp/realfile actually exists ! This is because a dead link is still valid and depending on your code you might (rarely) want to create the link before the real file.


Shell (bash, zsh, ...)

#!/bin/sh
ln -s /tmp/realfile /tmp/link

Real simple, just like you would do it on the command line (which is the shell). All error handling is done by the shell interpreter. This code assumes that you have a working shell interpreter at /bin/sh .

If needed you could still implement your own error handling by using the $? variable which will only be set to 0 if the link was successfully created.

C and C++

#include <unistd.h>
#include <stdio.h>

int main () {
  if( symlink("/tmp/realfile", "/tmp/link") != 0 )
    perror("Can't create the symlink");
}

symlink only returns 0 when the link can be created. In other cases I'm using perror to tell more about the problem.

Perl

#!/usr/bin/perl
if( symlink("/tmp/realfile", "/tmp/link") != 1) {
  print STDERR "Can't create the symlink: $!\n"
}

This code assumes you have a perl 5 interpreter at /usr/bin/perl. symlink only returns 1 if the link can be created. In other cases I'm printing the failure reason to the standard error output.

How to correctly iterate through getElementsByClassName

I followed Alohci's recommendation of looping in reverse because it's a live nodeList. Here's what I did for those who are curious...

  var activeObjects = documents.getElementsByClassName('active'); // a live nodeList

  //Use a reverse-loop because the array is an active NodeList
  while(activeObjects.length > 0) {
    var lastElem = activePaths[activePaths.length-1]; //select the last element

    //Remove the 'active' class from the element.  
    //This will automatically update the nodeList's length too.
    var className = lastElem.getAttribute('class').replace('active','');
    lastElem.setAttribute('class', className);
  }

Cannot read property 'map' of undefined

The error "Cannot read property 'map' of undefined" will be encountered if there is an error in the "this.props.data" or there is no props.data array.

Better put condition to check the the array like

if(this.props.data){
this.props.data.map(........)
.....
}

T-SQL to list all the user mappings with database roles/permissions for a Login

Is this the kind of thing you want? You might want to extend it to get more info out of the sys tables.

use master

DECLARE @name VARCHAR(50) -- database name 

DECLARE db_cursor CURSOR FOR 
select name from sys.databases

OPEN db_cursor  
FETCH NEXT FROM db_cursor INTO @name  

WHILE @@FETCH_STATUS = 0  
BEGIN  
       print @name
      exec('USE ' +  @name + '; select rp.name, mp.name from sys.database_role_members drm
            join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
            join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)')
       FETCH NEXT FROM db_cursor INTO @name  
END  

CLOSE db_cursor  
DEALLOCATE db_cursor

How to strip HTML tags with jQuery?

The safest way is to rely on the browser TextNode to correctly escape content. Here's an example:

_x000D_
_x000D_
function stripHTML(dirtyString) {_x000D_
  var container = document.createElement('div');_x000D_
  var text = document.createTextNode(dirtyString);_x000D_
  container.appendChild(text);_x000D_
  return container.innerHTML; // innerHTML will be a xss safe string_x000D_
}_x000D_
_x000D_
document.write( stripHTML('<p>some <span>content</span></p>') );_x000D_
document.write( stripHTML('<script><p>some <span>content</span></p>') );
_x000D_
_x000D_
_x000D_

The thing to remember here is that the browser escape the special characters of TextNodes when we access the html strings (innerHTML, outerHTML). By comparison, accessing text values (innerText, textContent) will yield raw strings, meaning they're unsafe and could contains XSS.

If you use jQuery, then using .text() is safe and backward compatible. See the other answers to this question.

The simplest way in pure JavaScript if you work with browsers <= Internet Explorer 8 is:

string.replace(/(<([^>]+)>)/ig,"");

But there's some issue with parsing HTML with regex so this won't provide very good security. Also, this only takes care of HTML characters, so it is not totally xss-safe.

C++ - struct vs. class

POD classes are Plain-Old data classes that have only data members and nothing else. There are a few questions on stackoverflow about the same. Find one here.

Also, you can have functions as members of structs in C++ but not in C. You need to have pointers to functions as members in structs in C.

Maximum number of rows of CSV data in excel sheet

Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link

MySQL COUNT DISTINCT

 Select
     Count(Distinct user_id) As countUsers
   , Count(site_id) As countVisits
   , site_id As site
 From cp_visits
 Where ts >= DATE_SUB(NOW(), INTERVAL 1 DAY)
 Group By site_id

How to Convert date into MM/DD/YY format in C#

 DateTime.Today.ToString("MM/dd/yy")

Look at the docs for custom date and time format strings for more info.

(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)

Running JAR file on Windows

If you need to distribute your .jar file and make it runnable at other people's Windows computers, you can make a simple .bat file like this in the command prompt:

java -jar MyJavaTool.jar

and place the .bat file in the same directory as your .jar file.

Should I write script in the body or the head of the html?

I always put my scripts in the header. My reasons:

  1. I like to separate code and (static) text
  2. I usually load my script from external sources
  3. The same script is used from several pages, so it feels like an include file (which also goes in the header)

Reading Space separated input in python

Assuming you are on Python 3, you can use this syntax

inputs = list(map(str,input().split()))

if you want to access individual element you can do it like that

m, n = map(str,input().split())

Static way to get 'Context' in Android?

I think you need a body for the getAppContext() method:

public static Context getAppContext()
   return MyApplication.context; 

Integer value in TextView

TextView tv = new TextView(this);
tv.setText(String.valueOf(number));

or

tv.setText(""+number);

Comparing boxed Long values 127 and 128

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

The problem is that the Java Developers wanted people to use Long like they used long to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long-values will be changed to Long-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.

So to be safe and to have predictable results always use .equals() to compare objects and do not rely on autoboxing in this case:

Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

The best thing you can do is leave out the action attribute altogether. If you leave it out, the form will be submitted to the document's address, i.e. the same page.

It is also possible to leave it empty, and any browser implementing HTML's form submission algorithm will treat it as equivalent to the document's address, which it does mainly because that's how browsers currently work:

8. Let action be the submitter element's action.

9. If action is the empty string, let action be the document's address.

Note: This step is a willful violation of RFC 3986, which would require base URL processing here. This violation is motivated by a desire for compatibility with legacy content. [RFC3986]

This definitely works in all current browsers, but may not work as expected in some older browsers ("browsers do weird things with an empty action="" attribute"), which is why the spec strongly discourages authors from leaving it empty:

The action and formaction content attributes, if specified, must have a value that is a valid non-empty URL potentially surrounded by spaces.

Put buttons at bottom of screen with LinearLayout?

<LinearLayout
 android:id="@+id/LinearLayouts02"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical"
 android:gravity="bottom|end">

<TextView
android:id="@+id/texts1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:layout_weight="2"
android:text="@string/forgotpass"
android:padding="7dp"
android:gravity="bottom|center_horizontal"
android:paddingLeft="10dp"
android:layout_marginBottom="30dp"
android:bottomLeftRadius="10dp"
android:bottomRightRadius="50dp"
android:fontFamily="sans-serif-condensed"
android:textColor="@color/colorAccent"
android:textStyle="bold"
android:textSize="16sp"
android:topLeftRadius="10dp"
android:topRightRadius="10dp"/>

</LinearLayout>

How to emulate a do-while loop in Python?

The built-in iter function does specifically that:

for x in iter(YOUR_FN, TERM_VAL):
    ...

E.g. (tested in Py2 and 3):

class Easy:
  X = 0
  @classmethod
  def com(cls):
    cls.X += 1
    return cls.X

for x in iter(Easy.com, 10):
  print(">>>", x)

If you want to give a condition to terminate instead of a value, you always can set an equality, and require that equality to be True.

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

Jquery to open Bootstrap v3 modal of remote url

If using @worldofjr answer in jQuery you are getting error:

e.relatedTarget.data is not a function

you should use:

$('#myModal').on('show.bs.modal', function (e) {
    var loadurl = $(e.relatedTarget).data('load-url');
    $(this).find('.modal-body').load(loadurl);
});

Not that e.relatedTarget if wrapped by $(..)

I was getting the error in latest Bootstrap 3 and after using this method it's working without any problem.

TestNG ERROR Cannot find class in classpath

To avoid the error

Cannot find class in classpath: (name of testcase file)

you need to hold Runner class and Test class in one place. I mean src and test folders.

OS X Terminal Colors

When I worked on Mac OS X in the lab I was able to get the terminal colors from using Terminal (rather than X11) and then editing the profile (from the Mac menu bar). The interface is a bit odd on the colors, but you have to set the modified theme as default.

Further settings worked by editing .bashrc.

How do I kill the process currently using a port on localhost in Windows?

For use in command line:

for /f "tokens=5" %a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %a

For use in bat-file:

for /f "tokens=5" %%a in ('netstat -aon ^| find ":8080" ^| find "LISTENING"') do taskkill /f /pid %%a

Refresh certain row of UITableView based on Int in Swift

let indexPathRow:Int = 0
let indexPosition = IndexPath(row: indexPathRow, section: 0)
tableView.reloadRows(at: [indexPosition], with: .none)

Can you disable tabs in Bootstrap?

Most easy and clean solution to avoid this is adding onclick="return false;" to a tag.

<ul class="nav nav-tabs">
    <li class="active">
        <a href="#home" onclick="return false;">Home</a>
    </li>    
    <li>
        <a href="#ApprovalDetails" onclick="return false;">Approval Details</a>
    </li>
</ul>
  • Adding "cursor:no-drop;" just makes cursor look disabled, but is clickable, Url gets appending with href target for ex page.apsx#Home
  • No need of adding "disabled" class to <li> AND removing href

How to set Java SDK path in AndroidStudio?

Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear. enter image description here

How to use the 'og' (Open Graph) meta tag for Facebook share

Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

The way we do that is with og:meta tags.

The tags look something like this -

  <meta property="og:title" content="Stuffed Cookies" />
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
  <meta property="og:description" content="The Turducken of Cookies" />
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">

You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

Get selected value of a dropdown's item using jQuery

Try this:

 $('#dropDownId option').filter(':selected').text();     

 $('#dropDownId option').filter(':selected').val();

Execute a command line binary with Node.js

I just wrote a Cli helper to deal with Unix/windows easily.

Javascript:

define(["require", "exports"], function (require, exports) {
    /**
     * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
     * Requires underscore or lodash as global through "_".
     */
    var Cli = (function () {
        function Cli() {}
            /**
             * Execute a CLI command.
             * Manage Windows and Unix environment and try to execute the command on both env if fails.
             * Order: Windows -> Unix.
             *
             * @param command                   Command to execute. ('grunt')
             * @param args                      Args of the command. ('watch')
             * @param callback                  Success.
             * @param callbackErrorWindows      Failure on Windows env.
             * @param callbackErrorUnix         Failure on Unix env.
             */
        Cli.execute = function (command, args, callback, callbackErrorWindows, callbackErrorUnix) {
            if (typeof args === "undefined") {
                args = [];
            }
            Cli.windows(command, args, callback, function () {
                callbackErrorWindows();

                try {
                    Cli.unix(command, args, callback, callbackErrorUnix);
                } catch (e) {
                    console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
                }
            });
        };

        /**
         * Execute a command on Windows environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.windows = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(process.env.comspec, _.union(['/c', command], args));
                callback(command, args, 'Windows');
            } catch (e) {
                callbackError(command, args, 'Windows');
            }
        };

        /**
         * Execute a command on Unix environment.
         *
         * @param command       Command to execute. ('grunt')
         * @param args          Args of the command. ('watch')
         * @param callback      Success callback.
         * @param callbackError Failure callback.
         */
        Cli.unix = function (command, args, callback, callbackError) {
            if (typeof args === "undefined") {
                args = [];
            }
            try {
                Cli._execute(command, args);
                callback(command, args, 'Unix');
            } catch (e) {
                callbackError(command, args, 'Unix');
            }
        };

        /**
         * Execute a command no matters what's the environment.
         *
         * @param command   Command to execute. ('grunt')
         * @param args      Args of the command. ('watch')
         * @private
         */
        Cli._execute = function (command, args) {
            var spawn = require('child_process').spawn;
            var childProcess = spawn(command, args);

            childProcess.stdout.on("data", function (data) {
                console.log(data.toString());
            });

            childProcess.stderr.on("data", function (data) {
                console.error(data.toString());
            });
        };
        return Cli;
    })();
    exports.Cli = Cli;
});

Typescript original source file:

 /**
 * Helper to use the Command Line Interface (CLI) easily with both Windows and Unix environments.
 * Requires underscore or lodash as global through "_".
 */
export class Cli {

    /**
     * Execute a CLI command.
     * Manage Windows and Unix environment and try to execute the command on both env if fails.
     * Order: Windows -> Unix.
     *
     * @param command                   Command to execute. ('grunt')
     * @param args                      Args of the command. ('watch')
     * @param callback                  Success.
     * @param callbackErrorWindows      Failure on Windows env.
     * @param callbackErrorUnix         Failure on Unix env.
     */
    public static execute(command: string, args: string[] = [], callback ? : any, callbackErrorWindows ? : any, callbackErrorUnix ? : any) {
        Cli.windows(command, args, callback, function () {
            callbackErrorWindows();

            try {
                Cli.unix(command, args, callback, callbackErrorUnix);
            } catch (e) {
                console.log('------------- Failed to perform the command: "' + command + '" on all environments. -------------');
            }
        });
    }

    /**
     * Execute a command on Windows environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static windows(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(process.env.comspec, _.union(['/c', command], args));
            callback(command, args, 'Windows');
        } catch (e) {
            callbackError(command, args, 'Windows');
        }
    }

    /**
     * Execute a command on Unix environment.
     *
     * @param command       Command to execute. ('grunt')
     * @param args          Args of the command. ('watch')
     * @param callback      Success callback.
     * @param callbackError Failure callback.
     */
    public static unix(command: string, args: string[] = [], callback ? : any, callbackError ? : any) {
        try {
            Cli._execute(command, args);
            callback(command, args, 'Unix');
        } catch (e) {
            callbackError(command, args, 'Unix');
        }
    }

    /**
     * Execute a command no matters what's the environment.
     *
     * @param command   Command to execute. ('grunt')
     * @param args      Args of the command. ('watch')
     * @private
     */
    private static _execute(command, args) {
        var spawn = require('child_process').spawn;
        var childProcess = spawn(command, args);

        childProcess.stdout.on("data", function (data) {
            console.log(data.toString());
        });

        childProcess.stderr.on("data", function (data) {
            console.error(data.toString());
        });
    }
}

Example of use:

    Cli.execute(Grunt._command, args, function (command, args, env) {
        console.log('Grunt has been automatically executed. (' + env + ')');

    }, function (command, args, env) {
        console.error('------------- Windows "' + command + '" command failed, trying Unix... ---------------');

    }, function (command, args, env) {
        console.error('------------- Unix "' + command + '" command failed too. ---------------');
    });

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

You need to update MVC.

  1. Go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution
  2. Click on "Updates"
  3. Update "Microsoft ASP.NET MVC"
  4. Rebuild Solution

Java: Check the date format of current string is according to required format or not

Here's a simple method:

public static boolean checkDatePattern(String padrao, String data) {
    try {
        SimpleDateFormat format = new SimpleDateFormat(padrao, LocaleUtils.DEFAULT_LOCALE);
        format.parse(data);
        return true;
    } catch (ParseException e) {
        return false;
    }
}

Delete all records in a table of MYSQL in phpMyAdmin

  • Visit phpmyadmin
  • Select your database and click on structure
  • In front of your table, you can see Empty, click on it to clear all the entries from the selected table.

demo-database-structure

Or you can do the same using sql query:

Click on SQL present along side Structure

TRUNCATE tablename; //offers better performance, but used only when all entries need to be cleared
or
DELETE FROM tablename; //returns the number of rows deleted

Refer to DELETE and TRUNCATE for detailed documentaion

Getting Python error "from: can't read /var/mail/Bio"

for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

'int' object has no attribute '__getitem__'

The error:

'int' object has no attribute '__getitem__'

means that you're attempting to apply the index operator [] on an int, not a list. So is col not a list, even when it should be? Let's start from that.

Look here:

col = [[0 for col in range(5)] for row in range(6)]

Use a different variable name inside, looks like the list comprehension overwrites the col variable during iteration. (Not during the iteration when you set col, but during the following ones.)

How do I decode a string with escaped unicode?

I don't have enough rep to put this under comments to the existing answers:

unescape is only deprecated for working with URIs (or any encoded utf-8) which is probably the case for most people's needs. encodeURIComponent converts a js string to escaped UTF-8 and decodeURIComponent only works on escaped UTF-8 bytes. It throws an error for something like decodeURIComponent('%a9'); // error because extended ascii isn't valid utf-8 (even though that's still a unicode value), whereas unescape('%a9'); // © So you need to know your data when using decodeURIComponent.

decodeURIComponent won't work on "%C2" or any lone byte over 0x7f because in utf-8 that indicates part of a surrogate. However decodeURIComponent("%C2%A9") //gives you © Unescape wouldn't work properly on that // © AND it wouldn't throw an error, so unescape can lead to buggy code if you don't know your data.

How to resolve git's "not something we can merge" error

git rebase the-branch-to-be-merged

I solved the problem using this git command, but rebase is only suited for some cases.

How to get the PYTHONPATH in shell?

Just write:

just write which python in your terminal and you will see the python path you are using.

Find control by name from Windows Forms controls

You can use:

f.Controls[name];

Where f is your form variable. That gives you the control with name name.

JS - window.history - Delete a state

You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).

One option I've been looking into is to handle the history yourself in JavaScript and use the window.history object as a carrier of sorts.

Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.

var myHistory = [];

function pageLoad() {
    window.history.pushState(myHistory, "<name>", "<url>");

    //Load page data.
}

Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState to keep the browser out of the loop.

function nav_to_details() {
    myHistory.push("page_im_on_now");
    window.history.replaceState(myHistory, "<name>", "<url>");

    //Load page data.
}

When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.

function on_popState() {
    // Note that some browsers fire popState on initial load,
    // so you should check your state object and handle things accordingly.
    // (I did not do that in these examples!)

    if (myHistory.length > 0) {
        var pg = myHistory.pop();
        window.history.pushState(myHistory, "<name>", "<url>");

        //Load page data for "pg".
    } else {
        //No "history" - let them exit or keep them in the app.
    }
}

The user will never be able to navigate forward using their browser buttons because they are always on the newest page.

From the browser's perspective, every time they go "back", they've immediately pushed forward again.

From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).

From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).

If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...

var myHistory = [];

function pageLoad() {
    // When the user first hits your page...
    // Check the state to see what's going on.

    if (window.history.state === null) {
        // If the state is null, this is a NEW navigation,
        //    the user has navigated to your page directly (not using back/forward).

        // First we establish a "back" page to catch backward navigation.
        window.history.replaceState(
            { isBackPage: true },
            "<back>",
            "<back>"
        );

        // Then push an "app" page on top of that - this is where the user will sit.
        // (As browsers vary, it might be safer to put this in a short setTimeout).
        window.history.pushState(
            { isBackPage: false },
            "<name>",
            "<url>"
        );

        // We also need to start our history tracking.
        myHistory.push("<whatever>");

        return;
    }

    // If the state is NOT null, then the user is returning to our app via history navigation.

    // (Load up the page based on the last entry of myHistory here)

    if (window.history.state.isBackPage) {
        // If the user came into our app via the back page,
        //     you can either push them forward one more step or just use pushState as above.

        window.history.go(1);
        // or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
    }

    setTimeout(function() {
        // Add our popstate event listener - doing it here should remove
        //     the issue of dealing with the browser firing it on initial page load.
        window.addEventListener("popstate", on_popstate);
    }, 100);
}

function on_popstate(e) {
    if (e.state === null) {
        // If there's no state at all, then the user must have navigated to a new hash.

        // <Look at what they've done, maybe by reading the hash from the URL>
        // <Change/load the new page and push it onto the myHistory stack>
        // <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>

        // Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
        window.history.go(-1);

        // Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
        // This would also prevent them from using the "forward" button to return to the new hash.
        window.history.replaceState(
            { isBackPage: false },
            "<new name>",
            "<new url>"
        );
    } else {
        if (e.state.isBackPage) {
            // If there is state and it's the 'back' page...

            if (myHistory.length > 0) {
                // Pull/load the page from our custom history...
                var pg = myHistory.pop();
                // <load/render/whatever>

                // And push them to our "app" page again
                window.history.pushState(
                    { isBackPage: false },
                    "<name>",
                    "<url>"
                );
            } else {
                // No more history - let them exit or keep them in the app.
            }
        }

        // Implied 'else' here - if there is state and it's NOT the 'back' page
        //     then we can ignore it since we're already on the page we want.
        //     (This is the case when we push the user back with window.history.go(-1) above)
    }
}

How to set shadows in React Native for android?

I added borderBottomWidth: 0 and it worked fine for me in android.

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

Sure. Here's a completely silly program that demonstrates calling main recursively.

public class main
{
    public static void main(String[] args)
    {
        for (int i = 0; i < args.length; ++i)
        {
            if (args[i] != "")
            {
                args[i] = "";
                System.out.println((args.length - i) + " left");
                main(args);
            }
        }

    }
}

Can I set up HTML/Email Templates with ASP.NET?

If you want to pass parameters like user names, product names, ... etc. you can use open source template engine NVelocity to produce your final email / HTML's.

An example of NVelocity template (MailTemplate.vm) :

A sample email template by <b>$name</b>.
<br />

Foreach example :
<br />    
#foreach ($item in $itemList)

[Date: $item.Date] Name: $item.Name, Value: $itemValue.Value
<br /><br />

#end

Generating mail body by MailTemplate.vm in your application :

VelocityContext context = new VelocityContext();
context.Put("name", "ScarletGarden");
context.Put("itemList", itemList);

StringWriter writer = new StringWriter();

Velocity.MergeTemplate("MailTemplate.vm", context, writer);

string mailBody = writer.GetStringBuilder().ToString();

The result mail body is :

A sample email template by ScarletGarden.

Foreach example :

[Date: 12.02.2009] Name: Item 1, Value: 09

[Date: 21.02.2009] Name: Item 4, Value: 52

[Date: 01.03.2009] Name: Item 2, Value: 21

[Date: 23.03.2009] Name: Item 6, Value: 24

For editing the templates, maybe you can use FCKEditor and save your templates to files.

Simple VBA selection: Selecting 5 cells to the right of the active cell

This example selects a new Range of Cells defined by the current cell to a cell 5 to the right.

Note that .Offset takes arguments of Offset(row, columns) and can be quite useful.


Sub testForStackOverflow()
    Range(ActiveCell, ActiveCell.Offset(0, 5)).Copy
End Sub

How to make html <select> element look like "disabled", but pass values?

if you don't want add the attr disabled can do it programmatically

can disable the edition into the <select class="yourClass"> element with this code:

//bloqueo selects
  //block all selects
  jQuery(document).on("focusin", 'select.yourClass', function (event) {
    var $selectDiabled = jQuery(this).attr('disabled', 'disabled');
    setTimeout(function(){ $selectDiabled.removeAttr("disabled"); }, 30);
  });

if you want try it can see it here: https://jsfiddle.net/9kjqjLyq/

@HostBinding and @HostListener: what do they do and what are they for?

Here is a basic hover example.

Component's template property:

Template

<!-- attention, we have the c_highlight class -->
<!-- c_highlight is the selector property value of the directive -->

<p class="c_highlight">
    Some text.
</p>

And our directive

import {Component,HostListener,Directive,HostBinding} from '@angular/core';

@Directive({
    // this directive will work only if the DOM el has the c_highlight class
    selector: '.c_highlight'
 })
export class HostDirective {

  // we could pass lots of thing to the HostBinding function. 
  // like class.valid or attr.required etc.

  @HostBinding('style.backgroundColor') c_colorrr = "red"; 

  @HostListener('mouseenter') c_onEnterrr() {
   this.c_colorrr= "blue" ;
  }

  @HostListener('mouseleave') c_onLeaveee() {
   this.c_colorrr = "yellow" ;
  } 
}

How to redirect to logon page when session State time out is completed in asp.net mvc

There is a generic solution:

Lets say you have a controller named Admin where you put content for authorized users.

Then, you can override the Initialize or OnAuthorization methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:

protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
    {
        //lets say you set session value to a positive integer
        AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
        if (AdminLoginType == 0)
        {
            filterContext.HttpContext.Response.Redirect("~/login");
        }

        base.OnAuthorization(filterContext);
    }

How to switch databases in psql?

Use below statement to switch to different databases residing inside your postgreSQL RDMS

\c databaseName

Capturing image from webcam in java?

Java usually doesn't like accessing hardware, so you will need a driver program of some sort, as goldenmean said. I've done this on my laptop by finding a command line program that snaps a picture. Then it's the same as goldenmean explained; you run the command line program from your java program in the takepicture() routine, and the rest of your code runs the same.

Except for the part about reading pixel values into an array, you might be better served by saving the file to BMP, which is nearly that format already, then using the standard java image libraries on it.

Using a command line program adds a dependency to your program and makes it less portable, but so was the webcam, right?

Excel add one hour

In cell A1, enter the time.
In cell B2, enter =A1+1/24

PHP: trying to create a new line with "\n"

It will be written on a new line if you examine the source code of the page. If you want it to appear on a new line when it is rendered in the browser, you'll have use a <br /> tag instead.

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

How to include Javascript file in Asp.Net page

Probably the file is not in the path specified. '../../../' will move 3 step up to the directory in which the page is located and look for the js file in a folder named JS.

Also the language attribute is Deprecated.

See Scripts:

18.2.1 The SCRIPT element

language = cdata [CI]

Deprecated. This attribute specifies the scripting language of the contents of this element. Its value is an identifier for the language, but since these identifiers are not standard, this attribute has been deprecated in favor of type.

Edit

Try changing

<script src="../../../JS/Registration.js" language="javascript" type="text/javascript" /> 

to

<script src="../../../JS/Registration.js" language="javascript" type="text/javascript"></script>

Laravel: Using try...catch with DB::transaction()

In the case you need to manually 'exit' a transaction through code (be it through an exception or simply checking an error state) you shouldn't use DB::transaction() but instead wrap your code in DB::beginTransaction and DB::commit/DB::rollback():

DB::beginTransaction();

try {
    DB::insert(...);
    DB::insert(...);
    DB::insert(...);

    DB::commit();
    // all good
} catch (\Exception $e) {
    DB::rollback();
    // something went wrong
}

See the transaction docs.

How to handle AssertionError in Python and find out which line or statement it occurred on?

Use the traceback module:

import sys
import traceback

try:
    assert True
    assert 7 == 7
    assert 1 == 2
    # many more statements like this
except AssertionError:
    _, _, tb = sys.exc_info()
    traceback.print_tb(tb) # Fixed format
    tb_info = traceback.extract_tb(tb)
    filename, line, func, text = tb_info[-1]

    print('An error occurred on line {} in statement {}'.format(line, text))
    exit(1)

When should iteritems() be used instead of items()?

Just as @Wessie noted, dict.iteritems, dict.iterkeys and dict.itervalues (which return an iterator in Python2.x) as well as dict.viewitems, dict.viewkeys and dict.viewvalues (which return view objects in Python2.x) were all removed in Python3.x

And dict.items, dict.keys and dict.values used to return a copy of the dictionary's list in Python2.x now return view objects in Python3.x, but they are still not the same as iterator.

If you want to return an iterator in Python3.x, use iter(dictview) :

$ python3.3

>>> d = {'one':'1', 'two':'2'}
>>> type(d.items())
<class 'dict_items'>
>>>
>>> type(d.keys())
<class 'dict_keys'>
>>>
>>>
>>> ii = iter(d.items())
>>> type(ii)
<class 'dict_itemiterator'>
>>>
>>> ik = iter(d.keys())
>>> type(ik)
<class 'dict_keyiterator'>

How can I search for a commit message on GitHub?

From the help page on searching code, it seems that this isn't yet possible.

You can search for text in your repository, including the ability to choose files or paths to search in, but you can't specify that you want to search in commits.

Maybe suggest this to them?

async at console app in C#?

My solution. The JSONServer is a class I wrote for running an HttpListener server in a console window.

class Program
{
    public static JSONServer srv = null;

    static void Main(string[] args)
    {
        Console.WriteLine("NLPS Core Server");

        srv = new JSONServer(100);
        srv.Start();

        InputLoopProcessor();

        while(srv.IsRunning)
        {
            Thread.Sleep(250);
        }

    }

    private static async Task InputLoopProcessor()
    {
        string line = "";

        Console.WriteLine("Core NLPS Server: Started on port 8080. " + DateTime.Now);

        while(line != "quit")
        {
            Console.Write(": ");
            line = Console.ReadLine().ToLower();
            Console.WriteLine(line);

            if(line == "?" || line == "help")
            {
                Console.WriteLine("Core NLPS Server Help");
                Console.WriteLine("    ? or help: Show this help.");
                Console.WriteLine("    quit: Stop the server.");
            }
        }
        srv.Stop();
        Console.WriteLine("Core Processor done at " + DateTime.Now);

    }
}

What is the C# version of VB.net's InputDialog?

You mean InputBox? Just look in the Microsoft.VisualBasic namespace.

C# and VB.Net share a common library. If one language can use it, so can the other.