Programs & Examples On #Live mesh

What are Keycloak's OAuth2 / OpenID Connect endpoints?

Following link Provides JSON document describing metadata about the Keycloak

/auth/realms/{realm-name}/.well-known/openid-configuration

Following information reported with Keycloak 6.0.1 for master realm

{  
   "issuer":"http://localhost:8080/auth/realms/master",
   "authorization_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/auth",
   "token_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token",
   "token_introspection_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token/introspect",
   "userinfo_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/userinfo",
   "end_session_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/logout",
   "jwks_uri":"http://localhost:8080/auth/realms/master/protocol/openid-connect/certs",
   "check_session_iframe":"http://localhost:8080/auth/realms/master/protocol/openid-connect/login-status-iframe.html",
   "grant_types_supported":[  
      "authorization_code",
      "implicit",
      "refresh_token",
      "password",
      "client_credentials"
   ],
   "response_types_supported":[  
      "code",
      "none",
      "id_token",
      "token",
      "id_token token",
      "code id_token",
      "code token",
      "code id_token token"
   ],
   "subject_types_supported":[  
      "public",
      "pairwise"
   ],
   "id_token_signing_alg_values_supported":[  
      "PS384",
      "ES384",
      "RS384",
      "HS256",
      "HS512",
      "ES256",
      "RS256",
      "HS384",
      "ES512",
      "PS256",
      "PS512",
      "RS512"
   ],
   "userinfo_signing_alg_values_supported":[  
      "PS384",
      "ES384",
      "RS384",
      "HS256",
      "HS512",
      "ES256",
      "RS256",
      "HS384",
      "ES512",
      "PS256",
      "PS512",
      "RS512",
      "none"
   ],
   "request_object_signing_alg_values_supported":[  
      "PS384",
      "ES384",
      "RS384",
      "ES256",
      "RS256",
      "ES512",
      "PS256",
      "PS512",
      "RS512",
      "none"
   ],
   "response_modes_supported":[  
      "query",
      "fragment",
      "form_post"
   ],
   "registration_endpoint":"http://localhost:8080/auth/realms/master/clients-registrations/openid-connect",
   "token_endpoint_auth_methods_supported":[  
      "private_key_jwt",
      "client_secret_basic",
      "client_secret_post",
      "client_secret_jwt"
   ],
   "token_endpoint_auth_signing_alg_values_supported":[  
      "RS256"
   ],
   "claims_supported":[  
      "aud",
      "sub",
      "iss",
      "auth_time",
      "name",
      "given_name",
      "family_name",
      "preferred_username",
      "email"
   ],
   "claim_types_supported":[  
      "normal"
   ],
   "claims_parameter_supported":false,
   "scopes_supported":[  
      "openid",
      "address",
      "email",
      "microprofile-jwt",
      "offline_access",
      "phone",
      "profile",
      "roles",
      "web-origins"
   ],
   "request_parameter_supported":true,
   "request_uri_parameter_supported":true,
   "code_challenge_methods_supported":[  
      "plain",
      "S256"
   ],
   "tls_client_certificate_bound_access_tokens":true,
   "introspection_endpoint":"http://localhost:8080/auth/realms/master/protocol/openid-connect/token/introspect"
}

Should you always favor xrange() over range()?

One other difference is that xrange() can't support numbers bigger than C ints, so if you want to have a range using python's built in large number support, you have to use range().

Python 2.7.3 (default, Jul 13 2012, 22:29:01) 
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> range(123456787676676767676676,123456787676676767676679)
[123456787676676767676676L, 123456787676676767676677L, 123456787676676767676678L]
>>> xrange(123456787676676767676676,123456787676676767676679)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

Python 3 does not have this problem:

Python 3.2.3 (default, Jul 14 2012, 01:01:48) 
[GCC 4.7.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> range(123456787676676767676676,123456787676676767676679)
range(123456787676676767676676, 123456787676676767676679)

Writing Unicode text to a text file?

Deal exclusively with unicode objects as much as possible by decoding things to unicode objects when you first get them and encoding them as necessary on the way out.

If your string is actually a unicode object, you'll need to convert it to a unicode-encoded string object before writing it to a file:

foo = u'?, ?, ?, ? ?, ?, ?, ?, ?, and ?.'
f = open('test', 'w')
f.write(foo.encode('utf8'))
f.close()

When you read that file again, you'll get a unicode-encoded string that you can decode to a unicode object:

f = file('test', 'r')
print f.read().decode('utf8')

Text File Parsing with Python

I would use a for loop to iterate over the lines in the text file:

for line in my_text:
    outputfile.writelines(data_parser(line, reps))

If you want to read the file line-by-line instead of loading the whole thing at the start of the script you could do something like this:

inputfile = open('test.dat')
outputfile = open('test.csv', 'w')

# sample text string, just for demonstration to let you know how the data looks like
# my_text = '"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636'

# dictionary definition 0-, 1- etc. are there to parse the date block delimited with dashes, and make sure the negative numbers are not effected
reps = {'"NAN"':'NAN', '"':'', '0-':'0,','1-':'1,','2-':'2,','3-':'3,','4-':'4,','5-':'5,','6-':'6,','7-':'7,','8-':'8,','9-':'9,', ' ':',', ':':',' }

for i in range(4): inputfile.next() # skip first four lines
for line in inputfile:
    outputfile.writelines(data_parser(line, reps))

inputfile.close()
outputfile.close()

How to bundle an Angular app for production

"Best" depends on the scenario. There are times when you only care about the smallest possible single bundle, but in large apps you may have to consider lazy loading. At some point it becomes impractical to serve the entire app as a single bundle.

In the latter case Webpack is generally the best way since it supports code splitting.

For a single bundle I would consider Rollup, or the Closure compiler if you are feeling brave :-)

I have created samples of all Angular bundlers I've ever used here: http://www.syntaxsuccess.com/viewarticle/angular-production-builds

The code can be found here: https://github.com/thelgevold/angular-2-samples

Angular version: 4.1.x

How to select the row with the maximum value in each group

One more base R solution:

merge(aggregate(pt ~ Subject, max, data = group), group)

  Subject pt Event
1       1  5     2
2       2 17     2
3       3  5     2

Immutable vs Mutable types

A class is immutable if each object of that class has a fixed value upon instantiation that cannot SUBSEQUENTLY be changed

In another word change the entire value of that variable (name) or leave it alone.

Example:

my_string = "Hello world" 
my_string[0] = "h"
print my_string 

you expected this to work and print hello world but this will throw the following error:

Traceback (most recent call last):
File "test.py", line 4, in <module>
my_string[0] = "h"
TypeError: 'str' object does not support item assignment

The interpreter is saying : i can't change the first character of this string

you will have to change the whole string in order to make it works:

my_string = "Hello World" 
my_string = "hello world"
print my_string #hello world

check this table:

enter image description here

source

Maximum packet size for a TCP connection

This is an excellent question and I run in to this a lot at work actually. There are a lot of "technically correct" answers such as 65k and 1500. I've done a lot of work writing network interfaces and using 65k is silly, and 1500 can also get you in to big trouble. My work goes on a lot of different hardware / platforms / routers, and to be honest the place I start is 1400 bytes. If you NEED more than 1400 you can start to inch your way up, you can probably go to 1450 and sometimes to 1480'ish? If you need more than that then of course you need to split in to 2 packets, of which there are several obvious ways of doing..

The problem is that you're talking about creating a data packet and writing it out via TCP, but of course there's header data tacked on and so forth, so you have "baggage" that puts you to 1500 or beyond.. and also a lot of hardware has lower limits.

If you "push it" you can get some really weird things going on. Truncated data, obviously, or dropped data I've seen rarely. Corrupted data also rarely but certainly does happen.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

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

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

remove kernel on jupyter notebook

Just for completeness, you can get a list of kernels with jupyter kernelspec list, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel. If you do not see everything in this list when you run jupyter kernelspec list, try looking in common Jupyter folders:

ls ~/.local/share/jupyter/kernels  # usually where local kernels go
ls /usr/local/share/jupyter/kernels  # usually where system-wide kernels go
ls /usr/share/jupyter/kernels  # also where system-wide kernels can go

Also, you can delete a kernel with jupyter kernelspec remove or jupyter kernelspec uninstall. The latter is an alias for remove. From the in-line help text for the command:

uninstall
    Alias for remove
remove
    Remove one or more Jupyter kernelspecs by name.

How to grep recursively, but only in files with certain extensions?

The below answer is good:

grep -r -i --include \*.h --include \*.cpp CP_Image ~/path[12345] | mailx -s GREP [email protected]

But can be updated to:

grep -r -i --include \*.{h,cpp} CP_Image ~/path[12345] | mailx -s GREP [email protected]

Which can be more simple.

MAX(DATE) - SQL ORACLE

SELECT p.MEMBSHIP_ID
FROM user_payments as p
WHERE USER_ID = 1 AND PAYM_DATE = (
    SELECT MAX(p2.PAYM_DATE)
    FROM user_payments as p2
    WHERE p2.USER_ID = p.USER_ID
)

Java split string to array

This is expected. Refer to Javadocs for split.

Splits this string around matches of the given regular expression.

This method works as if by invoking the two-argument split(java.lang.String,int) method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

OPTION (RECOMPILE) is Always Faster; Why?

To add to the excellent list (given by @CodeCowboyOrg) of situations where OPTION(RECOMPILE) can be very helpful,

  1. Table Variables. When you are using table variables, there will not be any pre-built statistics for the table variable, often leading to large differences between estimated and actual rows in the query plan. Using OPTION(RECOMPILE) on queries with table variables allows generation of a query plan that has a much better estimate of the row numbers involved. I had a particularly critical use of a table variable that was unusable, and which I was going to abandon, until I added OPTION(RECOMPILE). The run time went from hours to just a few minutes. That is probably unusual, but in any case, if you are using table variables and working on optimizing, it's well worth seeing whether OPTION(RECOMPILE) makes a difference.

You must add a reference to assembly 'netstandard, Version=2.0.0.0

We started getting this error on the production server after deploying the application migrated from 4.6.1 to 4.7.2.

We noticed that the .NET framework 4.7.2 was not installed there. In order to solve this issue we did the following steps:

  1. Installed the .NET Framework 4.7.2 from:

    https://support.microsoft.com/en-us/help/4054530/microsoft-net-framework-4-7-2-offline-installer-for-windows

  2. Restarted the machine

  3. Confirmed the .NET Framework version with the help of How do I find the .NET version?

Running the application again with the .Net Framework 4.7.2 version installed on the machine fixed the issue.

Zoom in on a point (using scale and translate)

I ran into this problem using c++, which I probably shouldn't have had i just used OpenGL matrices to begin with...anyways, if you're using a control whose origin is the top left corner, and you want pan/zoom like google maps, here's the layout (using allegro as my event handler):

// initialize
double originx = 0; // or whatever its base offset is
double originy = 0; // or whatever its base offset is
double zoom = 1;

.
.
.

main(){

    // ...set up your window with whatever
    //  tool you want, load resources, etc

    .
    .
    .
    while (running){
        /* Pan */
        /* Left button scrolls. */
        if (mouse == 1) {
            // get the translation (in window coordinates)
            double scroll_x = event.mouse.dx; // (x2-x1) 
            double scroll_y = event.mouse.dy; // (y2-y1) 

            // Translate the origin of the element (in window coordinates)      
            originx += scroll_x;
            originy += scroll_y;
        }

        /* Zoom */ 
        /* Mouse wheel zooms */
        if (event.mouse.dz!=0){    
            // Get the position of the mouse with respect to 
            //  the origin of the map (or image or whatever).
            // Let us call these the map coordinates
            double mouse_x = event.mouse.x - originx;
            double mouse_y = event.mouse.y - originy;

            lastzoom = zoom;

            // your zoom function 
            zoom += event.mouse.dz * 0.3 * zoom;

            // Get the position of the mouse
            // in map coordinates after scaling
            double newx = mouse_x * (zoom/lastzoom);
            double newy = mouse_y * (zoom/lastzoom);

            // reverse the translation caused by scaling
            originx += mouse_x - newx;
            originy += mouse_y - newy;
        }
    }
}  

.
.
.

draw(originx,originy,zoom){
    // NOTE:The following is pseudocode
    //          the point is that this method applies so long as
    //          your object scales around its top-left corner
    //          when you multiply it by zoom without applying a translation.

    // draw your object by first scaling...
    object.width = object.width * zoom;
    object.height = object.height * zoom;

    //  then translating...
    object.X = originx;
    object.Y = originy; 
}

Check if a string is a date value

function isDate(dateStr) {
  return !isNaN(new Date(dateStr).getDate());
}
  • This will work on any browser since it does not rely on "Invalid Date" check.
  • This will work with legacy code before ES6.
  • This will work without any library.
  • This will work regardless of any date format.
  • This does not rely on Date.parse which fails the purpose when values like "Spiderman 22" are in date string.
  • This does not ask us to write any RegEx.

auto create database in Entity Framework Core

For EF Core 2.0+ I had to take a different approach because they changed the API. As of March 2019 Microsoft recommends you put your database migration code in your application entry class but outside of the WebHost build code.

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();
        using (var serviceScope = host.Services.CreateScope())
        {
            var context = serviceScope.ServiceProvider.GetRequiredService<PersonContext>();
            context.Database.Migrate();
        }
        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

Hashing a dictionary?

The code below avoids using the Python hash() function because it will not provide hashes that are consistent across restarts of Python (see hash function in Python 3.3 returns different results between sessions). make_hashable() will convert the object into nested tuples and make_hash_sha256() will also convert the repr() to a base64 encoded SHA256 hash.

import hashlib
import base64

def make_hash_sha256(o):
    hasher = hashlib.sha256()
    hasher.update(repr(make_hashable(o)).encode())
    return base64.b64encode(hasher.digest()).decode()

def make_hashable(o):
    if isinstance(o, (tuple, list)):
        return tuple((make_hashable(e) for e in o))

    if isinstance(o, dict):
        return tuple(sorted((k,make_hashable(v)) for k,v in o.items()))

    if isinstance(o, (set, frozenset)):
        return tuple(sorted(make_hashable(e) for e in o))

    return o

o = dict(x=1,b=2,c=[3,4,5],d={6,7})
print(make_hashable(o))
# (('b', 2), ('c', (3, 4, 5)), ('d', (6, 7)), ('x', 1))

print(make_hash_sha256(o))
# fyt/gK6D24H9Ugexw+g3lbqnKZ0JAcgtNW+rXIDeU2Y=

No newline at end of file

For what it's worth, I encountered this when I created an IntelliJ project on a Mac, and then moved the project over to my Windows machine. I had to manually open every file and change the encoding setting at the bottom right of the IntelliJ window. Probably not happening to most if any who read this question but that could have saved me a couple of hours of work...

Copy entire contents of a directory to another using php

The best solution is!

<?php
$src = "/home/www/domain-name.com/source/folders/123456";
$dest = "/home/www/domain-name.com/test/123456";

shell_exec("cp -r $src $dest");

echo "<H3>Copy Paste completed!</H3>"; //output when done
?>

Win32Exception (0x80004005): The wait operation timed out

We encountered this error after an upgrade from 2008 to 2014 SQL Server where our some of our previous connection strings for local development had a Data Source=./ like this

        <add name="MyLocalDatabase" connectionString="Data Source=./;Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

Changing that from ./ to either (local) or localhost fixed the problem.

<add name="MyLocalDatabase" connectionString="Data Source=(local);Initial Catalog=SomeCatalog;Integrated Security=SSPI;Application Name=MyApplication;"/>

Bootstrap alert in a fixed floating div at the top of page

I think the issue is that you need to wrap your div in a container and/or row.

This should achieve a similar look as what you are looking for:

<div class="container">
    <div class="row" id="error-container">
         <div class="span12">  
             <div class="alert alert-error">
                <button type="button" class="close" data-dismiss="alert">×</button>
                 test error message
             </div>
         </div>
    </div>
</div>

CSS:

#error-container {
     margin-top:10px;
     position: fixed;
}

Bootply demo

BeautifulSoup Grab Visible Webpage Text

The simplest way to handle this case is by using getattr(). You can adapt this example to your needs:

from bs4 import BeautifulSoup

source_html = """
<span class="ratingsDisplay">
    <a class="ratingNumber" href="https://www.youtube.com/watch?v=oHg5SJYRHA0" target="_blank" rel="noopener">
        <span class="ratingsContent">3.7</span>
    </a>
</span>
"""

soup = BeautifulSoup(source_html, "lxml")
my_ratings = getattr(soup.find('span', {"class": "ratingsContent"}), "text", None)
print(my_ratings)

This will find the text element,"3.7", within the tag object <span class="ratingsContent">3.7</span> when it exists, however, default to NoneType when it does not.

getattr(object, name[, default])

Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise, AttributeError is raised.

Datatables: Cannot read property 'mData' of undefined

in my case this error occured if i use table without header

              <thead>
                   <tr>
                       <th>example</th>
                  </tr>
              </thead>

Command line tool to dump Windows DLL version?

You can write a VBScript script to get the file version info:

VersionInfo.vbs

set args = WScript.Arguments
Set fso = CreateObject("Scripting.FileSystemObject")
WScript.Echo fso.GetFileVersion(args(0))
Wscript.Quit

You can call this from the command line like this:

cscript //nologo VersionInfo.vbs C:\Path\To\MyFile.dll

Completely cancel a rebase

Use git rebase --abort. From the official Linux kernel documentation for git rebase:

git rebase --continue | --skip | --abort | --edit-todo

How to select true/false based on column value?

Use a CASE. I would post the specific code, but need more information than is supplied in the post - such as the data type of EntityProfile and what is usually stored in it. Something like:

CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END

Edit - the entire SELECT statement, as per the info in the comments:

SELECT EntityID, EntityName, 
       CASE WHEN EntityProfile IS NULL THEN 'False' ELSE 'True' END AS HasProfile
FROM Entity

No LEFT JOIN necessary in this case...

deny directory listing with htaccess

If Options -Indexes does not work as Bryan Drewery suggested, you could write a recursive method to create blank index.php files.

Place this inside of your base folder you wish to protect, you can name it whatever (I would recommend index.php)

<?php

recurse(".");

function recurse($path){
    foreach(scandir($path) as $o){
        if($o != "." && $o != ".."){
            $full = $path . "/" . $o;
            if(is_dir($full)){
                if(!file_exists($full . "/index.php")){
                    file_put_contents($full . "/index.php", "");
                }
                recurse($full);
            }
        }
    }
}

?>

These blank index.php files can be easily deleted or overwritten, and they'll keep your directories from being listable.

Override body style for content in an iframe

If you have control of the page hosting the iframe and the page of the iframe, you can pass a query parameter to the iframe...

Here's an example to add a class to the iframe based on whether or not the hosting site is mobile...

Adding iFrame:

var isMobile=$("mobile").length; //detect if page is mobile
var iFrameUrl ="https://myiframesite/?isMobile=" + isMobile; 

$(body).append("<div id='wrapper'><iframe src=''></iframe></div>");
$("#wrapper iframe").attr("src", iFrameUrl ); 

Inside iFrame:

//add mobile class if needed
var url = new URL(window.location.href);
var isMobile = url.searchParams.get("isMobile");
if(isMobile == "1") {
    $("body").addClass("mobile");
}

How can I split a string into segments of n characters?

Coming a little later to the discussion but here a variation that's a little faster than the substring + array push one.

// substring + array push + end precalc
var chunks = [];

for (var i = 0, e = 3, charsLength = str.length; i < charsLength; i += 3, e += 3) {
    chunks.push(str.substring(i, e));
}

Pre-calculating the end value as part of the for loop is faster than doing the inline math inside substring. I've tested it in both Firefox and Chrome and they both show speedup.

You can try it here

How to resolve git stash conflict without commit?

It seems that this may be the answer you're looking for, I haven't tried this personally yet, but it seems like it may do the trick. With this command GIT will try to apply the changes as they were before, without trying to add all of them for commit.

git stash apply --index

here is the full explanation:

http://git-scm.com/book/en/Git-Tools-Stashing

php hide ALL errors

The best way is to build your script in a way it cannot create any errors! When there is something that can create a Notice or an Error there is something wrong with your script and the checking of variables and environment!

If you want to hide them anyway: error_reporting(0);

How can I split a shell command over multiple lines when using an IF statement?

For Windows/WSL/Cygwin etc users:

Make sure that your line endings are standard Unix line feeds, i.e. \n (LF) only.

Using Windows line endings \r\n (CRLF) line endings will break the command line break.


This is because having \ at the end of a line with Windows line ending translates to \ \r \n.
As Mark correctly explains above:

The line-continuation will fail if you have whitespace after the backslash and before the newline.

This includes not just space () or tabs (\t) but also the carriage return (\r).

Android ListView Text Color

Ok, here are some things that you should be clear about:

  1. The background color you are setting in your xml file is of the activity and not of the ListItems you are trying to define.
  2. Every list item has its own layout file which should be passed or inflated in case you are using complex layout for list item.

I'll try to explain this with a code sample:

****Lets start with ListItems layout** : save it in your res/layout folder of you Android project with say **list_black_text.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Definig a container for you List Item-->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:gravity="center_vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <!-- Defining where should text be placed. You set you text color here-->
    <TextView
        android:id="@+id/list_content"
        android:textColor="#000000"
        android:gravity="center"
        android:text="sample"
        android:layout_margin="4dip"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</LinearLayout>

Well, a simple layout with a TextView to be precise. You must have an id assigned to TextView in order to use it.

Now coming to you screen/activity/chief layout, as I said you are defining background to your screen with android:background attribute. I see you have defined a TextView there as well and I suspect you are trying to define content/list item there, which is not at all needed.

Here's your edited layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" 
    android:background="#FFFFFF">

    <ListView 
        android:id="@android:id/list" android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
        <!-- REMOVED TEXT VIEW, AND KEEPING BACKGROUND WHITE -->
</LinearLayout>

And lastly, most importantly, set your adapter.

setListAdapter(new ArrayAdapter<String>(
            this, R.layout.list_black_text, R.id.list_content, listItems));

Notice the layout resource which we are passing to adapter R.layout.list_black_text, and R.id.list_content which is TextView ID we declared. I have also changed ArrayAdapter to String type since it's generic.

I hope this explains everything. Mark my answer accepted if you agree.

Messy but a good quick fix way
You can also do this with a quick fix if you do not want to go ahead with complex layout defining etc.

While instantiating the adapter declare an inner class to do this, here is the code sample:

    ArrayAdapter<String> adapter=new ArrayAdapter<String>(
            this, android.R.layout.simple_list_item_1, listItems){

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view =super.getView(position, convertView, parent);

            TextView textView=(TextView) view.findViewById(android.R.id.text1);

            /*YOUR CHOICE OF COLOR*/
            textView.setTextColor(Color.BLUE);

            return view;
        }
    };

    /*SET THE ADAPTER TO LISTVIEW*/
    setListAdapter(adapter);

How do I dynamically change the content in an iframe using jquery?

var handle = setInterval(changeIframe, 30000);
var sites = ["google.com", "yahoo.com"];
var index = 0;

function changeIframe() {
  $('#frame')[0].src = sites[index++];
  index = index >= sites.length ? 0 : index;
}

How do I find out my root MySQL password?

It is actually very simple. You don't have to go through a lot of stuff. Just run the following command in terminal and follow on-screen instructions.

sudo mysql_secure_installation

Properly embedding Youtube video into bootstrap 3.0 page

It also depend on how you style your site with bootstrap. In my example, I am using col-md-12 for my video div, and add class col-sm-12 for the iframe, so when resize to smaller screen, the video will not view squeezed. I add also height to the iframe:

<div class="col-md-12">
<iframe class="col-sm-12" height="333" frameborder="0" wmode="Opaque" allowfullscreen="" src="https://www.youtube.com/embed/oqDRPoPDehE?wmode=transparent">
</div>

Remove the legend on a matplotlib figure

As of matplotlib v1.4.0rc4, a remove method has been added to the legend object.

Usage:

ax.get_legend().remove()

or

legend = ax.legend(...)
...
legend.remove()

See here for the commit where this was introduced.

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

How to check if a variable is equal to one string or another string?

This does not do what you expect:

if var is 'stringone' or 'stringtwo':
    dosomething()

It is the same as:

if (var is 'stringone') or 'stringtwo':
    dosomething()

Which is always true, since 'stringtwo' is considered a "true" value.

There are two alternatives:

if var in ('stringone', 'stringtwo'):
    dosomething()

Or you can write separate equality tests,

if var == 'stringone' or var == 'stringtwo':
    dosomething()

Don't use is, because is compares object identity. You might get away with it sometimes because Python interns a lot of strings, just like you might get away with it in Java because Java interns a lot of strings. But don't use is unless you really want object identity.

>>> 'a' + 'b' == 'ab'
True
>>> 'a' + 'b' is 'abc'[:2]
False # but could be True
>>> 'a' + 'b' is 'ab'
True  # but could be False

JSON.stringify output to div in pretty print way

My proposal is based on:

  • replace each '\n' (newline) with a <br>
  • replace each space with &nbsp;

_x000D_
_x000D_
var x = { "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 };_x000D_
_x000D_
_x000D_
document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)_x000D_
     .replace(/\n( *)/g, function (match, p1) {_x000D_
         return '<br>' + '&nbsp;'.repeat(p1.length);_x000D_
     });
_x000D_
<div id="newquote"></div>
_x000D_
_x000D_
_x000D_

How to temporarily disable a click handler in jQuery?

This code will display loading on the button label, and set button to disable state, then after processing, re-enable and return back the original button text:

$(function () {

        $(".btn-Loading").each(function (idx, elm) {
            $(elm).click(function () {
                //do processing
                if ($(".input-validation-error").length > 0)
                    return;
                $(this).attr("label", $(this).text()).text("loading ....");
                $(this).delay(1000).animate({ disabled: true }, 1000, function () {
                    //original event call
                    $.when($(elm).delay(1000).one("click")).done(function () {
                        $(this).animate({ disabled: false }, 1000, function () {
                            $(this).text($(this).attr("label"));
                        })
                    });
                    //processing finalized
                });
            });
        });
        // and fire it after definition
    }
   );

Running npm command within Visual Studio Code

There is an extension available, npm Script runner. I have not tried it myself, though.

How to "comment-out" (add comment) in a batch/cmd?

No, plain old batch files use REM as a comment. ECHO is the command that prints something on the screen.

To "comment out" sections of the file you could use GOTO. An example of all these commands/techniques:

REM it starts here the section below can be safely erased once the file is customised
ECHO Hey you need to edit this file before running it!  Check the instructions inside
ECHO Now press ctrl-c to interrupt execution or enter to continue
PAUSE
REM erase the section above once you have customised the file
python executed1.py
ECHO Skipping some stuff now
GOTO End
python skipped1.py
python skipped2.py
:END
python executed2.py

What can I say? batch files are a relic of times long gone, they're clunky and ugly.

You can read more on this website.

EDIT: modified the example a bit to have it contain the elements you are apparently looking for.

Reading Datetime value From Excel sheet

i had a similar situation and i used the below code for getting this worked..

Aspose.Cells.LoadOptions loadOptions = new Aspose.Cells.LoadOptions(Aspose.Cells.LoadFormat.CSV);

Workbook workbook = new Workbook(fstream, loadOptions);

Worksheet worksheet = workbook.Worksheets[0];

dt = worksheet.Cells.ExportDataTable(0, 0, worksheet.Cells.MaxDisplayRange.RowCount, worksheet.Cells.MaxDisplayRange.ColumnCount, true);

DataTable dtCloned = dt.Clone();
ArrayList myAL = new ArrayList();

foreach (DataColumn column in dtCloned.Columns)
{
    if (column.DataType == Type.GetType("System.DateTime"))
    {
        column.DataType = typeof(String);
        myAL.Add(column.ColumnName);
    }
}


foreach (DataRow row in dt.Rows)
{
    dtCloned.ImportRow(row);
}



foreach (string colName in myAL)
{
    dtCloned.Columns[colName].Convert(val => DateTime.Parse(Convert.ToString(val)).ToString("MMMM dd, yyyy"));
}


/*******************************/

public static class MyExtension
{
    public static void Convert<T>(this DataColumn column, Func<object, T> conversion)
    {
        foreach (DataRow row in column.Table.Rows)
        {
            row[column] = conversion(row[column]);
        }
    }
}

Hope this helps some1 thx_joxin

Add a prefix string to beginning of each line

awk '$0="prefix"$0' file > new_file

With Perl(in place replacement):

perl -pi 's/^/prefix/' file

Uncaught TypeError: Cannot read property 'msie' of undefined

$.browser was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.

Can I redirect the stdout in python into some sort of string buffer?

Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.

This can be used to good effect to "catch" stdout output in a GUI application.

Here's a silly example in PyQt:

import sys
from PyQt4 import QtGui

class OutputWindow(QtGui.QPlainTextEdit):
    def write(self, txt):
        self.appendPlainText(str(txt))

app = QtGui.QApplication(sys.argv)
out = OutputWindow()
sys.stdout=out
out.show()
print "hello world !"

Make file echo displaying "$PATH" string

The make uses the $ for its own variable expansions. E.g. single character variable $A or variable with a long name - ${VAR} and $(VAR).

To put the $ into a command, use the $$, for example:

all:
  @echo "Please execute next commands:"
  @echo 'setenv PATH /usr/local/greenhills/mips5/linux86:$$PATH'

Also note that to make the "" and '' (double and single quoting) do not play any role and they are passed verbatim to the shell. (Remove the @ sign to see what make sends to shell.) To prevent the shell from expanding $PATH, second line uses the ''.

Expression ___ has changed after it was checked

I think a most simple solution would be as follows:

  1. Make one implementation of assigning a value to some variable i.e. via function or setter.
  2. Create a class variable (static working: boolean) in the class where this function exists and every time you call the function, simply make it true whichever you like. Within the function, if the value of working is true, then simply return right away without doing anything. else, perform the task you want. Make sure to change this variable to false once the task is completed i.e. at the end of the line of codes or within the subscribe method when you are done assigning values!

How do you run a command as an administrator from the Windows command line?

A batch/WSH hybrid is able to call ShellExecute to display the UAC elevation dialog...

@if (1==1) @if(1==0) @ELSE
@echo off&SETLOCAL ENABLEEXTENSIONS
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"||(
    cscript //E:JScript //nologo "%~f0"
    @goto :EOF
)
echo.Performing admin tasks...
REM call foo.exe
@goto :EOF
@end @ELSE
ShA=new ActiveXObject("Shell.Application")
ShA.ShellExecute("cmd.exe","/c \""+WScript.ScriptFullName+"\"","","runas",5);
@end

how to pass parameters to query in SQL (Excel)

This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.

This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.

So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.

Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))

What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.

First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:

[Picture of a cell of prompt (label) text, an empty cell, then a button.]

Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.

Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).

Sub RefreshQuery()
 Dim queryPreText As String
 Dim queryPostText As String
 Dim valueToFilter As String
 Dim paramPosition As Integer
 valueToFilter = "DB_TABLE_NAME.Field_Name ="

 With ActiveWorkbook.Connections("Connection name").OLEDBConnection
     queryPreText = .CommandText
     paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
     queryPreText = Left(queryPreText, paramPosition)
     queryPostText = .CommandText
     queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
     queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
     .CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
 End With
 ActiveWorkbook.Connections("Connection name").Refresh
End Sub

Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).

Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).

Save and close the VBA editor.

Enter your parameter in the appropriate cell.

Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!

Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".

This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.

Equal height rows in CSS Grid Layout

Short Answer

If the goal is to create a grid with equal height rows, where the tallest cell in the grid sets the height for all rows, here's a quick and simple solution:

  • Set the container to grid-auto-rows: 1fr

How it works

Grid Layout provides a unit for establishing flexible lengths in a grid container. This is the fr unit. It is designed to distribute free space in the container and is somewhat analogous to the flex-grow property in flexbox.

If you set all rows in a grid container to 1fr, let's say like this:

grid-auto-rows: 1fr;

... then all rows will be equal height.

It doesn't really make sense off-the-bat because fr is supposed to distribute free space. And if several rows have content with different heights, then when the space is distributed, some rows would be proportionally smaller and taller.

Except, buried deep in the grid spec is this little nugget:

7.2.3. Flexible Lengths: the fr unit

...

When the available space is infinite (which happens when the grid container’s width or height is indefinite), flex-sized (fr) grid tracks are sized to their contents while retaining their respective proportions.

The used size of each flex-sized grid track is computed by determining the max-content size of each flex-sized grid track and dividing that size by the respective flex factor to determine a “hypothetical 1fr size”.

The maximum of those is used as the resolved 1fr length (the flex fraction), which is then multiplied by each grid track’s flex factor to determine its final size.

So, if I'm reading this correctly, when dealing with a dynamically-sized grid (e.g., the height is indefinite), grid tracks (rows, in this case) are sized to their contents.

The height of each row is determined by the tallest (max-content) grid item.

The maximum height of those rows becomes the length of 1fr.

That's how 1fr creates equal height rows in a grid container.


Why flexbox isn't an option

As noted in the question, equal height rows are not possible with flexbox.

Flex items can be equal height on the same row, but not across multiple rows.

This behavior is defined in the flexbox spec:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

In order to show the icon, use getSupportActionBar().setIcon(R.xxx.xxx)

In my case the code is:-

getSupportActionBar().setIcon (R.mipmap.ic_launcher);

Insert multiple values using INSERT INTO (SQL Server 2005)

The syntax you are using is new to SQL Server 2008:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test'),(1001,N'test2')

For SQL Server 2005, you will have to use multiple INSERT statements:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1000,N'test')

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
 VALUES
       (1001,N'test2')

One other option is to use UNION ALL:

INSERT INTO [MyDB].[dbo].[MyTable]
       ([FieldID]
       ,[Description])
SELECT 1000, N'test' UNION ALL
SELECT 1001, N'test2'

#1142 - SELECT command denied to user ''@'localhost' for table 'pma_table_uiprefs'

This Will Surely help you

1.open PhpMyAdmin.

2.on the left side under the PhpMyAdmin logo click on second icon(Empty Session Data).

3.that's it.

enter image description here

Set QLineEdit to accept only numbers

The best is QSpinBox.

And for a double value use QDoubleSpinBox.

QSpinBox myInt;
myInt.setMinimum(-5);
myInt.setMaximum(5);
myInt.setSingleStep(1);// Will increment the current value with 1 (if you use up arrow key) (if you use down arrow key => -1)
myInt.setValue(2);// Default/begining value
myInt.value();// Get the current value
//connect(&myInt, SIGNAL(valueChanged(int)), this, SLOT(myValueChanged(int)));

If REST applications are supposed to be stateless, how do you manage sessions?

The whole concept is different... You don't need to manage sessions if you are trying to implement RESTFul protocol. In that case it is better to do authentication procedure on every request (whereas there is an extra cost to it in terms of performance - hashing password would be a good example. not a big deal...). If you use sessions - how can you distribute load across multiple servers? I bet RESTFul protocol is meant to eliminate sessions whatsoever - you don't really need them... That's why it is called "stateless". Sessions are only required when you cannot store anything other than Cookie on a client side after a reqest has been made (take old, non Javascript/HTML5-supporting browser as an example). In case of "full-featured" RESTFul client it is usually safe to store base64(login:password) on a client side (in memory) until the applictation is still loaded - the application is used to access to the only host and the cookie cannot be compromised by the third party scripts...

I would stronly recommend to disable cookie authentication for RESTFul sevices... check out Basic/Digest Auth - that should be enough for RESTFul based services.

Change hover color on a button with Bootstrap customization

This is the correct way to change btn color.

 .btn-primary:not(:disabled):not(.disabled).active, 
    .btn-primary:not(:disabled):not(.disabled):active, 
    .show>.btn-primary.dropdown-toggle{
        color: #fff;
        background-color: #F7B432;
        border-color: #F7B432;
    }

Javascript Cookie with no expiration date

Nope. That can't be done. The best 'way' of doing that is just making the expiration date be like 2100.

How do I bottom-align grid elements in bootstrap fluid layout

Based on the other answers here is an even more responsive version. I made changes from Ivan's version to support viewports <768px wide and to better support slow window resizes.

!function ($) { //ensure $ always references jQuery
    $(function () { //when dom has finished loading
        //make top text appear aligned to bottom: http://stackoverflow.com/questions/13841387/how-do-i-bottom-align-grid-elements-in-bootstrap-fluid-layout
        function fixHeader() {
            //for each element that is classed as 'pull-down'
            //reset margin-top for all pull down items
            $('.pull-down').each(function () {
                $(this).css('margin-top', 0);
            });

            //set its margin-top to the difference between its own height and the height of its parent
            $('.pull-down').each(function () {
                if ($(window).innerWidth() >= 768) {
                    $(this).css('margin-top', $(this).parent().height() - $(this).height());
                }
            });
        }

        $(window).resize(function () {
            fixHeader();
        });

        fixHeader();
    });
}(window.jQuery);

Visual Studio Code open tab in new window

With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.

See issue 89989:

It should be possible to e.g. invoke the "Open Active File in New Window" command and open that file into an empty workspace in the web.

new windows -- https://user-images.githubusercontent.com/900690/73733120-aa0f6680-473b-11ea-8bcd-f2f71b75b496.png

Array versus linked-list

For me it is like this,

  1. Access

    • Linked Lists allow only sequential access to elements. Thus the algorithmic complexities is order of O(n)
    • Arrays allow random access to its elements and thus the complexity is order of O(1)
  2. Storage

    • Linked lists require an extra storage for references. This makes them impractical for lists of small data items such as characters or boolean values.
    • Arrays do not need an extra storage to point to next data item. Each element can be accessed via indexes.
  3. Size

    • The size of Linked lists are dynamic by nature.
    • The size of array is restricted to declaration.
  4. Insertion/Deletion

    • Elements can be inserted and deleted in linked lists indefinitely.
    • Insertion/Deletion of values in arrays are very expensive. It requires memory reallocation.

Java - Convert integer to string

There are multiple ways:

  • String.valueOf(number) (my preference)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)

How to solve WAMP and Skype conflict on Windows 7?

I think it is better to change default port of Skype.

Open skype. Go to Tools, Options, Connections, change the port.

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

Unique device identification

I have following idea how you can deal with such Access Device ID (ADID):

Gen ADID

  • prepare web-page https://mypage.com/manager-login where trusted user e.g. Manager can login from device - that page should show button "Give access to this device"
  • when user press button, page send request to server to generate ADID
  • server gen ADID, store it on whitelist and return to page
  • then page store it in device localstorage
  • trusted user now logout.

Use device

  • Then other user e.g. Employee using same device go to https://mypage.com/statistics and page send to server request for statistics including parameter ADID (previous stored in localstorage)
  • server checks if the ADID is on the whitelist, and if yes then return data

In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.

You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.

In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.

UPDATE

Simpler approach based on links:

  • Manager login to system using any device and generate ONE-TIME USE LINK https://mypage.com/access-link/ZD34jse24Sfses3J (which works e.g. 24h).
  • Then manager send this link to employee (or someone else; e.g. by email) which put that link into device and server returns ADID to device which store it in Local Storage. After that link above stops working - so only the system and device know ADID
  • Then employee using this device can read data from https://mypage.com/statistics because it has ADID which is on servers whitelist

IOPub data rate exceeded in Jupyter notebook (when viewing image)

Try this:

jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10

Or this:

yourTerminal:prompt> jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 

Programmatically change UITextField Keyboard type

for people who want to use UIDatePicker as input:

UIDatePicker *timePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 250, 0, 0)];
[timePicker addTarget:self action:@selector(pickerChanged:)
     forControlEvents:UIControlEventValueChanged];
[_textField setInputView:timePicker];

// pickerChanged:
- (void)pickerChanged:(id)sender {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"d/M/Y"];
    _textField.text = [formatter stringFromDate:[sender date]];
}

Cheap way to search a large text file for a string

If it is "pretty large" file, then access the lines sequentially and don't read the whole file into memory:

with open('largeFile', 'r') as inF:
    for line in inF:
        if 'myString' in line:
            # do_something

What's the main difference between int.Parse() and Convert.ToInt32

Have a look in reflector:

int.Parse("32"):

public static int Parse(string s)
{
    return System.Number.ParseInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}

which is a call to:

internal static unsafe int ParseInt32(string s, NumberStyles style, NumberFormatInfo info)
{
    byte* stackBuffer = stackalloc byte[1 * 0x72];
    NumberBuffer number = new NumberBuffer(stackBuffer);
    int num = 0;
    StringToNumber(s, style, ref number, info, false);
    if ((style & NumberStyles.AllowHexSpecifier) != NumberStyles.None)
    {
        if (!HexNumberToInt32(ref number, ref num))
        {
            throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
        }
        return num;
    }
    if (!NumberToInt32(ref number, ref num))
    {
        throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
    }
    return num;
}

Convert.ToInt32("32"):

public static int ToInt32(string value)
{
    if (value == null)
    {
        return 0;
    }
    return int.Parse(value, CultureInfo.CurrentCulture);
}

As the first (Dave M's) comment says.

Type or namespace name does not exist

Delete the .refresh.dll file if you are under source control. Then rebuild. It should work. This worked for me

How to display a pdf in a modal window?

you can use iframe within your modal form so when u open the iframe window it open inside your your modal form . i hope you are rendering to some pdf opener with some url , if u have the pdf contents simply add the contents in a div in the modal form .

"Logging out" of phpMyAdmin?

The presence of the logout button depends on whether you are required to login or not, in the first place. This is tweakable in PHPMyAdmin config files.

Yet, I don't think that would change anything concerning your error message. You would need to fix the configuration for the message to go away.

Edit: this is the kind of solution you should be searching for. And here are plenty of others for you to explore ^^

std::enable_if to conditionally compile a member function

Here is my minimalist example, using a macro. Use double brackets enable_if((...)) when using more complex expressions.

template<bool b, std::enable_if_t<b, int> = 0>
using helper_enable_if = int;

#define enable_if(value) typename = helper_enable_if<value>

struct Test
{
     template<enable_if(false)>
     void run();
}

Make Iframe to fit 100% of container's remaining height

It will work with below mentioned code

<iframe src="http: //www.google.com.tw"style="position: absolute; height: 100%; border: none"></iframe>

Simple Android RecyclerView example

Android RecyclerView

Start by adding recyclerview library.

implementation 'androidx.recyclerview:recyclerview:1.1.0'

Create model class.

     public class UserModel implements Serializable {

    private String userName;


    public UserModel(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
   }

create adapter class.

public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersAdapterVh> implements Filterable {

    private List<UserModel> userModelList;
    private List<UserModel> getUserModelListFiltered;
    private Context context;
    private SelectedUser selectedUser;

    public UsersAdapter(List<UserModel> userModelList,SelectedUser selectedUser) {
        this.userModelList = userModelList;
        this.getUserModelListFiltered = userModelList;
        this.selectedUser = selectedUser;
    }

    @NonNull
    @Override
    public UsersAdapter.UsersAdapterVh onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        context = parent.getContext();

        return new UsersAdapterVh(LayoutInflater.from(context).inflate(R.layout.row_users,null));
    }

    @Override
    public void onBindViewHolder(@NonNull UsersAdapter.UsersAdapterVh holder, int position) {

        UserModel userModel = userModelList.get(position);

        String username = userModel.getUserName();
        String prefix = userModel.getUserName().substring(0,1);

        holder.tvUsername.setText(username);
        holder.tvPrefix.setText(prefix);

    }

    @Override
    public int getItemCount() {
        return userModelList.size();
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                FilterResults filterResults = new FilterResults();

                if(charSequence == null | charSequence.length() == 0){
                    filterResults.count = getUserModelListFiltered.size();
                    filterResults.values = getUserModelListFiltered;

                }else{
                    String searchChr = charSequence.toString().toLowerCase();

                    List<UserModel> resultData = new ArrayList<>();

                    for(UserModel userModel: getUserModelListFiltered){
                        if(userModel.getUserName().toLowerCase().contains(searchChr)){
                            resultData.add(userModel);
                        }
                    }
                    filterResults.count = resultData.size();
                    filterResults.values = resultData;

                }

                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

                userModelList = (List<UserModel>) filterResults.values;
                notifyDataSetChanged();

            }
        };
        return filter;
    }


    public interface SelectedUser{

        void selectedUser(UserModel userModel);

    }

    public class UsersAdapterVh extends RecyclerView.ViewHolder {

        TextView tvPrefix;
        TextView tvUsername;
        ImageView imIcon;
        public UsersAdapterVh(@NonNull View itemView) {
            super(itemView);
            tvPrefix = itemView.findViewById(R.id.prefix);
            tvUsername = itemView.findViewById(R.id.username);
            imIcon = itemView.findViewById(R.id.imageView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectedUser.selectedUser(userModelList.get(getAdapterPosition()));
                }
            });


        }
    }
}

create layout row_uses.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:padding="10dp"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="50dp"
            android:background="@drawable/users_bg"
            android:layout_height="50dp">
            <TextView
                android:id="@+id/prefix"
                android:layout_width="wrap_content"
                android:textSize="16sp"
                android:textColor="@color/headerColor"
                android:text="T"
                android:layout_centerInParent="true"
                android:layout_height="wrap_content"/>

        </RelativeLayout>
        <TextView
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:textSize="16sp"
            android:textColor="@color/headerColor"
            android:text="username"
            android:layout_marginStart="90dp"
            android:layout_centerVertical="true"
            android:layout_height="wrap_content"/>
        <ImageView
            android:layout_width="wrap_content"
            android:id="@+id/imageView"
            android:layout_margin="10dp"
            android:layout_alignParentEnd="true"
            android:src="@drawable/ic_navigate_next_black_24dp"
            android:layout_height="wrap_content"/>
    </RelativeLayout>

</LinearLayout>

Find recyclerview and populate data.

Toolbar toolbar;
RecyclerView recyclerView;

List<UserModel> userModelList = new ArrayList<>();

String[] names = {"Richard","Alice","Hannah","David"};

UsersAdapter usersAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    recyclerView = findViewById(R.id.recyclerview);
    toolbar = findViewById(R.id.toolbar);

    this.setSupportActionBar(toolbar);
    this.getSupportActionBar().setTitle("");

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

    for(String s:names){
        UserModel userModel = new UserModel(s);

        userModelList.add(userModel);
    }

    usersAdapter = new UsersAdapter(userModelList,this);

    recyclerView.setAdapter(usersAdapter);

}

find full tutorial and source code here:

Android RecyclerView

Access denied for user 'test'@'localhost' (using password: YES) except root user

connect your server from mysqlworkbench and run this command-> ALTER USER 'root'@'localhost' IDENTIFIED BY 'yourpassword';

Query to check index on a table

On Oracle:

  • Determine all indexes on table:

    SELECT index_name 
     FROM user_indexes
     WHERE table_name = :table
    
  • Determine columns indexes and columns on index:

    SELECT index_name
         , column_position
         , column_name
      FROM user_ind_columns
     WHERE table_name = :table
     ORDER BY index_name, column_order
    

References:

Get input type="file" value when it has multiple files selected

The files selected are stored in an array: [input].files

For example, you can access the items

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

For jQuery-comfortable people, it's similarly easy

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

Observable.of is not a function

For Angular 5+ :

import { Observable } from 'rxjs/Observable';should work. The observer package should match the import as well import { Observer } from 'rxjs/Observer'; if you're using observers that is

import {<something>} from 'rxjs'; does a huge import so it's better to avoid it.

Add error bars to show standard deviation on a plot in R

A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).

You should better use the errbar function from the Hmisc package:

d = data.frame(
  x  = c(1:5)
  , y  = c(1.1, 1.5, 2.9, 3.8, 5.2)
  , sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
)

##install.packages("Hmisc", dependencies=T)
library("Hmisc")

# add error bars (without adjusting yrange)
plot(d$x, d$y, type="n")
with (
  data = d
  , expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
)

# new plot (adjusts Yrange automatically)
with (
  data = d
  , expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
)

Replace one substring for another string in shell script

Since I can't add a comment. @ruaka To make the example more readable write it like this

full_string="I love Suzy and Mary"
search_string="Suzy"
replace_string="Sara"
my_string=${full_string/$search_string/$replace_string}
or
my_string=${full_string/Suzy/Sarah}

.Net picking wrong referenced assembly version

I was getting:

Could not load file or assembly 'XXX-new-3.3.0.0' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

It was because I changed the name of the assembly from XXX.dll to XXX-new-3.3.0.0.dll. Reverting name back to the original fixed the error.

How to listen for changes to a MongoDB collection?

MongoDB version 3.6 now includes change streams which is essentially an API on top of the OpLog allowing for trigger/notification-like use cases.

Here is a link to a Java example: http://mongodb.github.io/mongo-java-driver/3.6/driver/tutorials/change-streams/

A NodeJS example might look something like:

 var MongoClient = require('mongodb').MongoClient;
    MongoClient.connect("mongodb://localhost:22000/MyStore?readConcern=majority")
     .then(function(client){
       let db = client.db('MyStore')

       let change_streams = db.collection('products').watch()
          change_streams.on('change', function(change){
            console.log(JSON.stringify(change));
          });
      });

What is WebKit and how is it related to CSS?

This has been answered and accepted, but if someone is still wondering why are things a bit messed up today, you'll have to read this:

http://webaim.org/blog/user-agent-string-history/

It gives a good idea of how gecko, webkit and other major rendering engines evolved and what led to the current state of messed up user-agent strings.

Quoting the last paragraph for TL;DR purposes:

And then Google built Chrome, and Chrome used Webkit, and it was like Safari, and wanted pages built for Safari, and so pretended to be Safari. And thus Chrome used WebKit, and pretended to be Safari, and WebKit pretended to be KHTML, and KHTML pretended to be Gecko, and all browsers pretended to be Mozilla, and Chrome called itself Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13, and the user agent string was a complete mess, and near useless, and everyone pretended to be everyone else, and confusion abounded.

How to split one string into multiple strings separated by at least one space in bash shell?

Did you try just passing the string variable to a for loop? Bash, for one, will split on whitespace automatically.

sentence="This is   a sentence."
for word in $sentence
do
    echo $word
done

 

This
is
a
sentence.

jquery count li elements inside ul -> length?

Use $('ul#menu').children('li').length

.size() instead of .length will also work

Load local JSON file into variable

My solution, as answered here, is to use:

    var json = require('./data.json'); //with path

The file is loaded only once, further requests use cache.

edit To avoid caching, here's the helper function from this blogpost given in the comments, using the fs module:

var readJson = (path, cb) => {
  fs.readFile(require.resolve(path), (err, data) => {
    if (err)
      cb(err)
    else
      cb(null, JSON.parse(data))
  })
}

Show "Open File" Dialog

I agree John M has best answer to OP's question. Thought not explictly stated, the apparent purpose is to get a selected file name, whereas other answers return either counts or lists. I would add, however, that the msofiledialogfilepicker might be a better option in this case. ie:

Dim f As object
Set f = Application.FileDialog(msoFileDialogFilePicker)
dim varfile as variant 
f.show
with f
    .allowmultiselect = false
     for each varfile in .selecteditems
        msgbox varfile
     next varfile
end with

Note: the value of varfile will remain the same since multiselect is false (only one item is ever selected). I used its value outside the loop with equal success. It's probably better practice to do it as John M did, however. Also, the folder picker can be used to get a selected folder. I always prefer late binding, but I think the object is native to the default access library, so it may not be necessary here

Why is 2 * (i * i) faster than 2 * i * i in Java?

Kasperd asked in a comment of the accepted answer:

The Java and C examples use quite different register names. Are both example using the AMD64 ISA?

xor edx, edx
xor eax, eax
.L2:
mov ecx, edx
imul ecx, edx
add edx, 1
lea eax, [rax+rcx*2]
cmp edx, 1000000000
jne .L2

I don't have enough reputation to answer this in the comments, but these are the same ISA. It's worth pointing out that the GCC version uses 32-bit integer logic and the JVM compiled version uses 64-bit integer logic internally.

R8 to R15 are just new X86_64 registers. EAX to EDX are the lower parts of the RAX to RDX general purpose registers. The important part in the answer is that the GCC version is not unrolled. It simply executes one round of the loop per actual machine code loop. While the JVM version has 16 rounds of the loop in one physical loop (based on rustyx answer, I did not reinterpret the assembly). This is one of the reasons why there are more registers being used since the loop body is actually 16 times longer.

How to determine if a point is in a 2D triangle?

I agree with Andreas Brinck, barycentric coordinates are very convenient for this task. Note that there is no need to solve an equation system every time: just evaluate the analytical solution. Using Andreas' notation, the solution is:

s = 1/(2*Area)*(p0y*p2x - p0x*p2y + (p2y - p0y)*px + (p0x - p2x)*py);
t = 1/(2*Area)*(p0x*p1y - p0y*p1x + (p0y - p1y)*px + (p1x - p0x)*py);

where Area is the (signed) area of the triangle:

Area = 0.5 *(-p1y*p2x + p0y*(-p1x + p2x) + p0x*(p1y - p2y) + p1x*p2y);

Just evaluate s, t and 1-s-t. The point p is inside the triangle if and only if they are all positive.

EDIT: Note that the above expression for the area assumes that the triangle node numbering is counter-clockwise. If the numbering is clockwise, this expression will return a negative area (but with correct magnitude). The test itself (s>0 && t>0 && 1-s-t>0) doesn't depend on the direction of the numbering, however, since the expressions above that are multiplied by 1/(2*Area) also change sign if the triangle node orientation changes.

EDIT 2: For an even better computational efficiency, see coproc's comment below (which makes the point that if the orientation of the triangle nodes (clockwise or counter-clockwise) is known beforehand, the division by 2*Area in the expressions for s and t can be avoided). See also Perro Azul's jsfiddle-code in the comments under Andreas Brinck's answer.

Java and HTTPS url connection without downloading certificate

Java and HTTPS url connection without downloading certificate

If you really want to avoid downloading the server's certificate, then use an anonymous protocol like Anonymous Diffie-Hellman (ADH). The server's certificate is not sent with ADH and friends.

You select an anonymous protocol with setEnabledCipherSuites. You can see the list of cipher suites available with getEnabledCipherSuites.

Related: that's why you have to call SSL_get_peer_certificate in OpenSSL. You'll get a X509_V_OK with an anonymous protocol, and that's how you check to see if a certificate was used in the exchange.

But as Bruno and Stephed C stated, its a bad idea to avoid the checks or use an anonymous protocol.


Another option is to use TLS-PSK or TLS-SRP. They don't require server certificates either. (But I don't think you can use them).

The rub is, you need to be pre-provisioned in the system because TLS-PSK is Pres-shared Secret and TLS-SRP is Secure Remote Password. The authentication is mutual rather than server only.

In this case, the mutual authentication is provided by a property that both parties know the shared secret and arrive at the same premaster secret; or one (or both) does not and channel setup fails. Each party proves knowledge of the secret is the "mutual" part.

Finally, TLS-PSK or TLS-SRP don't do dumb things, like cough up the user's password like in a web app using HTTP (or over HTTPS). That's why I said each party proves knowledge of the secret...

Manually put files to Android emulator SD card

In Android Studio, open the Device Manager: Tools -> Android -> Android Device Monitor

In Eclipse open the Device Manager: enter image description here

In the device manager you can add files to the SD Card here: enter image description here

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

Open page in new window without popup blocking

A browser will only open a tab/popup without the popup blocker warning if the command to open the tab/popup comes from a trusted event. That means the user has to actively click somewhere to open a popup.

In your case, the user performs a click so you have the trusted event. You do lose that trusted context, however, by performing the Ajax request. Your success handler does not have that event anymore. The only way to circumvent this is to perform a synchronous Ajax request which will block your browser while it runs, but will preserve the event context.

In jQuery this should do the trick:

$.ajax({
 url: 'http://yourserver/',
 data: 'your image',
 success: function(){window.open(someUrl);},
 async: false
});

Here is your answer: Open new tab without popup blocker after ajax call on user click

MySQL duplicate entry error even though there is no duplicate entry

This problem is often created when adding a column or using an existing column as a primary key. It is not created due to a primary key existing that was never actually created or due to damage to the table.

What the error actually denotes is that a pending key value is blank.

The solution is to populate the column with unique values and then try to create the primary key again. There can be no blank, null or duplicate values, or this misleading error will appear.

How to make MySQL handle UTF-8 properly

MySQL 4.1 and above has a default character set that it calls utf8 but which is actually only a subset of UTF-8 (allows only three-byte characters and smaller).

Use utf8mb4 as your charset if you want "full" UTF-8.

Start redis-server with config file

To start redis with a config file all you need to do is specifiy the config file as an argument:

redis-server /root/config/redis.rb

Instead of using and killing PID's I would suggest creating an init script for your service

I would suggest taking a look at the Installing Redis more properly section of http://redis.io/topics/quickstart. It will walk you through setting up an init script with redis so you can just do something like service redis_server start and service redis_server stop to control your server.

I am not sure exactly what distro you are using, that article describes instructions for a Debian based distro. If you are are using a RHEL/Fedora distro let me know, I can provide you with instructions for the last couple of steps, the config file and most of the other steps will be the same.

How to detect IE11?

Get IE Version from the User-Agent

var ie = 0;
try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; }
catch(e){}

How it works: The user-agent string for all IE versions includes a portion "MSIE space version" or "Trident other-text rv space-or-colon version". Knowing this, we grab the version number from a String.match() regular expression. A try-catch block is used to shorten the code, otherwise we'd need to test the array bounds for non-IE browsers.

Note: The user-agent can be spoofed or omitted, sometimes unintentionally if the user has set their browser to a "compatibility mode". Though this doesn't seem like much of an issue in practice.


Get IE Version without the User-Agent

var d = document, w = window;
var ie = ( !!w.MSInputMethodContext ? 11 : !d.all ? 99 : w.atob ? 10 : 
d.addEventListener ? 9 : d.querySelector ? 8 : w.XMLHttpRequest ? 7 : 
d.compatMode ? 6 : w.attachEvent ? 5 : 1 );

How it works: Each version of IE adds support for additional features not found in previous versions. So we can test for the features in a top-down manner. A ternary sequence is used here for brevity, though if-then and switch statements would work just as well. The variable ie is set to an integer 5-11, or 1 for older, or 99 for newer/non-IE. You can set it to 0 if you just want to test for IE 1-11 exactly.

Note: Object detection may break if your code is run on a page with third-party scripts that add polyfills for things like document.addEventListener. In such situations the user-agent is the best option.


Detect if the Browser is Modern

If you're only interested in whether or not a browser supports most HTML 5 and CSS 3 standards, you can reasonably assume that IE 8 and lower remain the primary problem apps. Testing for window.getComputedStyle will give you a fairly good mix of modern browsers, as well (IE 9, FF 4, Chrome 11, Safari 5, Opera 11.5). IE 9 greatly improves on standards support, but native CSS animation requires IE 10.

var isModernBrowser = ( !document.all || ( document.all && document.addEventListener ) ); 

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

How do I view 'git diff' output with my preferred diff tool/ viewer?

Building on VonC's answer to deal with file removals and additions, use the following commands and scripts:

> git config --global diff.tool winmerge
> git config --global difftool.winmerge.cmd "winmerge.sh \"$LOCAL\" \"$REMOTE\" \"$BASE\""
> git config --global difftool.prompt false

Which is the same as putting this in your global .gitconfig:

[diff]
    tool = winmerge
[difftool "winmerge"]
    cmd = winmerge.bat "$LOCAL" "$REMOTE" "$BASE"
[difftool]
    prompt = false

Then put the following in winmerge.shwhich must be on your path:

#!/bin/sh
NULL="/dev/null"
if [ "$2" = "$NULL" ] ; then
    echo "removed: $3"
elif [ "$1" = "$NULL" ] ; then
    echo "added: $3"
else
    echo "changed: $3"
    "C:/Program Files (x86)/WinMerge/WinMergeU.exe" -e -ub -dl "Base" -dr "Mine" "$1" "$2"
fi

converting Java bitmap to byte array

Try something like this:

Bitmap bmp = intent.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
bmp.recycle();

How to access host port from docker container

When you have two docker images "already" created and you want to put two containers to communicate with one-another.

For that, you can conveniently run each container with its own --name and use the --link flag to enable communication between them. You do not get this during docker build though.

When you are in a scenario like myself, and it is your

docker build -t "centos7/someApp" someApp/ 

That breaks when you try to

curl http://172.17.0.1:localPort/fileIWouldLikeToDownload.tar.gz > dump.tar.gz

and you get stuck on "curl/wget" returning no "route to host".

The reason is security that is set in place by docker that by default is banning communication from a container towards the host or other containers running on your host. This was quite surprising to me, I must say, you would expect the echosystem of docker machines running on a local machine just flawlessly can access each other without too much hurdle.

The explanation for this is described in detail in the following documentation.

http://www.dedoimedo.com/computers/docker-networking.html

Two quick workarounds are given that help you get moving by lowering down the network security.

The simplest alternative is just to turn the firewall off - or allow all. This means running the necessary command, which could be systemctl stop firewalld, iptables -F or equivalent.

Hope this information helps you.

Smart way to truncate long strings

Note that this only needs to be done for Firefox.

All other browsers support a CSS solution (see support table):

p {
    white-space: nowrap;
    width: 100%;                   /* IE6 needs any width */
    overflow: hidden;              /* "overflow" value must be different from  visible"*/ 
    -o-text-overflow: ellipsis;    /* Opera < 11*/
    text-overflow:    ellipsis;    /* IE, Safari (WebKit), Opera >= 11, FF > 6 */
}

The irony is I got that code snippet from Mozilla MDC.

Bash script - variable content as a command to run

Your are probably looking for eval $var.

S3 limit to objects in a bucket

According to Amazon:

Write, read, and delete objects containing from 0 bytes to 5 terabytes of data each. The number of objects you can store is unlimited.

Source: http://aws.amazon.com/s3/details/ as of Sep 3, 2015.

Deleting all pending tasks in celery / rabbitmq

From the docs:

$ celery -A proj purge

or

from proj.celery import app
app.control.purge()

(EDIT: Updated with current method.)

Paste MS Excel data to SQL Server

The simplest way is to create a computed column in XLS that would generate the syntax of the insert statement. Then copy these insert into a text file and then execute on the SQL. The other alternatives are to buy database connectivity add-on's for Excel and write VBA code to accomplish the same.

How do you get a timestamp in JavaScript?

Short & Snazzy:

+ new Date()

A unary operator like plus triggers the valueOf method in the Date object and it returns the timestamp (without any alteration).

Details:

On almost all current browsers you can use Date.now() to get the UTC timestamp in milliseconds; a notable exception to this is IE8 and earlier (see compatibility table).

You can easily make a shim for this, though:

if (!Date.now) {
    Date.now = function() { return new Date().getTime(); }
}

To get the timestamp in seconds, you can use:

Math.floor(Date.now() / 1000)

Or alternatively you could use:

Date.now() / 1000 | 0

Which should be slightly faster, but also less readable (also see this answer).

I would recommend using Date.now() (with compatibility shim). It's slightly better because it's shorter & doesn't create a new Date object. However, if you don't want a shim & maximum compatibility, you could use the "old" method to get the timestamp in milliseconds:

new Date().getTime()

Which you can then convert to seconds like this:

Math.round(new Date().getTime()/1000)

And you can also use the valueOf method which we showed above:

new Date().valueOf()

Timestamp in Milliseconds

_x000D_
_x000D_
var timeStampInMs = window.performance && window.performance.now && window.performance.timing && window.performance.timing.navigationStart ? window.performance.now() + window.performance.timing.navigationStart : Date.now();_x000D_
_x000D_
console.log(timeStampInMs, Date.now());
_x000D_
_x000D_
_x000D_

CMake not able to find OpenSSL library

Just in case...this works for me. Sorry for specific version of OpenSSL, but might be desirable.

# On macOS, search Homebrew for keg-only versions of OpenSSL
# equivalent of # -DOPENSSL_ROOT_DIR=/usr/local/opt/openssl/ -DOPENSSL_CRYPTO_LIBRARY=/usr/local/opt/openssl/lib/
if (CMAKE_HOST_SYSTEM_NAME MATCHES "Darwin")
    execute_process(
        COMMAND brew --prefix OpenSSL 
        RESULT_VARIABLE BREW_OPENSSL
        OUTPUT_VARIABLE BREW_OPENSSL_PREFIX
        OUTPUT_STRIP_TRAILING_WHITESPACE
    )
    if (BREW_OPENSSL EQUAL 0 AND EXISTS "${BREW_OPENSSL_PREFIX}")
        message(STATUS "Found OpenSSL keg installed by Homebrew at ${BREW_OPENSSL_PREFIX}")
        set(OPENSSL_ROOT_DIR "${BREW_OPENSSL_PREFIX}/")
        set(OPENSSL_INCLUDE_DIR "${BREW_OPENSSL_PREFIX}/include")
        set(OPENSSL_LIBRARIES "${BREW_OPENSSL_PREFIX}/lib")
        set(OPENSSL_CRYPTO_LIBRARY "${BREW_OPENSSL_PREFIX}/lib/libcrypto.dylib")
    endif()
endif()

...

find_package(OpenSSL REQUIRED)
if (OPENSSL_FOUND)
  # Add the include directories for compiling
  target_include_directories(${TARGET_SERVER} PUBLIC ${OPENSSL_INCLUDE_DIR})
  # Add the static lib for linking
  target_link_libraries(${TARGET_SERVER} OpenSSL::SSL OpenSSL::Crypto)
  message(STATUS "Found OpenSSL ${OPENSSL_VERSION}")
else()
  message(STATUS "OpenSSL Not Found")
endif()

RESTful web service - how to authenticate requests from other services?

5. Something else - there must be other solutions out there?

You're right, there is! And it is called JWT (JSON Web Tokens).

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA.

I highly recommend looking into JWTs. They're a much simpler solution to the problem when compared against alternative solutions.

https://jwt.io/introduction/

How do I access ViewBag from JS

if you are using razor engine template then do the following

in your view write :

<script> var myJsVariable = '@ViewBag.MyVariable' </script>

UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```

<head>
 <script>
   var AppConfig = @Html.Raw(Json.Encode(new {
    baseUrl: Url.Content("~"),
    fbApi: "get it from db",
    awsUrl: "get it from db"
   }));
 </script>
</head>

And you can use it in your JavaScript code as follow:

<script>
  myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
  alert(myProduct.fullUrl);
</script>

How to check if a column exists in a SQL Server table?

I'd prefer INFORMATION_SCHEMA.COLUMNS over a system table because Microsoft does not guarantee to preserve the system tables between versions. For example, dbo.syscolumns does still work in SQL 2008, but it's deprecated and could be removed at any time in future.

Removing Java 8 JDK from Mac

in Mac Remove Java Version using this 3 Commands

java -version

sudo rm -rf /Library/Java/*

sudo rm -rf /Library/PreferencePanes/Java*

sudo rm -rf /Library/Internet\ Plug-Ins/Java*

Run

java -version

//See java was successfully uninstalled.

java -version sudo rm -rf /Library/Java/* sudo rm -rf /Library/PreferencePanes/Java* sudo rm -rf /Library/Internet\ Plug-Ins/Java*

Run java -version

Install Java 8 Link

enter image description here

Download Package and click next next next

Javascript change date into format of (dd/mm/yyyy)

Some JavaScript engines can parse that format directly, which makes the task pretty easy:

_x000D_
_x000D_
function convertDate(inputFormat) {_x000D_
  function pad(s) { return (s < 10) ? '0' + s : s; }_x000D_
  var d = new Date(inputFormat)_x000D_
  return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/')_x000D_
}_x000D_
_x000D_
console.log(convertDate('Mon Nov 19 13:29:40 2012')) // => "19/11/2012"
_x000D_
_x000D_
_x000D_

ORA-01031: insufficient privileges when selecting view

As the table owner you need to grant SELECT access on the underlying tables to the user you are running the SELECT statement as.

grant SELECT on TABLE_NAME to READ_USERNAME;

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

What is the proper way to URL encode Unicode characters?

IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.

Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.

Blank HTML SELECT without blank item in dropdown list

For purely html @isherwood has a great solution. For jQuery, give your select drop down an ID then select it with jQuery:

<form>
  <select id="myDropDown">
    <option value="0">aaaa</option>
    <option value="1">bbbb</option>
  </select>
</form> 

Then use this jQuery to clear the drop down on page load:

$(document).ready(function() {
    $('#myDropDown').val(''); 
});

Or put it inside a function by itself:

$('#myDropDown').val(''); 

accomplishes what you're looking for and it is easy to put this in functions that may get called on your page if you need to blank out the drop down without reloading the page.

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

I had the same problem in my (YouTube player project)... and the following solved the problem for me:

  1. Add this code into your build.gradle (module: app) inside defaultConfing:

    defaultConfig {
        ....
        ....
        multiDexEnabled = true
    }
    
  2. Add this code into your build.gradle (module: app) inside dependencies:

    dependencies {
        compile 'com.android.support:multidex:1.0.1'
        .....
        .....
    }
    
  3. Open AndroidManifest.xml and within application:

    <application
        android:name="android.support.multidex.MultiDexApplication"
        .....
        .....
    </application>
    

    or if you have your App class, extend it from MultiDexApplication like:

    public class MyApp extends MultiDexApplication {
    .....
    

And finally, I think you should have Android Support Repository downloaded, in the Extras in SDK Manager.

Is a GUID unique 100% of the time?

GUID stands for Global Unique Identifier

In Brief: (the clue is in the name)

In Detail: GUIDs are designed to be unique; they are calculated using a random method based on the computers clock and computer itself, if you are creating many GUIDs at the same millisecond on the same machine it is possible they may match but for almost all normal operations they should be considered unique.

angularjs ng-style: background-image isn't working

The syntax is changed for Angular 2 and above:

[ngStyle]="{'background-image': 'url(path)'}"

JComboBox Selection Change Listener?

Code example of ItemListener implementation

class ItemChangeListener implements ItemListener{
    @Override
    public void itemStateChanged(ItemEvent event) {
       if (event.getStateChange() == ItemEvent.SELECTED) {
          Object item = event.getItem();
          // do something with object
       }
    }       
}

Now we will get only selected item.

Then just add listener to your JComboBox

addItemListener(new ItemChangeListener());

How to restart Activity in Android

Actually the following code is valid for API levels 5 and up, so if your target API is lower than this, you'll end up with something very similar to EboMike's code.

intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
overridePendingTransition(0, 0);

Difference between modes a, a+, w, w+, and r+ in built-in open function?

I hit upon this trying to figure out why you would use mode 'w+' versus 'w'. In the end, I just did some testing. I don't see much purpose for mode 'w+', as in both cases, the file is truncated to begin with. However, with the 'w+', you could read after writing by seeking back. If you tried any reading with 'w', it would raise an IOError. Reading without using seek with mode 'w+' isn't going to yield anything, since the file pointer will be after where you have written.

How to convert string to long

Use parseLong(), e.g.:

long lg = lg.parseLong("123456789123456789");

How to catch and print the full exception traceback without halting/exiting the program?

You want the traceback module. It will let you print stack dumps like Python normally does. In particular, the print_last function will print the last exception and a stack trace.

How to force open links in Chrome not download them?

To make certain file types OPEN on your computer, instead of Chrome Downloading...

You have to download the file type once, then right after that download, look at the status bar at the bottom of the browser. Click the arrow next to that file and choose "always open files of this type". DONE.

Now the file type will always OPEN using your default program.

To reset this feature, go to Settings / Advance Settings and under the "Download.." section, there's a button to reset 'all' Auto Downloads

Hope this helps.. :-)

Visual Instructions found here:

http://www.presentermedia.com/blog/2013/10/my-file-automatically-opens-instead-of-saving-with-chrome/

How does #include <bits/stdc++.h> work in C++?

It is basically a header file that also includes every standard library and STL include file. The only purpose I can see for it would be for testing and education.

Se e.g. GCC 4.8.0 /bits/stdc++.h source.

Using it would include a lot of unnecessary stuff and increases compilation time.

Edit: As Neil says, it's an implementation for precompiled headers. If you set it up for precompilation correctly it could, in fact, speed up compilation time depending on your project. (https://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html)

I would, however, suggest that you take time to learn about each of the sl/stl headers and include them separately instead, and not use "super headers" except for precompilation purposes.

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

Mi helped: windows defender settings >> device security >> core insulation (details) >> Memory integrity >> Disable (OFF) SYSTEM RESTART !

How to convert file to base64 in JavaScript?

Modern ES6 way (async/await)

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();

UPD:

If you want to catch errors

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   const result = await toBase64(file).catch(e => Error(e));
   if(result instanceof Error) {
      console.log('Error: ', result.message);
      return;
   }
   //...
}

Creating a PDF from a RDLC Report in the Background

The below code work fine with me of sure thanks for the above comments. You can add report viewer and change the visible=false and use the below code on submit button:

protected void Button1_Click(object sender, EventArgs e)
{
    Warning[] warnings;
    string[] streamIds;
    string mimeType = string.Empty;
    string encoding = string.Empty;
    string extension = string.Empty;
    string HIJRA_TODAY = "01/10/1435";
    ReportParameter[] param = new ReportParameter[3];
    param[0] = new ReportParameter("CUSTOMER_NUM", CUSTOMER_NUMTBX.Text);
    param[1] = new ReportParameter("REF_CD", REF_CDTB.Text);
    param[2] = new ReportParameter("HIJRA_TODAY", HIJRA_TODAY);

    byte[] bytes = ReportViewer1.LocalReport.Render(
        "PDF", 
        null, 
        out mimeType, 
        out encoding, 
        out extension, 
        out streamIds, 
        out warnings);

    Response.Buffer = true;
    Response.Clear();
    Response.ContentType = mimeType;
    Response.AddHeader(
        "content-disposition", 
        "attachment; filename= filename" + "." + extension);
    Response.OutputStream.Write(bytes, 0, bytes.Length); // create the file  
    Response.Flush(); // send it to the client to download  
    Response.End();
}    

Can "git pull --all" update all my local branches?

To complete the answer by Matt Connolly, this is a safer way to update local branch references that can be fast-forwarded, without checking out the branch. It does not update branches that cannot be fast-forwarded (i.e. that have diverged), and it does not update the branch that is currently checked out (because then the working copy should be updated as well).

git fetch

head="$(git symbolic-ref HEAD)"
git for-each-ref --format="%(refname) %(upstream)" refs/heads | while read ref up; do
    if [ -n "$up" -a "$ref" != "$head" ]; then
        mine="$(git rev-parse "$ref")"
        theirs="$(git rev-parse "$up")"
        base="$(git merge-base "$ref" "$up")"
        if [ "$mine" != "$theirs" -a "$mine" == "$base" ]; then
            git update-ref "$ref" "$theirs"
        fi
    fi
done

Xcode 4 - build output directory

Another thing to check before you start playing with Xcode preferences is:

Select your target and go to Build Settings > Packaging > Wrapper Extension

The value there should be: app

If not double click it and type "app" without the qoutes.

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

Try connecting to a vpn, if possible. That was the reason I was facing problem. Tip: if you're using an ec2 machine, try rebooting it. This worked for me the other day :)

How to serialize Object to JSON?

The "reference" Java implementation by Sean Leary is here on github. Make sure to have the latest version - different libraries pull in versions buggy old versions from 2009.

Java EE 7 has a JSON API in javax.json, see the Javadoc. From what I can tell, it doesn't have a simple method to marshall any object to JSON, you need to construct a JsonObject or a JsonArray.

import javax.json.*;

JsonObject value = Json.createObjectBuilder()
 .add("firstName", "John")
 .add("lastName", "Smith")
 .add("age", 25)
 .add("address", Json.createObjectBuilder()
     .add("streetAddress", "21 2nd Street")
     .add("city", "New York")
     .add("state", "NY")
     .add("postalCode", "10021"))
 .add("phoneNumber", Json.createArrayBuilder()
     .add(Json.createObjectBuilder()
         .add("type", "home")
         .add("number", "212 555-1234"))
     .add(Json.createObjectBuilder()
         .add("type", "fax")
         .add("number", "646 555-4567")))
 .build();

JsonWriter jsonWriter = Json.createWriter(...);
jsonWriter.writeObject(value);
jsonWriter.close();

But I assume the other libraries like GSON will have adapters to create objects implementing those interfaces.

HTML input fields does not get focus when clicked

I had the same issue and the fix was to remove the placeholders and I changed the design of the form to use labels instead of placeholders...

Cannot create SSPI context

It sounds like your PC hasn't contacted an authenticating domain controller for a little while. (I used to have this happen on my laptop a few times.)

It can also happen if your password expires.

How to Query an NTP Server using C#?

Since the old accepted answer got deleted (It was a link to a Google code search results that no longer exist), I figured I could answer this question for future reference :

public static DateTime GetNetworkTime()
{
    //default Windows time server
    const string ntpServer = "time.windows.com";

    // NTP message size - 16 bytes of the digest (RFC 2030)
    var ntpData = new byte[48];

    //Setting the Leap Indicator, Version Number and Mode values
    ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)

    var addresses = Dns.GetHostEntry(ntpServer).AddressList;

    //The UDP port number assigned to NTP is 123
    var ipEndPoint = new IPEndPoint(addresses[0], 123);
    //NTP uses UDP

    using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
    {
        socket.Connect(ipEndPoint);

        //Stops code hang if NTP is blocked
        socket.ReceiveTimeout = 3000;     

        socket.Send(ntpData);
        socket.Receive(ntpData);
        socket.Close();
    }

    //Offset to get to the "Transmit Timestamp" field (time at which the reply 
    //departed the server for the client, in 64-bit timestamp format."
    const byte serverReplyTime = 40;

    //Get the seconds part
    ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);

    //Get the seconds fraction
    ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);

    //Convert From big-endian to little-endian
    intPart = SwapEndianness(intPart);
    fractPart = SwapEndianness(fractPart);

    var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);

    //**UTC** time
    var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);

    return networkDateTime.ToLocalTime();
}

// stackoverflow.com/a/3294698/162671
static uint SwapEndianness(ulong x)
{
    return (uint) (((x & 0x000000ff) << 24) +
                   ((x & 0x0000ff00) << 8) +
                   ((x & 0x00ff0000) >> 8) +
                   ((x & 0xff000000) >> 24));
}

Note: You will have to add the following namespaces

using System.Net;
using System.Net.Sockets;

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Have you seen CodeIgniter's Language library?

The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.

In your CodeIgniter system folder you'll find one called language containing sets of language files. You can create your own language files as needed in order to display error and other messages in other languages.

Language files are typically stored in your system/language directory. Alternately you can create a folder called language inside your application folder and store them there. CodeIgniter will look first in your application/language directory. If the directory does not exist or the specified language is not located there CI will instead look in your global system/language folder.

In your case...

  • you need to create a polish_lang.php and english_lang.php inside application/language/polish
  • then create your keys inside that file (e.g. $lang['hello'] = "Witaj";
  • then load it in your controller like $this->lang->load('polish_lang', 'polish');
  • then fetch the line like $this->lang->line('hello'); Just store the return value of this function in a variable so you can use it in your view.

Repeat the steps for the english language and all other languages you need.

CSS Display an Image Resized and Cropped

You can put the img tag in a div tag and do both, but I would recommend against scaling images in the browser. It does a lousy job most of the time because browsers have very simplistic scaling algorithms. Better to do your scaling in Photoshop or ImageMagick first, then serve it up to the client nice and pretty.

Min / Max Validator in Angular 2 Final

Angular 6 supports min & max validators: https://angular.io/api/forms/Validators

You can use those for static & dynamic values.

Static:

<input min="0" max="5">

Dynamic:

<input [min]="someMinValue" [max]="someMaxValue">

Head and tail in one line

Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]

If you need it to be exception-proof (i.e. supporting empty list), then add:

t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]

If you want to do it without the semicolon, use:

h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]

jquery how to catch enter key and change event to tab

These solutions didn't work with my datagrid. I was hoping they would. I don't really need Tab or Enter to move to the next input, column, row or whatever. I just need Enter to trigger .focusout or .change and my datagrid updates the database. So I added the "enter" class to the relevant text inputs and this did the trick for me:

$(function() {
   if ($.browser.mozilla) {
        $(".enter").keypress(checkForEnter);
    } else {
        $(".enter").keydown(checkForEnter);
    }
});

function checkForEnter(event) {
    if (event.keyCode == 13) {
        $(".enter").blur();
    }
}

How can I export Excel files using JavaScript?

There is an interesting project on github called Excel Builder (.js) that offers a client-side way of downloading Excel xlsx files and includes options for formatting the Excel spreadsheet.
https://github.com/stephenliberty/excel-builder.js

You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful.

Another github project with less Excel options but less worries about Excel compatibility issues can be found here: ExcellentExport.js
https://github.com/jmaister/excellentexport

If you are using AngularJS, there is ng-csv:
a "Simple directive that turns arrays and objects into downloadable CSV files".

Show / hide div on click with CSS

CSS does not have an onlclick event handler. You have to use Javascript.

See more info here on CSS Pseudo-classes: http://www.w3schools.com/css/css_pseudo_classes.asp

a:link {color:#FF0000;}    /* unvisited link - link is untouched */
a:visited {color:#00FF00;} /* visited link - user has already been to this page */
a:hover {color:#FF00FF;}   /* mouse over link - user is hovering over the link with the mouse or has selected it with the keyboard */
a:active {color:#0000FF;}  /* selected link - the user has clicked the link and the browser is loading the new page */

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

Recently, I'm trying upgrade EF5 to EF6 sample project . The table of sample project has decimal(5,2) type columns. Database migration successfully completed. But, initial data seed generated exception.

Model :

    public partial class Weather
    {
    ...
    public decimal TMax {get;set;}
    public decimal TMin {get;set;}
    ...
    }

Wrong Configuration :

public partial class WeatherMap : EntityTypeConfiguration<Weather>
{

    public WeatherMap()
    {
        ...
        this.Property(t => t.TMax).HasColumnName("TMax");
        this.Property(t => t.TMin).HasColumnName("TMin");
        ...
    }
}

Data :

    internal static Weather[] data = new Weather[365]
    {
      new Weather() {...,TMax = 3.30M,TMin = -12.00M,...},
      new Weather() {...,TMax = 5.20M,TMin = -10.00M,...},
      new Weather() {...,TMax = 3.20M,TMin = -8.00M,...},
      new Weather() {...,TMax = 11.00M,TMin = -7.00M,...},
      new Weather() {...,TMax = 9.00M,TMin = 0.00M,...},
    };

I found the problem, Seeding data has precision values, but configuration does not have precision and scale parameters. TMax and TMin fields defined with decimal(10,0) in sample table.

Correct Configuration :

public partial class WeatherMap : EntityTypeConfiguration<Weather>
{

    public WeatherMap()
    {
        ...
        this.Property(t => t.TMax).HasPrecision(5,2).HasColumnName("TMax");
        this.Property(t => t.TMin).HasPrecision(5,2).HasColumnName("TMin");
        ...
    }
}

My sample project run with: MySql 5.6.14, Devart.Data.MySql, MVC4, .Net 4.5.1, EF6.01

Best regards.

incompatible character encodings: ASCII-8BIT and UTF-8

I had a similar issue on a custom CoffeeScript file. I solved it by changing the endline encoding from "Unix/Linux" to "Mac OS Classic"

How to get milliseconds from LocalDateTime in Java 8

If you have a Java 8 Clock, then you can use clock.millis() (although it recommends you use clock.instant() to get a Java 8 Instant, as it's more accurate).

Why would you use a Java 8 clock? So in your DI framework you can create a Clock bean:

@Bean
public Clock getClock() {
    return Clock.systemUTC();
}

and then in your tests you can easily Mock it:

@MockBean private Clock clock;

or you can have a different bean:

@Bean
public Clock getClock() {
    return Clock.fixed(instant, zone);
}

which helps with tests that assert dates and times immeasurably.

Dynamically Add C# Properties at Runtime

Thanks @Clint for the great answer:

Just wanted to highlight how easy it was to solve this using the Expando Object:

    var dynamicObject = new ExpandoObject() as IDictionary<string, Object>;
    foreach (var property in properties) {
        dynamicObject.Add(property.Key,property.Value);
    }

Read connection string from web.config

In VB : This should work

ConfigurationManager.ConnectionStrings("SQLServer").ConnectionString

In C# it would be (as per comment of Ala)

ConfigurationManager.ConnectionStrings["SQLServer"].ConnectionString

How to change folder with git bash?

pwd: to check where you are (If necessary)

cd: change directory

In your case if I understand you, you need:

cd c/project

Using Enum values as String literals

Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?

String name = Modes.mode1.name();
Modes mode = Modes.valueOf(name);

There's also a static valueOf(Class, String) on Enum itself, so you could also use

Modes mode = Enum.valueOf(Modes.class, name);

ImportError: Cannot import name X

In my case, I was working in a Jupyter notebook and this was happening due the import already being cached from when I had defined the class/function inside my working file.

I restarted my Jupyter kernel and the error disappeared.

Git error on commit after merge - fatal: cannot do a partial commit during a merge

You probably got a conflict in something that you haven't staged for commit. git won't let you commit things independently (because it's all part of the merge, I guess), so you need to git add that file and then git commit -m "Merge conflict resolution". The -i flag for git commit does the add for you.

How to change color in circular progress bar?

For API 21 and Higher. Simply set the indeterminateTint property. Like:

android:indeterminateTint="@android:color/holo_orange_dark"

To support pre-API 21 devices:

mProgressSpin.getIndeterminateDrawable()
                .setColorFilter(ContextCompat.getColor(this, R.color.colorPrimary), PorterDuff.Mode.SRC_IN );

continuing execution after an exception is thrown in java

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/

Are Git forks actually Git clones?

There is a misunderstanding here with respect to what a "fork" is. A fork is in fact nothing more than a set of per-user branches. When you push to a fork you actually do push to the original repository, because that is the ONLY repository.

You can try this out by pushing to a fork, noting the commit and then going to the original repository and using the commit ID, you'll see that the commit is "in" the original repository.

This makes a lot of sense, but it is far from obvious (I only discovered this accidentally recently).

When John forks repository SuperProject what seems to actually happen is that all branches in the source repository are replicated with a name like "John.master", "John.new_gui_project", etc.

GitHub "hides" the "John." from us and gives us the illusion we have our own "copy" of the repository on GitHub, but we don't and nor is one even needed.

So my fork's branch "master" is actually named "Korporal.master", but the GitHub UI never reveals this, showing me only "master".

This is pretty much what I think goes on under the hood anyway based on stuff I've been doing recently and when you ponder it, is very good design.

For this reason I think it would be very easy for Microsoft to implement Git forks in their Visual Studio Team Services offering.

Explaining Python's '__enter__' and '__exit__'

If you know what context managers are then you need nothing more to understand __enter__ and __exit__ magic methods. Lets see a very simple example.

In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.

fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
    for line in fp:
        print(line)
finally:
    fp.close()

Now I am opening same file with with statement:

with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
    for line in fp:
        print(line) 

If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling print(fp.closed) attribute -- which returns True.

This is because the file objects (fp in my example) returned by open function has two built-in methods __enter__ and __exit__. It is also known as context manager. __enter__ method is called at the start of with block and __exit__ method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have __enter__ and __exit__ methods. A class which implement both methods is known as context manager class.

Now lets define our own context manager class.

 class Log:
    def __init__(self,filename):
        self.filename=filename
        self.fp=None    
    def logging(self,text):
        self.fp.write(text+'\n')
    def __enter__(self):
        print("__enter__")
        self.fp=open(self.filename,"a+")
        return self    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        self.fp.close()

with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
    print("Main")
    logfile.logging("Test1")
    logfile.logging("Test2")

I hope now you have basic understanding of both __enter__ and __exit__ magic methods.

Open URL in new window with JavaScript

Don't confuse, if you won't give any strWindowFeatures then it will open in a new tab.

window.open('https://play.google.com/store/apps/details?id=com.drishya');

How to select top n rows from a datatable/dataview in ASP.NET

In framework 3.5, dt.Rows.Cast<System.Data.DataRow>().Take(n)

Otherwise the way you mentioned

A server with the specified hostname could not be found

I faced this issue when we changed from one domain to another for API service.

Restarting the network router/modem fixed this issue.

switch() statement usage

In short, yes. But there are times when you might favor one vs. the other. Google "case switch vs. if else". There are some discussions already on SO too. Also, here is a good video that talks about it in the context of MATLAB:

http://blogs.mathworks.com/pick/2008/01/02/matlab-basics-switch-case-vs-if-elseif/

Personally, when I have 3 or more cases, I usually just go with case/switch.

Hide div if screen is smaller than a certain width

I have the almost the same situation as yours; that if the screen width is less than the my specified width it should hide the div. This is the jquery code I used that worked for me.

$(window).resize(function() {

  if ($(this).width() < 1024) {

    $('.divIWantedToHide').hide();

  } else {

    $('.divIWantedToHide').show();

    }

});

Simple JavaScript problem: onClick confirm not preventing default action

try this:

OnClientClick='return (confirm("Are you sure you want to delete this comment?"));'

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Error in your question is raised when you try something like following:

>>> a_dictionary = {}
>>> a_dictionary.update([[1]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 1; 2 is required

It's hard to tell where is the cause in your code unless you show your code, full traceback.

What does %5B and %5D in POST requests stand for?

To take a quick look, you can percent-en/decode using this online tool.

How do I set a column value to NULL in SQL Server Management Studio?

If you are using the table interface you can type in NULL (all caps)

otherwise you can run an update statement where you could:

Update table set ColumnName = NULL where [Filter for record here]

WPF ListView - detect when selected item is clicked

You can handle the ListView's PreviewMouseLeftButtonUp event. The reason not to handle the PreviewMouseLeftButtonDown event is that, by the time when you handle the event, the ListView's SelectedItem may still be null.

XAML:

<ListView ... PreviewMouseLeftButtonUp="listView_Click"> ...

Code behind:

private void listView_Click(object sender, RoutedEventArgs e)
{
    var item = (sender as ListView).SelectedItem;
    if (item != null)
    {
        ...
    }
}

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

I think you could have used:
value.ToString("F"+NumberOfDecimals)

value = 10,502
value.ToString("F2") //10,50
value = 10,5 
value.ToString("F2") //10,50

Here is a detailed description of Numeric Format Strings

How permission can be checked at runtime without throwing SecurityException?

Sharing my methods in case someone needs them:

 /** Determines if the context calling has the required permission
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermission(Context context, String permission) {

    int res = context.checkCallingOrSelfPermission(permission);

    Log.v(TAG, "permission: " + permission + " = \t\t" + 
    (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));

    return res == PackageManager.PERMISSION_GRANTED;

}

/** Determines if the context calling has the required permissions
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermissions(Context context, String... permissions) {

    boolean hasAllPermissions = true;

    for(String permission : permissions) {
        //you can return false instead of assigning, but by assigning you can log all permission values
        if (! hasPermission(context, permission)) {hasAllPermissions = false; }
    }

    return hasAllPermissions;

}

And to call it:

boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {
                android.Manifest.permission.ACCESS_WIFI_STATE,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.ACCESS_NETWORK_STATE,
                android.Manifest.permission.INTERNET,
        });

Jackson how to transform JsonNode to ArrayNode without casting?

Is there a method equivalent to getJSONArray in org.json so that I have proper error handling in case it isn't an array?

It depends on your input; i.e. the stuff you fetch from the URL. If the value of the "datasets" attribute is an associative array rather than a plain array, you will get a ClassCastException.

But then again, the correctness of your old version also depends on the input. In the situation where your new version throws a ClassCastException, the old version will throw JSONException. Reference: http://www.json.org/javadoc/org/json/JSONObject.html#getJSONArray(java.lang.String)

How / can I display a console window in Intellij IDEA?

More IntelliJ 13+ Shortcuts for Terminal

Mac OS X:

alt ?F12

cmd ?shift ?A then type Terminal then hit Enter

shift ?shift ?shift ?shift ? then type Terminal then hit Enter

Windows:

altF12 press Enter

ctrlshift ?A start typing Terminal then hit Enter

shift ?shift ? then type Terminal then hit Enter

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

use set serveroutput on;

for example:

set serveroutput on;

DECLARE
x NUMBER;
BEGIN
x := 72600;
dbms_output.put_line('The variable X = '); dbms_output.put_line(x);
END;

Use of "instanceof" in Java

instanceof is used to check if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

Read more from the Oracle language definition here.

Where does one get the "sys/socket.h" header/source file?

Given that Windows has no sys/socket.h, you might consider just doing something like this:

#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif

I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a

#ifdef __WIN32__
   WORD versionWanted = MAKEWORD(1, 1);
   WSADATA wsaData;
   WSAStartup(versionWanted, &wsaData);
#endif

at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process.

Installing SetupTools on 64-bit Windows

Get the file register.py from this gist. Save it on your C drive or D drive, go to CMD to run it with:

'python register.py'

Then you will be able to install it.

Angular 2: import external js file into component

Instead of including your js file extension in index.html, you can include it in .angular-cli-json file.

These are the steps I followed to get this working:

  1. First include your external js file in assets/js
  2. In .angular-cli.json - add the file path under scripts: [../app/assets/js/test.js]
  3. In the component where you want to use the functions of the js file.

Declare at the top where you want to import the files as

declare const Test:any;

After this you can access its functions as for example Test.add()

How can I get the DateTime for the start of the week?

Step 1: Create a static class

  public static class TIMEE
{
    public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(-1 * diff).Date;
    }
    public static DateTime EndOfWeek(this DateTime dt, DayOfWeek startOfWeek)
    {
        int diff = (7 - (dt.DayOfWeek - startOfWeek)) % 7;
        return dt.AddDays(1 * diff).Date;
    }
}

Step2: Use this class to get both start and end day of the week

 DateTime dt =TIMEE.StartOfWeek(DateTime.Now ,DayOfWeek.Monday);
        DateTime dt1 = TIMEE.EndOfWeek(DateTime.Now, DayOfWeek.Sunday);

Python: Continuing to next iteration in outer loop

I think one of the easiest ways to achieve this is to replace "continue" with "break" statement,i.e.

for ii in range(200):
 for jj in range(200, 400):
    ...block0...
    if something:
        break
 ...block1...       

For example, here is the easy code to see how exactly it goes on:

for i in range(10):
    print("doing outer loop")
    print("i=",i)
    for p in range(10):
        print("doing inner loop")
        print("p=",p)
        if p==3:
            print("breaking from inner loop")
            break
    print("doing some code in outer loop")

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

No, CASE is a function, and can only return a single value. I think you are going to have to duplicate your CASE logic.

The other option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.

How to get numeric value from a prompt box?

var xInt = parseInt(x)

This will return either the integer value, or NaN.

Read more about parseInt here.

How do I delete all messages from a single queue using the CLI?

To purge queue you can use following command (more information in API doc):

curl -i -u guest:guest -XDELETE http://localhost:15672/api/queues/vhost_name/queue_name/contents

What does auto do in margin:0 auto?

From the CSS specification on Calculating widths and margins for Block-level, non-replaced elements in normal flow:

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

Google maps Marker Label with multiple characters

For anyone trying to

...in 2019, it's worth noting some of the code referenced here no longer exists (officially). Google discontinued support for the "MarkerWithLabel" project a long time ago. It was originally hosted on Google code here, now it's unofficially hosted on Github here.

But there is another project Google maintained until 2016, called "MapLabel"s. That approach is different (and arguably better). You create a separate map label object with the same origin as the marker instead of adding a mapLabel option to the marker itself. You can make a marker with label with multiple characters using js-marker-label.

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

Best /Fastest way to read an Excel Sheet into a DataTable?

The below code is tested by myself and is very simple, understandable, usable and fast. This code, initially takes all sheet names, then puts all tables of that excel file in a DataSet.

    public static DataSet ToDataSet(string exceladdress, int startRecord = 0, int maxRecord = -1, string condition = "")
    {
        DataSet result = new DataSet();
        using (OleDbConnection connection = new OleDbConnection(
                (exceladdress.TrimEnd().ToLower().EndsWith("x"))
                ? "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + exceladdress + "';" + "Extended Properties='Excel 12.0 Xml;HDR=YES;'"
                : "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + exceladdress + "';Extended Properties=Excel 8.0;"))
            try
            {
                connection.Open();
                DataTable schema = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                foreach (DataRow drSheet in schema.Rows)
                    if (drSheet["TABLE_NAME"].ToString().Contains("$"))
                    {
                        string s = drSheet["TABLE_NAME"].ToString();
                        if (s.StartsWith("'")) s = s.Substring(1, s.Length - 2);
                        System.Data.OleDb.OleDbDataAdapter command =
                            new System.Data.OleDb.OleDbDataAdapter(string.Join("", "SELECT * FROM [", s, "] ", condition), connection);
                        DataTable dt = new DataTable();
                        if (maxRecord > -1 && startRecord > -1) command.Fill(startRecord, maxRecord, dt);
                        else command.Fill(dt);
                        result.Tables.Add(dt);
                    }
                return result;
            }
            catch (Exception ex) { return null; }
            finally { connection.Close(); }
    }

Enjoy...

Which ChromeDriver version is compatible with which Chrome Browser version?

I found, that chrome and chromedriver versions support policy has changed recently.

As stated on downloads page:

There is general guide to select version of crhomedriver for specific chrome version: https://sites.google.com/a/chromium.org/chromedriver/downloads/version-selection

Here is excerpt:

  • First, find out which version of Chrome you are using. Let's say you have Chrome 72.0.3626.81.
  • Take the Chrome version number, remove the last part, and append the result to URL "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_". For example, with Chrome version 72.0.3626.81, you'd get a URL "https://chromedriver.storage.googleapis.com/LATEST_RELEASE_72.0.3626".
  • Use the URL created in the last step to retrieve a small file containing the version of ChromeDriver to use. For example, the above URL will get your a file containing "72.0.3626.69". (The actual number may change in the future, of course.)
  • Use the version number retrieved from the previous step to construct the URL to download ChromeDriver. With version 72.0.3626.69, the URL would be "https://chromedriver.storage.googleapis.com/index.html?path=72.0.3626.69/".
  • After the initial download, it is recommended that you occasionally go through the above process again to see if there are any bug fix releases.

Note, that this version selection algorithm can be easily automated. For example, simple powershell script in another answer has automated chromedriver updating on windows platform.

Mongoose delete array element in document and save

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

How to set default font family in React Native?

For React Native 0.56.0+ check if defaultProps is defined first:

Text.defaultProps = Text.defaultProps || {}

Then add:

Text.defaultProps.style =  { fontFamily: 'some_font' }

Add the above in the constructor of the App.js file (or any root component you have).

In order to override the style you can create a style object and spread it then add your additional style (e.g { ...baseStyle, fontSize: 16 })

C# - Multiple generic types in one list

Following leppie's answer, why not make MetaData an interface:

public interface IMetaData { }

public class Metadata<DataType> : IMetaData where DataType : struct
{
    private DataType mDataType;
}

How do I do a Date comparison in Javascript?

new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()