Programs & Examples On #Reverse proxy

A reverse proxy server usually refers to an HTTP accelerator or load-balancer which proxies requests on behalf of the actual clients to one or more backend HTTP servers.

Configure Nginx with proxy_pass

Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.

The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.

Nginx reverse proxy causing 504 Gateway Timeout

You can also face this situation if your upstream server uses a domain name, and its IP address changes (e.g.: your upstream points to an AWS Elastic Load Balancer)

The problem is that nginx will resolve the IP address once, and keep it cached for subsequent requests until the configuration is reloaded.

You can tell nginx to use a name server to re-resolve the domain once the cached entry expires:

location /mylocation {
    # use google dns to resolve host after IP cached expires
    resolver 8.8.8.8;
    set $upstream_endpoint http://your.backend.server/;
    proxy_pass $upstream_endpoint;
}

The docs on proxy_pass explain why this trick works:

Parameter value can contain variables. In this case, if an address is specified as a domain name, the name is searched among the described server groups, and, if not found, is determined using a resolver.

Kudos to "Nginx with dynamic upstreams" (tenzer.dk) for the detailed explanation, which also contains some relevant information on a caveat of this approach regarding forwarded URIs.

nginx - read custom header from upstream server

$http_name_of_the_header_key

i.e if you have origin = domain.com in header, you can use $http_origin to get "domain.com"

In nginx does support arbitrary request header field. In the above example last part of a variable name is the field name converted to lower case with dashes replaced by underscores

Reference doc here: http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_

For your example the variable would be $http_my_custom_header.

What's the difference between a proxy server and a reverse proxy server?

If no proxy

To see from the client side and server side are the same:

Client -> Server

Proxy

From the client side:

Client -> proxy -> Server

From the server side:

Client -> Server

Reverse proxy

From the client side:

Client -> Server

From the server side:

Client -> proxy -> Server

So I think if it set up by a client user,it is called a proxy; if it set up by a server manager it is a reverse proxy.

Because the purposes and reasons for setting it up are different, they deal with data in different ways and use different software.

   User side          |      Server side
client  <->  proxy  <-->  reverse_proxy <-> real server

Error during SSL Handshake with remote server

Faced the same problem as OP:

  • Tomcat returned response when accessing directly via SOAP UI
  • Didn't load html files
  • When used Apache properties mentioned by the previous answer, web-page appeared but AngularJS couldn't get HTTP response

Tomcat SSL certificate was expired while a browser showed it as secure - Apache certificate was far from expiration. Updating Tomcat KeyStore file solved the problem.

From inside of a Docker container, how do I connect to the localhost of the machine?

Edit: I ended up prototyping out the concept on GitHub. Check out: https://github.com/sivabudh/system-in-a-box


First, my answer is geared towards 2 groups of people: those who use a Mac, and those who use Linux.

The host network mode doesn't work on a Mac. You have to use an IP alias, see: https://stackoverflow.com/a/43541681/2713729

What is a host network mode? See: https://docs.docker.com/engine/reference/run/#/network-settings

Secondly, for those of you who are using Linux (my direct experience was with Ubuntu 14.04 LTS and I'm upgrading to 16.04 LTS in production soon), yes, you can make the service running inside a Docker container connect to localhost services running on the Docker host (eg. your laptop).

How?

The key is when you run the Docker container, you have to run it with the host mode. The command looks like this:

docker run --network="host" -id <Docker image ID>

When you do an ifconfig (you will need to apt-get install net-tools your container for ifconfig to be callable) inside your container, you will see that the network interfaces are the same as the one on Docker host (eg. your laptop).

It's important to note that I'm a Mac user, but I run Ubuntu under Parallels, so using a Mac is not a disadvantage. ;-)

And this is how you connect NGINX container to the MySQL running on a localhost.

Proxy with express.js

request has been deprecated as of February 2020, I'll leave the answer below for historical reasons, but please consider moving to an alternative listed in this issue.

Archive

I did something similar but I used request instead:

var request = require('request');
app.get('/', function(req,res) {
  //modify the url in any way you want
  var newurl = 'http://google.com/';
  request(newurl).pipe(res);
});

I hope this helps, took me a while to realize that I could do this :)

Get the index of a certain value in an array in PHP

array_search should work fine, just tested this and it returns the keys as expected:

$list = array('string1', 'string2', 'string3');
echo "Key = ".array_search('string1', $list);
echo " Key = ".array_search('string2', $list);
echo " Key = ".array_search('string3', $list);

Or for the index, you could use

$list = array('string1', 'string2', 'string3');
echo "Index = ".array_search('string1', array_merge($list));
echo " Index = ".array_search('string2', array_merge($list));
echo " Index = ".array_search('string3', array_merge($list));

Apache redirect to another port

This might be an old question, but here's what I did:

In a .conf file loaded by apache:

<VirtualHost *:80>
  ServerName something.com
  ProxyPass / http://localhost:8080/
</VirtualHost>

Explanation: Listen on all requests to the local machine's port 80. If I requested "http://something.com/somethingorother", forward that request to "http://localhost:8080/somethingorother". This should work for an external visitor because, according to the docs, it maps the remote request to the local server's space.

I'm running Apache 2.4.6-2ubuntu2.2, so I'm not sure how the "-2ubuntu2.2" affects the wider applicability of this answer.

After you make these changes, add the needed modules and restart apache

sudo a2enmod proxy && sudo a2enmod proxy_http && sudo service apache2 restart

Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

Good tutorial for using HTML5 History API (Pushstate?)

The HTML5 history spec is quirky.

history.pushState() doesn't dispatch a popstate event or load a new page by itself. It was only meant to push state into history. This is an "undo" feature for single page applications. You have to manually dispatch a popstate event or use history.go() to navigate to the new state. The idea is that a router can listen to popstate events and do the navigation for you.

Some things to note:

  • history.pushState() and history.replaceState() don't dispatch popstate events.
  • history.back(), history.forward(), and the browser's back and forward buttons do dispatch popstate events.
  • history.go() and history.go(0) do a full page reload and don't dispatch popstate events.
  • history.go(-1) (back 1 page) and history.go(1) (forward 1 page) do dispatch popstate events.

You can use the history API like this to push a new state AND dispatch a popstate event.

history.pushState({message:'New State!'}, 'New Title', '/link'); window.dispatchEvent(new PopStateEvent('popstate', { bubbles: false, cancelable: false, state: history.state }));

Then listen for popstate events with a router.

How do I get rid of the "cannot empty the clipboard" error?

I have seen various answers which say when I uninstalled this or that it worked. I think that the uninstall is probably just sorting out an issue in the registry, rather it being an issue with the particular application that is being uninstalled.

I have also seen cases of people saying kill the RDP task but I don't have that and I still have the error.

I have seen cases of people saying clear the clipboard in Excel, but that doesn't work for me - nor does changing the settings in the Clipboard.

I believe that the issue is that an application has a lock on the clipboard and that application is not releasing it. The clipboard is a shared resource, so that implies that each application has to get a lock on it before changing it and then release the lock once it has completed the change, however, it looks like sometimes the lock is not released.

I found that the following cured it. Close down all MS applications including IE and Outlook. Check Task Manager processes to make sure that they are all gone.

Then restart the application where you had the Copy and Paste issue and it will probably then work.

Regards

Paul Simon

How to pass the values from one jsp page to another jsp without submit button?

Note: Give accurate path details for Form1.jsp in Test.jsp 1. Test.jsp and 2.Form1.jsp

Test.jsp

<body>
<form method ="get" onsubmit="Form1.jsp">
<input type="text" name="uname">
<input type="submit" value="go" ><br/>
</form>
</body>

Form1.jsp

</head>
<body>
<% String name=request.getParameter("uname"); out.print("welcome "+name); %>  
</body>

Powershell: count members of a AD group

easy way to do it: To get the actual user count:

$ADInfo = Get-ADGroup -Identity '<groupname>' -Properties Members
$AdInfo.Members.Count

and you get the count easily, it is pretty fast as well for 20k+ users too

Converting integer to string in Python

>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5

Capturing URL parameters in request.GET

This is another alternate solution that can be implemented:

In the URL configuration:

urlpatterns = [path('runreport/<str:queryparams>', views.get)]

In the views:

list2 = queryparams.split("&")

Create multiple threads and wait all of them to complete

In my case, I could not instantiate my objects on the the thread pool with Task.Run() or Task.Factory.StartNew(). They would not synchronize my long running delegates correctly.

I needed the delegates to run asynchronously, pausing my main thread for their collective completion. The Thread.Join() would not work since I wanted to wait for collective completion in the middle of the parent thread, not at the end.

With the Task.Run() or Task.Factory.StartNew(), either all the child threads blocked each other or the parent thread would not be blocked, ... I couldn't figure out how to go with async delegates because of the re-serialization of the await syntax.

Here is my solution using Threads instead of Tasks:

using (EventWaitHandle wh = new EventWaitHandle(false, EventResetMode.ManualReset))
{
  int outdex = mediaServerMinConnections - 1;
  for (int i = 0; i < mediaServerMinConnections; i++)
  {
    new Thread(() =>
    {
      sshPool.Enqueue(new SshHandler());
      if (Interlocked.Decrement(ref outdex) < 1)
        wh.Set();
    }).Start();
  }
  wh.WaitOne();
}

Execute combine multiple Linux commands in one line

You can use as the following code;

cd /my_folder && \
rm *.jar && \
svn co path to repo && \
mvn compile package install

It works...

Content Type application/soap+xml; charset=utf-8 was not supported by service

I had the same problem, got it working by "binding" de service with the service behaviour by doing this :

Gave a name to the behaviour

<serviceBehaviors>
        <behavior name="YourBehaviourNameHere">

And making a reference to your behaviour in your service

<services>
  <service name="WCFTradeLibrary.TradeService" behaviorConfiguration="YourBehaviourNameHere">

The whole thing would be :

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

  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="basicHttp" allowCookies="true"
                 maxReceivedMessageSize="20000000"
                 maxBufferSize="20000000"
                 maxBufferPoolSize="20000000">
          <readerQuotas maxDepth="32"
               maxArrayLength="200000000"
               maxStringContentLength="200000000"/>
        </binding>
      </basicHttpBinding>
    </bindings>
    <services>
     <service name="WCFTradeLibrary.TradeService" behaviourConfiguration="YourBehaviourNameHere">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="basicHttp" contract="WCFTradeLibrary.ITradeService">          
         </endpoint>
     </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="YourBehaviourNameHere">
          <!-- To avoid disclosing metadata information, 
          set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faul`enter code here`ts for debugging purposes, 
          set the value below to true.  Set to false before deployment 
          to avoid disclosing exception info`enter code here`rmation -->
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

For rails6, I was facing the same problem, as I was missing following files, once I added them, the issue resolved:

1. config/master.key
2. config/credentials.yml.enc

Make sure you have this files.!!!

How to rename a file using Python

File may be inside a directory, in that case specify the path:

import os
old_file = os.path.join("directory", "a.txt")
new_file = os.path.join("directory", "b.kml")
os.rename(old_file, new_file)

Get Environment Variable from Docker Container

We can modify entrypoint of a non-running container with the docker run command.

Example show PATH environment variable:

  1. using bash and echo: This answer claims that echo will not produce any output, which is incorrect.

    docker run --rm --entrypoint bash <container> -c 'echo "$PATH"'
    
  2. using printenv

    docker run --rm --entrypoint printenv <container> PATH
    

#pragma once vs include guards?

I just wanted to add to this discussion that I am just compiling on VS and GCC, and used to use include guards. I have now switched to #pragma once, and the only reason for me is not performance or portability or standard as I don't really care what is standard as long as VS and GCC support it, and that is that:

#pragma once reduces possibilities for bugs.

It is all too easy to copy and paste a header file to another header file, modify it to suit ones needs, and forget to change the name of the include guard. Once both are included, it takes you a while to track down the error, as the error messages aren't necessarily clear.

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

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

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

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

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

IMHO this is much more readable.


In Kotlin this looks like this:

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

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

Check if one list contains element from the other

If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line

!Collections.disjoint(list1, list2);

If you need to test a specific property, that's harder. I would recommend, by default,

list1.stream()
   .map(Object1::getProperty)
   .anyMatch(
     list2.stream()
       .map(Object2::getProperty)
       .collect(toSet())
       ::contains)

...which collects the distinct values in list2 and tests each value in list1 for presence.

Where is the Docker daemon log?

If your OS is using systemd then you can view docker daemon log with:

sudo journalctl -fu docker.service

PHP server on local machine?

If you are using Windows, then the WPN-XM Server Stack might be a suitable alternative.

How to disable the resize grabber of <textarea>?

<textarea style="resize:none" name="name" cols="num" rows="num"></textarea>

Just an example

Understanding INADDR_ANY for socket programming

INADDR_ANY is used when you don't need to bind a socket to a specific IP. When you use this value as the address when calling bind(), the socket accepts connections to all the IPs of the machine.

Turn a string into a valid filename?

You can look at the Django framework for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly.

The Django text utils define a function, slugify(), that's probably the gold standard for this kind of thing. Essentially, their code is the following.

import unicodedata
import re

def slugify(value, allow_unicode=False):
    """
    Taken from https://github.com/django/django/blob/master/django/utils/text.py
    Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
    dashes to single dashes. Remove characters that aren't alphanumerics,
    underscores, or hyphens. Convert to lowercase. Also strip leading and
    trailing whitespace, dashes, and underscores.
    """
    value = str(value)
    if allow_unicode:
        value = unicodedata.normalize('NFKC', value)
    else:
        value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
    value = re.sub(r'[^\w\s-]', '', value.lower())
    return re.sub(r'[-\s]+', '-', value).strip('-_')

And the older version:

def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.
    """
    import unicodedata
    value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
    value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
    value = unicode(re.sub('[-\s]+', '-', value))
    # ...
    return value

There's more, but I left it out, since it doesn't address slugification, but escaping.

How do I generate sourcemaps when using babel and webpack?

If optimizing for dev + production, you could try something like this in your config:

const dev = process.env.NODE_ENV !== 'production'

// in config

{
  devtool: dev ? 'eval-cheap-module-source-map' : 'source-map',
}

From the docs:

  • devtool: "eval-cheap-module-source-map" offers SourceMaps that only maps lines (no column mappings) and are much faster
  • devtool: "source-map" cannot cache SourceMaps for modules and need to regenerate complete SourceMap for the chunk. It’s something for production.

I am using webpack 2.1.0-beta.19

Compression/Decompression string with C#

This is an updated version for .NET 4.5 and newer using async/await and IEnumerables:

public static class CompressionExtensions
{
    public static async Task<IEnumerable<byte>> Zip(this object obj)
    {
        byte[] bytes = obj.Serialize();

        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(mso, CompressionMode.Compress))
                await msi.CopyToAsync(gs);

            return mso.ToArray().AsEnumerable();
        }
    }

    public static async Task<object> Unzip(this byte[] bytes)
    {
        using (MemoryStream msi = new MemoryStream(bytes))
        using (MemoryStream mso = new MemoryStream())
        {
            using (var gs = new GZipStream(msi, CompressionMode.Decompress))
            {
                // Sync example:
                //gs.CopyTo(mso);

                // Async way (take care of using async keyword on the method definition)
                await gs.CopyToAsync(mso);
            }

            return mso.ToArray().Deserialize();
        }
    }
}

public static class SerializerExtensions
{
    public static byte[] Serialize<T>(this T objectToWrite)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            binaryFormatter.Serialize(stream, objectToWrite);

            return stream.GetBuffer();
        }
    }

    public static async Task<T> _Deserialize<T>(this byte[] arr)
    {
        using (MemoryStream stream = new MemoryStream())
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            await stream.WriteAsync(arr, 0, arr.Length);
            stream.Position = 0;

            return (T)binaryFormatter.Deserialize(stream);
        }
    }

    public static async Task<object> Deserialize(this byte[] arr)
    {
        object obj = await arr._Deserialize<object>();
        return obj;
    }
}

With this you can serialize everything BinaryFormatter supports, instead only of strings.

Edit:

In case, you need take care of Encoding, you could just use Convert.ToBase64String(byte[])...

Take a look at this answer if you need an example!

Plotting a list of (x, y) coordinates in python matplotlib

As per this example:

import numpy as np
import matplotlib.pyplot as plt

N = 50
x = np.random.rand(N)
y = np.random.rand(N)

plt.scatter(x, y)
plt.show()

will produce:

enter image description here

To unpack your data from pairs into lists use zip:

x, y = zip(*li)

So, the one-liner:

plt.scatter(*zip(*li))

node.js hash string?

The crypto module makes this very easy.

Setup:

// import crypto from 'crypto';
const crypto = require('crypto');

const sha256 = x => crypto.createHash('sha256').update(x, 'utf8').digest('hex');

Usage:

sha256('Hello, world. ');

How do I copy an object in Java?

Add Cloneable and below code to your class

public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

Use this clonedObject = (YourClass) yourClassObject.clone();

How to get all keys with their values in redis

You can use MGET to get the values of multiple keys in a single go.

Example:

redis> SET key1 "Hello"
"OK"
redis> SET key2 "World"
"OK"
redis> MGET key1 key2 nonexisting
1) "Hello"
2) "World"
3) (nil)

For listing out all keys & values you'll probably have to use bash or something similar, but MGET can help in listing all the values when you know which keys to look for beforehand.

How to redirect to a 404 in Rails?

You could also use the render file:

render file: "#{Rails.root}/public/404.html", layout: false, status: 404

Where you can choose to use the layout or not.

Another option is to use the Exceptions to control it:

raise ActiveRecord::RecordNotFound, "Record not found."

Conversion failed when converting the nvarchar value ... to data type int

You are trying to concatenate a string and an integer.
You need to cast @ID as a string.
try:

SET @sql=@sql+' AND Emp_Id_Pk=' + CAST(@ID AS NVARCHAR(10))

How do I make an image smaller with CSS?

You can resize images using CSS just fine if you're modifying an image tag:

<img src="example.png" style="width:2em; height:3em;" />

You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size.

What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

Saving a select count(*) value to an integer (SQL Server)

select @myInt = COUNT(*) from myTable

Can I get "&&" or "-and" to work in PowerShell?

I tried this sequence of commands in PowerShell:

First Test

PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True

($MyVar -ne $null) returned true and (Get-Content $MyVar) also returned true.

Second Test

PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False

($MyVar -ne $null) returned false and so far I must assume the (Get-Content $MyVar) also returned false.

The third test proved the second condition was not even analyzed.

PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False

($MyVar -ne $null) returned false and proved the second condition (Get-Content "C:\MyTxt.txt") never ran, by returning false on the whole command.

PostgreSQL: days/months/years between two dates

SELECT
  AGE('2012-03-05', '2010-04-01'),
  DATE_PART('year', AGE('2012-03-05', '2010-04-01')) AS years,
  DATE_PART('month', AGE('2012-03-05', '2010-04-01')) AS months,
  DATE_PART('day', AGE('2012-03-05', '2010-04-01')) AS days;

This will give you full years, month, days ... between two dates:

          age          | years | months | days
-----------------------+-------+--------+------
 1 year 11 mons 4 days |     1 |     11 |    4

More detailed datediff information.

Random float number generation

If you know that your floating point format is IEEE 754 (almost all modern CPUs including Intel and ARM) then you can build a random floating point number from a random integer using bit-wise methods. This should only be considered if you do not have access to C++11's random or Boost.Random which are both much better.

float rand_float()
{
    // returns a random value in the range [0.0-1.0)

    // start with a bit pattern equating to 1.0
    uint32_t pattern = 0x3f800000;

    // get 23 bits of random integer
    uint32_t random23 = 0x7fffff & (rand() << 8 ^ rand());

    // replace the mantissa, resulting in a number [1.0-2.0)
    pattern |= random23;

    // convert from int to float without undefined behavior
    assert(sizeof(float) == sizeof(uint32_t));
    char buffer[sizeof(float)];
    memcpy(buffer, &pattern, sizeof(float));
    float f;
    memcpy(&f, buffer, sizeof(float));

    return f - 1.0;
}

This will give a better distribution than one using division.

How to I say Is Not Null in VBA

Use Not IsNull(Fields!W_O_Count.Value)

Finding median of list in Python

You can try the quickselect algorithm if faster average-case running times are needed. Quickselect has average (and best) case performance O(n), although it can end up O(n²) on a bad day.

Here's an implementation with a randomly chosen pivot:

import random

def select_nth(n, items):
    pivot = random.choice(items)

    lesser = [item for item in items if item < pivot]
    if len(lesser) > n:
        return select_nth(n, lesser)
    n -= len(lesser)

    numequal = items.count(pivot)
    if numequal > n:
        return pivot
    n -= numequal

    greater = [item for item in items if item > pivot]
    return select_nth(n, greater)

You can trivially turn this into a method to find medians:

def median(items):
    if len(items) % 2:
        return select_nth(len(items)//2, items)

    else:
        left  = select_nth((len(items)-1) // 2, items)
        right = select_nth((len(items)+1) // 2, items)

        return (left + right) / 2

This is very unoptimised, but it's not likely that even an optimised version will outperform Tim Sort (CPython's built-in sort) because that's really fast. I've tried before and I lost.

Split an integer into digits to compute an ISBN checksum

Recursion version:

def int_digits(n):
    return [n] if n<10 else int_digits(n/10)+[n%10]

Switch on ranges of integers in JavaScript

Here is another way I figured it out:

const x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

Adding files to java classpath at runtime

The way I have done this is by using my own class loader

URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
DynamicURLClassLoader dynalLoader = new DynamicURLClassLoader(urlClassLoader);

And create the following class:

public class DynamicURLClassLoader extends URLClassLoader {

    public DynamicURLClassLoader(URLClassLoader classLoader) {
        super(classLoader.getURLs());
    }

    @Override
    public void addURL(URL url) {
        super.addURL(url);
    }
}

Works without any reflection

Using setDate in PreparedStatement

If you want to add the current date into the database, I would avoid calculating the date in Java to begin with. Determining "now" on the Java (client) side leads to possible inconsistencies in the database if the client side is mis-configured, has the wrong time, wrong timezone, etc. Instead, the date can be set on the server side in a manner such as the following:

requestSQL = "INSERT INTO CREDIT_REQ_TITLE_ORDER ("   +
                "REQUEST_ID, ORDER_DT, FOLLOWUP_DT) " +
                "VALUES(?, SYSDATE, SYSDATE + 30)";

...

prs.setInt(1, new Integer(requestID));

This way, only one bind parameter is required and the dates are calculated on the server side will be consistent. Even better would be to add an insert trigger to CREDIT_REQ_TITLE_ORDER and have the trigger insert the dates. That can help enforce consistency between different client apps (for example, someone trying to do a fix via sqlplus.

Apache 2.4.3 (with XAMPP 1.8.1) not starting in windows 8

This problem may occur due to apache not getting required port (default is 80).

The port may be being used by other services.

For example: Skype also has default port 80.

Installing Skype and Apache both on same machine will cause conflict and hence Apache will not start.

Either, you change Skype port or change Apache port as described in following steps:

Change the ports of Apache and it will work for you. Go to httpd.conf

How to change port for Apache:

Search for:

ServerName localhost:80

Change it to:

ServerName localhost:81

Also Search For:

Listen 80

Change it to:

Listen 81

If you have created any virtual hosts, change the ports there also. Then restart your apache.

How to pass 2D array (matrix) in a function in C?

Easiest Way in Passing A Variable-Length 2D Array

Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.

#include <stdio.h>

void func(int row, int col, int* matrix){
    int i, j;
    for(i=0; i<row; i++){
        for(j=0; j<col; j++){
            printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
        }
        printf("\n");
    }
}

int main(){
    int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
    func(2, 3, matrix[0]);

    return 0;
}

Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.

jQuery call function after load

$(window).bind("load", function() {

   // code here 
});

Linq order by, group by and order by each group?

Sure:

var query = grades.GroupBy(student => student.Name)
                  .Select(group => 
                        new { Name = group.Key,
                              Students = group.OrderByDescending(x => x.Grade) })
                  .OrderBy(group => group.Students.First().Grade);

Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.

Then you could display them with:

foreach (var group in query)
{
    Console.WriteLine("Group: {0}", group.Name);
    foreach (var student in group.Students)
    {
        Console.WriteLine("  {0}", student.Grade);
    }
}

Jenkins could not run git

I got a very similar error when my Jenkins agent was running Java 11 instead of Java 8. It had nothing to do with configuring my git path! Downgrading the agent to Java 8 was the only solution I found.

How to tar certain file types in all subdirectories?

If you're using bash version > 4.0, you can exploit shopt -s globstar to make short work of this:

shopt -s globstar; tar -czvf deploy.tar.gz **/Alice*.yml **/Bob*.json

this will add all .yml files that starts with Alice from any sub-directory and add all .json files that starts with Bob from any sub-directory.

Open Redis port for remote connections

  1. Open the file at location /etc/redis.conf

  2. Comment out bind 127.0.0.1

  3. Restart Redis:

     sudo systemctl start redis.service
    
  4. Disable Firewalld:

     systemctl disable firewalld
    
  5. Stop Firewalld:

     systemctl stop firewalld
    

Then try:

redis-cli -h 192.168.0.2(ip) -a redis(username)

CodeIgniter: How to get Controller, Action, URL information

$this->router->fetch_class(); 

// fecth class the class in controller $this->router->fetch_method();

// method

How to recover just deleted rows in mysql?

If you use MyISAM tables, then you can recover any data you deleted, just

open file: mysql/data/[your_db]/[your_table].MYD

with any text editor

Using a RegEx to match IP addresses in Python

regex for ip v4:

^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$

otherwise you take not valid ip address like 999.999.999.999, 256.0.0.0 etc

PHP - Get key name of array value

If i understand correctly, can't you simply use:

foreach($arr as $key=>$value)
{
  echo $key;
}

See PHP manual

Delete all objects in a list

If the goal is to delete the objects a and b themselves (which appears to be the case), forming the list [a, b] is not helpful. Instead, one should keep a list of strings used as the names of those objects. These allow one to delete the objects in a loop, by accessing the globals() dictionary.

c = ['a', 'b']
# create and work with a and b    
for i in c:
    del globals()[i]

ORA-01017 Invalid Username/Password when connecting to 11g database from 9i client

The user and password are DEFINITELY incorrect. Oracle 11g credentials are case sensitive.

Try ALTER SYSTEM SET SEC_CASE_SENSITIVE_LOGON = FALSE; and alter password.

http://oracle-base.com/articles/11g/case-sensitive-passwords-11gr1.php

Is there a command line command for verifying what version of .NET is installed

You mean a DOS command such as below will do the job displaying installed .NET frameworks:

wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get version

The following may then be displayed:

Version
4.0.30319

WMIC is quite useful once you master using it, much easier than coding WMI in scripts depending on what you want to achieve.

How do you change the server header returned by nginx?

Like Apache, this is a quick edit to the source and recompile. From Calomel.org:

The Server: string is the header which is sent back to the client to tell them what type of http server you are running and possibly what version. This string is used by places like Alexia and Netcraft to collect statistics about how many and of what type of web server are live on the Internet. To support the author and statistics for Nginx we recommend keeping this string as is. But, for security you may not want people to know what you are running and you can change this in the source code. Edit the source file src/http/ngx_http_header_filter_module.c at look at lines 48 and 49. You can change the String to anything you want.

## vi src/http/ngx_http_header_filter_module.c (lines 48 and 49)
static char ngx_http_server_string[] = "Server: MyDomain.com" CRLF;
static char ngx_http_server_full_string[] = "Server: MyDomain.com" CRLF;

March 2011 edit: Props to Flavius below for pointing out a new option, replacing Nginx's standard HttpHeadersModule with the forked HttpHeadersMoreModule. Recompiling the standard module is still the quick fix, and makes sense if you want to use the standard module and won't be changing the server string often. But if you want more than that, the HttpHeadersMoreModule is a strong project and lets you do all sorts of runtime black magic with your HTTP headers.

DB2 Date format

This isn't straightforward, but

SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1

returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.

SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

Can I set subject/content of email using mailto:?

You can add subject added to the mailto command using either one of the following ways. Add ?subject out mailto to the mailto tag.

<a href="mailto:[email protected]?subject=testing out mailto">First Example</a>

We can also add text into the body of the message by adding &body to the end of the tag as shown in the below example.

 <a href="mailto:[email protected]?subject=testing out mailto&body=Just testing">Second Example</a>

In addition to body, a user may also type &cc or &bcc to fill out the CC and BCC fields.

<a href="mailto:[email protected]?subject=testing out mailto&body=Just testing&[email protected]&[email protected]">Third
    Example</a>

How to add subject to mailto tag

JPA Query.getResultList() - use in a generic way

General rule is the following:

  • If select contains single expression and it's an entity, then result is that entity
  • If select contains single expression and it's a primitive, then result is that primitive
  • If select contains multiple expressions, then result is Object[] containing the corresponding primitives/entities

So, in your case list is a List<Object[]>.

Converting byte array to String (Java)

The byte array contains characters in a special encoding (that you should know). The way to convert it to a String is:

String decoded = new String(bytes, "UTF-8");  // example for one encoding type

By The Way - the raw bytes appear may appear as negative decimals just because the java datatype byte is signed, it covers the range from -128 to 127.


-109 = 0x93: Control Code "Set Transmit State"

The value (-109) is a non-printable control character in UNICODE. So UTF-8 is not the correct encoding for that character stream.

0x93 in "Windows-1252" is the "smart quote" that you're looking for, so the Java name of that encoding is "Cp1252". The next line provides a test code:

System.out.println(new String(new byte[]{-109}, "Cp1252")); 

How to sort a file in-place

sort file | sponge file

This is in the following Fedora package:

moreutils : Additional unix utilities
Repo        : fedora
Matched from:
Filename    : /usr/bin/sponge

Are there dictionaries in php?

http://php.net/manual/en/language.types.array.php

<?php
$array = array(
    "foo" => "bar",
    "bar" => "foo",
);

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",
];
?>

Standard arrays can be used that way.

How to Navigate from one View Controller to another using Swift

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
navigationController?.pushViewController(home, animated: true);

How to select only 1 row from oracle sql?

The answer is:

You should use nested query as:

SELECT *
FROM ANY_TABLE_X 
WHERE ANY_COLUMN_X = (SELECT MAX(ANY_COLUMN_X) FROM ANY_TABLE_X) 

=> In PL/SQL "ROWNUM = 1" is NOT equal to "TOP 1" of TSQL.

So you can't use a query like this: "select * from any_table_x where rownum=1 order by any_column_x;" Because oracle gets first row then applies order by clause.

vuejs update parent data from child component

The way more simple is use this.$emit

Father.vue

<template>
  <div>
    <h1>{{ message }}</h1>
    <child v-on:listenerChild="listenerChild"/>
  </div>
</template>

<script>
import Child from "./Child";
export default {
  name: "Father",
  data() {
    return {
      message: "Where are you, my Child?"
    };
  },
  components: {
    Child
  },
  methods: {
    listenerChild(reply) {
      this.message = reply;
    }
  }
};
</script>

Child.vue

<template>
  <div>
    <button @click="replyDaddy">Reply Daddy</button>
  </div>
</template>

<script>
export default {
  name: "Child",
  methods: {
    replyDaddy() {
      this.$emit("listenerChild", "I'm here my Daddy!");
    }
  }
};
</script>

My full example: https://codesandbox.io/s/update-parent-property-ufj4b

How to determine the version of the C++ standard used by the compiler?

__cplusplus

In C++0x the macro __cplusplus will be set to a value that differs from (is greater than) the current 199711L.

C++0x FAQ by BS

Converting milliseconds to minutes and seconds with Javascript

With hours, 0-padding minutes and seconds:

var ms = 298999;
var d = new Date(1000*Math.round(ms/1000)); // round to nearest second
function pad(i) { return ('0'+i).slice(-2); }
var str = d.getUTCHours() + ':' + pad(d.getUTCMinutes()) + ':' + pad(d.getUTCSeconds());
console.log(str); // 0:04:59

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

What is the best collation to use for MySQL with PHP?

Collations affect how data is sorted and how strings are compared to each other. That means you should use the collation that most of your users expect.

Example from the documentation for charset unicode:

utf8_general_ci also is satisfactory for both German and French, except that ‘ß’ is equal to ‘s’, and not to ‘ss’. If this is acceptable for your application, then you should use utf8_general_ci because it is faster. Otherwise, use utf8_unicode_ci because it is more accurate.

So - it depends on your expected user base and on how much you need correct sorting. For an English user base, utf8_general_ci should suffice, for other languages, like Swedish, special collations have been created.

How to set a binding in Code?

You need to change source to viewmodel object:

myBinding.Source = viewModelObject;

Bootstrap 3 navbar active li not changing background-color

Well, I had a similar challenge. Using the inspect element tool in Firefox, I was able to trace the markup and the CSS used to style the link when clicked. On click, the list item (li) is given a class of .open and it's the anchor tag in the class that is formatted with the grey color background.

To fix this, just add this to your stylesheet.

.nav .open > a
{
    background:#759ad6;
    // Put in styling
}

angular2: Error: TypeError: Cannot read property '...' of undefined

That's because abc is undefined at the moment of the template rendering. You can use safe navigation operator (?) to "protect" template until HTTP call is completed:

{{abc?.xyz?.name}}

You can read more about safe navigation operator here.

Update:

Safe navigation operator can't be used in arrays, you will have to take advantage of NgIf directive to overcome this problem:

<div *ngIf="arr && arr.length > 0">
    {{arr[0].name}}
</div>

Read more about NgIf directive here.

Loading and parsing a JSON file with multiple JSON objects

You have a JSON Lines format text file. You need to parse your file line by line:

import json

data = []
with open('file') as f:
    for line in f:
        data.append(json.loads(line))

Each line contains valid JSON, but as a whole, it is not a valid JSON value as there is no top-level list or object definition.

Note that because the file contains JSON per line, you are saved the headaches of trying to parse it all in one go or to figure out a streaming JSON parser. You can now opt to process each line separately before moving on to the next, saving memory in the process. You probably don't want to append each result to one list and then process everything if your file is really big.

If you have a file containing individual JSON objects with delimiters in-between, use How do I use the 'json' module to read in one JSON object at a time? to parse out individual objects using a buffered method.

How can you determine a point is between two other points on a line segment?

The length of the segment is not important, thus using a square root is not required and should be avoided since we could lose some precision.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class Segment:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def is_between(self, c):
        # Check if slope of a to c is the same as a to b ;
        # that is, when moving from a.x to c.x, c.y must be proportionally
        # increased than it takes to get from a.x to b.x .

        # Then, c.x must be between a.x and b.x, and c.y must be between a.y and b.y.
        # => c is after a and before b, or the opposite
        # that is, the absolute value of cmp(a, b) + cmp(b, c) is either 0 ( 1 + -1 )
        #    or 1 ( c == a or c == b)

        a, b = self.a, self.b             

        return ((b.x - a.x) * (c.y - a.y) == (c.x - a.x) * (b.y - a.y) and 
                abs(cmp(a.x, c.x) + cmp(b.x, c.x)) <= 1 and
                abs(cmp(a.y, c.y) + cmp(b.y, c.y)) <= 1)

Some random example of usage :

a = Point(0,0)
b = Point(50,100)
c = Point(25,50)
d = Point(0,8)

print Segment(a,b).is_between(c)
print Segment(a,b).is_between(d)

How to use ScrollView in Android?

There are two options. You can make your entire layout to be scrollable or only the TextView to be scrollable.

For the first case,

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

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:stretchColumns="1" >

            <TableRow>

                <ImageView
                    android:id="@+id/imageView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="5dip"
                    android:layout_marginRight="5dip"
                    android:layout_marginTop="10dip"
                    android:src="@drawable/icon"
                    android:tint="#55ff0000" >
                </ImageView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Name " >
                </TextView>

                <TextView
                    android:id="@+id/name1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Veer" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/age"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Age" >
                </TextView>

                <TextView
                    android:id="@+id/age1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="23" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/gender"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Gender" >
                </TextView>

                <TextView
                    android:id="@+id/gender1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Male" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/profession"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Professsion" >
                </TextView>

                <TextView
                    android:id="@+id/profession1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Mobile Developer" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/phone"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Phone" >
                </TextView>

                <TextView
                    android:id="@+id/phone1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="03333736767" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/email"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Email" >
                </TextView>

                <TextView
                    android:id="@+id/email1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="[email protected]" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/hobby"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Hobby" >
                </TextView>

                <TextView
                    android:id="@+id/hobby1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Play Games" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/ilike"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  I like" >
                </TextView>

                <TextView
                    android:id="@+id/ilike1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Java, Objective-c" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/idislike"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  I dislike" >
                </TextView>

                <TextView
                    android:id="@+id/idislike1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Microsoft" >
                </TextView>
            </TableRow>

            <TableRow>

                <TextView
                    android:id="@+id/address"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:padding="3dip"
                    android:text="  Address" >
                </TextView>

                <TextView
                    android:id="@+id/address1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:gravity="left"
                    android:text="Johar Mor" >
                </TextView>
            </TableRow>

            <Relativelayout>
            </Relativelayout>
        </TableLayout>
    </RelativeLayout>

</ScrollView>

or, as I said you can use scrollView for TextView alone.

Delete statement in SQL is very slow

As an extension to Andomar's answer, above, I had a scenario where the first 700,000,000 records (of ~1.2 billion) processed very quickly, with chunks of 25,000 records processing per second (roughly). But, then it starting taking 15 minutes to do a batch of 25,000. I reduced the chunk size down to 5,000 records and it went back to its previous speed. I'm not certain what internal threshold I hit, but the fix was to reduce the number of records, further, to regain the speed.

String.equals versus ==

It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()) during compilation - so when you write for example "hello world" in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal") and second is constructed during runtime ie. with "new" keyword like new String("i am string literal"), the == (equality) operator returns false, because both of them are different instances of the String class.

Only right way is using .equals() -> datos[0].equals(usuario). == says only if two objects are the same instance of object (ie. have same memory address)

Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language

Is there a job scheduler library for node.js?

All these answers and noone has pointed to the most popular NPM package .. cron

https://www.npmjs.com/package/cron

image processing to improve tesseract OCR accuracy

Adaptive thresholding is important if the lighting is uneven across the image. My preprocessing using GraphicsMagic is mentioned in this post: https://groups.google.com/forum/#!topic/tesseract-ocr/jONGSChLRv4

GraphicsMagic also has the -lat feature for Linear time Adaptive Threshold which I will try soon.

Another method of thresholding using OpenCV is described here: http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_thresholding/py_thresholding.html

Getting a Request.Headers value

The following code should allow you to check for the existance of the header you're after in Request.Headers:

if (Request.Headers.AllKeys.Contains("XYZComponent"))
{
    // Can now check if the value is true:
    var value = Convert.ToBoolean(Request.Headers["XYZComponent"]);
}

How to parseInt in Angular.js

Perform the operation inside the scope itself.

<script>
angular.controller('MyCtrl', function($scope, $window) {
$scope.num1= 0;
$scope.num2= 1;


  $scope.total = $scope.num1 + $scope.num2;

 });
</script>
<input type="text" ng-model="num1">
<input type="text" ng-model="num2">

Total: {{total}}

I want to remove double quotes from a String

If you're trying to remove the double quotes try following

  var Stringstr = "\"I am here\"";
  var mystring = String(Stringstr);
  mystring = mystring.substring(1, mystring.length - 1);
  alert(mystring);

Git keeps asking me for my ssh key passphrase

Once you have started the SSH agent with:

eval $(ssh-agent)

Do either:

  1. To add your private key to it:

     ssh-add
    

    This will ask you your passphrase just once, and then you should be allowed to push, provided that you uploaded the public key to Github.

  2. To add and save your key permanently on macOS:

     ssh-add -K  
    

    This will persist it after you close and re-open it by storing it in user's keychain.

  3. To add and save your key permanently on Ubuntu (or equivalent):

      ssh-add ~/.ssh/id_rsa
    

How do I trigger a macro to run after a new mail is received in Outlook?

Try something like this inside ThisOutlookSession:

Private Sub Application_NewMail()
    Call Your_main_macro
End Sub

My outlook vba just fired when I received an email and had that application event open.

Edit: I just tested a hello world msg box and it ran after being called in the application_newmail event when an email was received.

Setting up connection string in ASP.NET to SQL SERVER

For some reason I don't see the simple answer here.

Put this at the top of your code:

using System.Web.Configuration;
using System.Data.SqlClient; 

Put this in Web.Config:

<connectionStrings >
    <add
         name="myConnectionString" 
         connectionString="Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False;"
         providerName="System.Data.SqlClient"/>
</connectionStrings>

and where you want to setup the connection variable:

SqlConnection con = new SqlConnection(
    WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

Is there anyway to exclude artifacts inherited from a parent POM?

When you call a package but do not want some of its dependencies you can do a thing like this (in this case I did not want the old log4j to be added because I needed to use the newer one):

<dependency>
  <groupId>package</groupId>
  <artifactId>package-pk</artifactId>
  <version>${package-pk.version}</version>

  <exclusions>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
    </exclusion>
    <exclusion>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<!-- LOG4J -->
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-core</artifactId>
  <version>2.5</version>
</dependency>
<dependency>
  <groupId>org.apache.logging.log4j</groupId>
  <artifactId>log4j-api</artifactId>
  <version>2.5</version>
</dependency>

This works for me... but I am pretty new to java/maven so it is maybe not optimum.

SQL Server find and replace specific word in all rows of specific column

You can also export the database and then use a program like notepad++ to replace words and then inmport aigain.

How do you display code snippets in MS Word preserving format and syntax highlighting?

Simply right click and paste using the "Keep Source Formatting" option. I do this almost everyday to document my work. Further, you can set the 'default paste' for pasting from various soures in File/Options/Advanced/Cut,CopyPaste. Also useful: enable "Show paste options" in the same section of Word Options.

Note that all of the text properties from your Code Editor's theme (colors, fonts, etc.) will be added to the Stylesheet in your Word doc, so I would recommend that you not make any changes directly to the pasted text as that will add clutter to your stylesheet and subsequent pastes will not match. It will be to your great advantage to do a quick study on using 'Styles' in Word (which are actually CSS). They are very powerful. Using Word's Stylesheet you can make global changes to the pasted text, but it will probably cause subsequent pasted text to add new styles.

How to remove index.php from URLs?

How about this in your .htaccess:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

Ruby on Rails generates model field:type - what are the options for field:type?

http://guides.rubyonrails.org should be a good site if you're trying to get through the basic stuff in Ruby on Rails.

Here is a link to associate models while you generate them: http://guides.rubyonrails.org/getting_started.html#associating-models

How can I get a side-by-side diff when I do "git diff"?

This question showed up when I was searching for a fast way to use git builtin way to locate differences. My solution criteria:

  • Fast startup, needed builtin options
  • Can handle many formats easily, xml, different programming languages
  • Quickly identify small code changes in big textfiles

I found this answer to get color in git.

To get side by side diff instead of line diff I tweaked mb14's excellent answer on this question with the following parameters:

$ git diff --word-diff-regex="[A-Za-z0-9. ]|[^[:space:]]"

If you do not like the extra [- or {+ the option --word-diff=color can be used.

$ git diff --word-diff-regex="[A-Za-z0-9. ]|[^[:space:]]" --word-diff=color

That helped to get proper comparison with both json and xml text and java code.

In summary the --word-diff-regex options has a helpful visibility together with color settings to get a colorized side by side source code experience compared to the standard line diff, when browsing through big files with small line changes.

Link to reload current page

<a href="">Refresh!</a>

Leave the href="" blank and it will refresh the page.
Also works if some info is passed using forms.

console.log(result) returns [object Object]. How do I get result.name?

Try adding JSON.stringify(result) to convert the JS Object into a JSON string.

From your code I can see you are logging the result in error which is called if the AJAX request fails, so I'm not sure how you'd go about accessing the id/name/etc. then (you are checking for success inside the error condition!).

Note that if you use Chrome's console you should be able to browse through the object without having to stringify the JSON, which makes it easier to debug.

SQL Server Management Studio, how to get execution time down to milliseconds

What you want to do is this:

set statistics time on

-- your query

set statistics time off

That will have the output looking something like this in your Messages window:

SQL Server Execution Times: CPU time = 6 ms, elapsed time = 6 ms.

byte[] to file in Java

Without any libraries:

try (FileOutputStream stream = new FileOutputStream(path)) {
    stream.write(bytes);
}

With Google Guava:

Files.write(bytes, new File(path));

With Apache Commons:

FileUtils.writeByteArrayToFile(new File(path), bytes);

All of these strategies require that you catch an IOException at some point too.

private constructor

It is reasonable to make constructor private if there are other methods that can produce instances. Obvious examples are patterns Singleton (every call return the same instance) and Factory (every call usually create new instance).

Are there any free Xml Diff/Merge tools available?

I wrote and released a Windows application that specifically solves the problem of comparing and merging XML files.

Project: Merge can perform two and three way comparisons and merges of any XML file (where two of the files are considered to be independent revisions of a common base file). You can instruct it to identify elements within the input files by attribute values, or the content of child elements, among other things.

It is fully controllable via the command line and can also generate text reports containing the differences between the files.

Project: Merge merging three XML files

How to enable multidexing with the new Android Multidex support library

Multi_Dex.java

public class Multi_Dex extends Application {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

ImportError: No module named Image

The PIL distribution is mispackaged for egg installation.

Install Pillow instead, the friendly PIL fork.

Find the day of a week

Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:

require(lubridate)
df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)

The result is the days in the interval [0,..,6].

If you want the interval to be [1,..7], use the following:

df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)

... or, alternatively:

df$day = df$day + 1

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

You are using field access strategy (determined by @Id annotation). Put any JPA related annotation right above each field instead of getter property

@OneToMany(targetEntity=Student.class, mappedBy="college", fetch=FetchType.EAGER)
private List<Student> students;

How to reset postgres' primary key sequence when it falls out of sync?

Reset all sequences, no assumptions about names except that the primary key of each table is "id":

CREATE OR REPLACE FUNCTION "reset_sequence" (tablename text, columnname text)
RETURNS "pg_catalog"."void" AS
$body$
DECLARE
BEGIN
    EXECUTE 'SELECT setval( pg_get_serial_sequence(''' || tablename || ''', ''' || columnname || '''),
    (SELECT COALESCE(MAX(id)+1,1) FROM ' || tablename || '), false)';
END;
$body$  LANGUAGE 'plpgsql';

select table_name || '_' || column_name || '_seq', reset_sequence(table_name, column_name) from information_schema.columns where column_default like 'nextval%';

Django DB Settings 'Improperly Configured' Error

You can't just fire up Python and check things, Django doesn't know what project you want to work on. You have to do one of these things:

  • Use python manage.py shell
  • Use django-admin.py shell --settings=mysite.settings (or whatever settings module you use)
  • Set DJANGO_SETTINGS_MODULE environment variable in your OS to mysite.settings
  • (This is removed in Django 1.6) Use setup_environ in the python interpreter:

    from django.core.management import setup_environ
    from mysite import settings
    
    setup_environ(settings)
    

Naturally, the first way is the easiest.

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

To set the position relative to the parent you need to set the position:relative of parent and position:absolute of the element

$("#mydiv").parent().css({position: 'relative'});
$("#mydiv").css({top: 200, left: 200, position:'absolute'});

This works because position: absolute; positions relatively to the closest positioned parent (i.e., the closest parent with any position property other than the default static).

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Error:could not create the Java Virtual Machine Error:A fatal exception has occured.Program will exit

--version is a valid option from JDK 9 and it is not a valid option until JDK 8 hence you get the below:

Unrecognized option: --version
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

You can try installing JDK 9 or any version later and check for java --version it will work.

Alternately, from the installed JDK 9 or later versions you can see from java -help the below two options will be available:

    -version      print product version to the error stream and exit
    --version     print product version to the output stream and exit

where as in JDK 8 you will only have below when you execute java -help

    -version      print product version and exit

I hope it answers your question.

Regex number between 1 and 100

Try:

^[1-9][0-9]?$|^100$

Working fiddle

EDIT: IF you want to match 00001, 00000099 try

^0*(?:[1-9][0-9]?|100)$

FIDDLE

Fragment Inside Fragment

Curently in nested fragment, the nested one(s) are only supported if they are generated programmatically! So at this time no nested fragment layout are supported in xml layout scheme!

Android Studio Google JAR file causing GC overhead limit exceeded error

I tried all the solutions mentioned above, but I was still facing the issue. Finally I stumbled upon the following which resolved the issue.

(On MacOS) Went to Preferences -> Memory Settings -> Find existing grade demon(s) -> Stopped all of them.

Hiding a button in Javascript

visibility=hidden

is very useful, but it will still take up space on the page. You can also use

display=none

because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")

What and where are the stack and heap?

The stack is essentially an easy-to-access memory that simply manages its items as a - well - stack. Only items for which the size is known in advance can go onto the stack. This is the case for numbers, strings, booleans.

The heap is a memory for items of which you can’t predetermine the exact size and structure. Since objects and arrays can be mutated and change at runtime, they have to go into the heap.

Source: Academind

Could not load NIB in bundle

I ran into the same problem. In my case the nib name was "MyViewController.xib" and I renamed it to "MyView.xib". This got rid of the error.

I was also moving a project from XCode 3 to 4.2. Changing the Path type did not matter.

Aesthetics must either be length one, or the same length as the dataProblems

I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:

ggplot(df, aes(x="", y = y, fill=grp))

because df was empty.

When should I write the keyword 'inline' for a function/method?

  • When will the the compiler not know when to make a function/method 'inline'?

This depends on the compiler used. Do not blindly trust that nowadays compilers know better then humans how to inline and you should never use it for performance reasons, because it's linkage directive rather than optimization hint. While I agree that ideologically are these arguments correct encountering reality might be a different thing.

After reading multiple threads around I tried out of curiosity the effects of inline on the code I'm just working and the results were that I got measurable speedup for GCC and no speed up for Intel compiler.

(More detail: math simulations with few critical functions defined outside class, GCC 4.6.3 (g++ -O3), ICC 13.1.0 (icpc -O3); adding inline to critical points caused +6% speedup with GCC code).

So if you qualify GCC 4.6 as a modern compiler the result is that inline directive still matters if you write CPU intensive tasks and know where exactly is the bottleneck.

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

How to create .ipa file using Xcode?

Easiest way, follow the steps :

step 1: After Archive project, right click on project and select show in finder

step 2: Right click on that project and select show as Show package contents, in that go to Products>Applications

step 3: Right click on projectname.app

step 4: Copy projectname.app into a empty folder and zip the folder(foldername.zip)

step 5: Change the zipfolder extension to .ipa(foldername.zip -> foldername.ipa)

step 6: Now you have the final .ipa file

How to insert newline in string literal?

If you are working with Web application you can try this.

StringBuilder sb = new StringBuilder();
sb.AppendLine("Some text with line one");
sb.AppendLine("Some mpre text with line two");
MyLabel.Text = sb.ToString().Replace(Environment.NewLine, "<br />")

What is the effect of encoding an image in base64?

It will be bigger in base64.

Base64 uses 6 bits per byte to encode data, whereas binary uses 8 bits per byte. Also, there is a little padding overhead with Base64. Not all bits are used with Base64 because it was developed in the first place to encode binary data on systems that can only correctly process non-binary data.

That means that the encoded image will be around 33%-36% larger (33% from not using 2 of the bits per byte, plus possible padding accounting for the remaining 3%).

How to connect a Windows Mobile PDA to Windows 10

  1. Install

    • Windows Mobile 6 Professional SDK Refresh
    • Windows Mobile 6 Standard SDK Refresh
    • Windows Mobile 6.5 Professional Developer Tool Kit (USA)
    • Windows Mobile 6.5 Standard Developer Tool Kit (USA)
  2. Control Panel > Programs and Features > Add or remove a Windows component

    • NET Framework 3.5
    • Check HTTP and non HTTP
  3. Reinstall WMDC observing your platform x64/x86

  4. Services.msc > Windows Mobile 2003-based device connectivity

    • Logon > Local System
    • Allow service to interact with desktop
  5. Restart your PC

How can I schedule a daily backup with SQL Server Express?

You cannot use the SQL Server agent in SQL Server Express. The way I have done it before is to create a SQL Script, and then run it as a scheduled task each day, you could have multiple scheduled tasks to fit in with your backup schedule/retention. The command I use in the scheduled task is:

"C:\Program Files\Microsoft SQL Server\90\Tools\Binn\SQLCMD.EXE" -i"c:\path\to\sqlbackupScript.sql"

How can I declare and use Boolean variables in a shell script?

My receipe to (my own) idiocy:

# setting ----------------
commonMode=false
if [[ $something == 'COMMON' ]]; then
    commonMode=true
fi

# using ----------------
if $commonMode; then
    echo 'YES, Common Mode'
else
    echo 'NO, no Common Mode'
fi

$commonMode && echo 'commonMode is ON  ++++++'
$commonMode || echo 'commonMode is OFF xxxxxx'

React fetch data in server before render

The best answer I use to receive data from server and display it

 constructor(props){
            super(props);
            this.state = {
                items2 : [{}],
                isLoading: true
            }

        }

componentWillMount (){
 axios({
            method: 'get',
            responseType: 'json',
            url: '....',

        })
            .then(response => {
                self.setState({
                    items2: response ,
                    isLoading: false
                });
                console.log("Asmaa Almadhoun *** : " + self.state.items2);
            })
            .catch(error => {
                console.log("Error *** : " + error);
            });
    })}



    render() {
       return(
       { this.state.isLoading &&
                    <i className="fa fa-spinner fa-spin"></i>

                }
                { !this.state.isLoading &&
            //external component passing Server data to its classes
                     <TestDynamic  items={this.state.items2}/> 
                }
         ) }

How to stick text to the bottom of the page?

You might want to put the absolutely aligned div in a relatively aligned container - this way it will still be contained into the container rather than the browser window.

<div style="position: relative;background-color: blue; width: 600px; height: 800px;">    

    <div style="position: absolute; bottom: 5px; background-color: green">
    TEST (C) 2010
    </div>
</div>

Laravel 5 call a model function in a blade view

You can pass it to view but first query it in controller, and then after that add this :

return view('yourview', COMPACT('variabelnametobepassedtoview'));

How to print a debug log?

You can use error_log to send to your servers error log file (or an optional other file if you'd like)

Git command to show which specific files are ignored by .gitignore

While generally correct your solution does not work in all circumstances. Assume a repo dir like this:

# ls **/*                                                                                                       
doc/index.html  README.txt  tmp/dir0/file0  tmp/file1  tmp/file2

doc:
index.html

tmp:
dir0  file1  file2

tmp/dir0:
file0

and a .gitignore like this:

# cat .gitignore
doc
tmp/*

This ignores the doc directory and all files below tmp. Git works as expected, but the given command for listing the ignored files does not. Lets have a look at what git has to say:

# git ls-files --others --ignored --exclude-standard                                                            
tmp/file1
tmp/file2

Notice that doc is missing from the listing. You can get it with:

# git ls-files --others --ignored --exclude-standard --directory                                                
doc/

Notice the additional --directory option.

From my knowledge there is no one command to list all ignored files at once. But I don't know why tmp/dir0 does not show up at all.

How do I connect to a MySQL Database in Python?

Just a modification in above answer. Simply run this command to install mysql for python

sudo yum install MySQL-python
sudo apt-get install MySQL-python

remember! It is case sensitive.

Is there a way to get the source code from an APK file?

Step 1: Make a new folder and copy over the .apk file that you want to decode.

Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.

Step 2: Now extract this .zip file in the same folder (or NEW FOLDER).

Download https://github.com/pxb1988/dex2jar/releases/tag/2.0 : dex2jar-2.0

Now open command prompt and change directory to that folder (or NEW FOLDER). Then execute : d2j-dex2jar.bat classes.dex

Download this decompiler http://java-decompiler.github.io/ to decompile classes-dex2jar.jar

Step 3: Now open another new folder

Put in the .apk file which you want to decode

Download the latest version of apktool AND apktool (https://ibotpeaches.github.io/Apktool/install/) install window (both can be downloaded from the same link) and place them in the same folder

Open a command window

Now run command like apktool if framework-res.apk (if you don't have it get it here)and next

apktool d myApp.apk (where myApp.apk denotes the filename that you want to decode)

now you get a file folder in that folder and can easily read the apk's xml files.

Copycontents of both folders to a single folder

Done !

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

C++ performance vs. Java/C#

The executable code produced from a Java or C# compiler is not interpretted -- it is compiled to native code "just in time" (JIT). So, the first time code in a Java/C# program is encountered during execution, there is some overhead as the "runtime compiler" (aka JIT compiler) turns the byte code (Java) or IL code (C#) into native machine instructions. However, the next time that code is encountered while the application is still running, the native code is executed immediately. This explains how some Java/C# programs appear to be slow initially, but then perform better the longer they run. A good example is an ASP.Net web site. The very first time the web site is accessed, it may be a bit slower as the C# code is compiled to native code by the JIT compiler. Subsequent accesses result in a much faster web site -- server and client side caching aside.

build failed with: ld: duplicate symbol _OBJC_CLASS_$_Algebra5FirstViewController

I received this once by (accidentally) importing both the .h and .m files into the same class.

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

Could not load file or assembly System.Net.Http, Version=4.0.0.0 with ASP.NET (MVC 4) Web API OData Prerelease

I experienced this issue when I tried to update a Hot Towel Project from the project template and when I created an empty project and installed HotTowel via nuget in VS 2012 as of 10/23/2013.

To fix, I updated via Nuget the Web Api Web Host and Web API packages to 5.0, the current version in NuGet at the moment (10/23/2013).

I then added the binding directs:

<dependentAssembly>
  <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
  <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

How to send POST request?

Your data dictionary conteines names of form input fields, you just keep on right their values to find results. form view Header configures browser to retrieve type of data you declare. With requests library it's easy to send POST:

import requests

url = "https://bugs.python.org"
data = {'@number': 12524, '@type': 'issue', '@action': 'show'}
headers = {"Content-type": "application/x-www-form-urlencoded", "Accept":"text/plain"}
response = requests.post(url, data=data, headers=headers)

print(response.text)

More about Request object: https://requests.readthedocs.io/en/master/api/

Left Join With Where Clause

For this problem, as for many others involving non-trivial left joins such as left-joining on inner-joined tables, I find it convenient and somewhat more readable to split the query with a with clause. In your example,

with settings_for_char as (
  select setting_id, value from character_settings where character_id = 1
)
select
  settings.*,
  settings_for_char.value
from
  settings
  left join settings_for_char on settings_for_char.setting_id = settings.id;

How to make Visual Studio copy a DLL file to the output directory?

(This answer only applies to C# not C++, sorry I misread the original question)

I've got through DLL hell like this before. My final solution was to store the unmanaged DLLs in the managed DLL as binary resources, and extract them to a temporary folder when the program launches and delete them when it gets disposed.

This should be part of the .NET or pinvoke infrastructure, since it is so useful.... It makes your managed DLL easy to manage, both using Xcopy or as a Project reference in a bigger Visual Studio solution. Once you do this, you don't have to worry about post-build events.

UPDATE:

I posted code here in another answer https://stackoverflow.com/a/11038376/364818

Can I create view with parameter in MySQL?

Actually if you create func:

create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;

and view:

create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;

Then you can call a view with a parameter:

select s.* from (select @p1:=12 p) parm , h_parm s;

I hope it helps.

how to cancel/abort ajax request in axios

import React, { Component } from "react";
import axios from "axios";

const CancelToken = axios.CancelToken;

let cancel;

class Abc extends Component {
  componentDidMount() {
    this.Api();
  }

  Api() {
      // Cancel previous request
    if (cancel !== undefined) {
      cancel();
    }
    axios.post(URL, reqBody, {
        cancelToken: new CancelToken(function executor(c) {
          cancel = c;
        }),
      })
      .then((response) => {
        //responce Body
      })
      .catch((error) => {
        if (axios.isCancel(error)) {
          console.log("post Request canceled");
        }
      });
  }

  render() {
    return <h2>cancel Axios Request</h2>;
  }
}

export default Abc;

Best way to overlay an ESRI shapefile on google maps?

I would not use KML. Instead, use GeoJSON which you can natively consume in Google Maps API now. It is a newer feature that didn't exist from the original responses.

In any case, simply open the SHP file in Quantum GIS, and then you can output it in any format you like (KML, GeoJSON).

If you are using Google Maps for Work, I found a premium extension that handles loading shapefiles directly where you can just connect direct to the shapefile that you generate from ESRI. I did a search on the CMaps site and found this snippet which loaded US by state shapefile: https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp

var cMap = new centigon.locationIntelligence.MapView();
    cMap.key([your_api_key]);


    cMap.layerNames(["Basic Shapes"]);
    cMap.dbfKeys([['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','District of Columbia','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming']]);
    cMap.userShapeKeys([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 
    cMap.labels([['Massachusetts','Minnesota','Montana','North Dakota','Hawaii','Idaho','Washington','Arizona','California','Colorado','Nevada','New Mexico','Oregon','Utah','Wyoming','Arkansas','Iowa','Kansas','Missouri','Nebraska','Oklahoma','South Dakota','Louisiana','Texas','Connecticut','New Hampshire','Rhode Island','Vermont','Alabama','Florida','Georgia','Mississippi','South Carolina','Illinois','Indiana','Kentucky','North Carolina','Ohio','Tennessee','Virginia','Wisconsin','West Virginia','Delaware','District of Columbia','Maryland','New Jersey','New York','Pennsylvania','Maine','Michigan','Alaska']]); 

    cMap.polyDataSources([centigon.locationIntelligence.CMapAnalytics.DATA_PROVIDERS.SHAPE_DATAPROVIDER]);
    cMap.layerTypes([centigon.mapping.Layer.TYPE.POLY]);
    cMap.locations([["https://gmapsplugin.net/cmapsanalytics/assets/shapes/usstates.shp"]]);

    cMap.panTo("USA");
    cMap.zoomLevel(3);

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

just copy " _CRT_SECURE_NO_WARNINGS " paste it on projects->properties->c/c++->preprocessor->preprocessor definitions click ok.it will work

how to check if the input is a number or not in C?

A self-made solution:

bool isNumeric(const char *str) 
{
    while(*str != '\0')
    {
        if(*str < '0' || *str > '9')
            return false;
        str++;
    }
    return true;
}

Note that this solution should not be used in production-code, because it has severe limitations. But I like it for understanding C-Strings and ASCII.

How to get row data by clicking a button in a row in an ASP.NET gridview

<ItemTemplate>
     <asp:Button ID="Button1" runat="server" Text="Button" 
            OnClick="MyButtonClick" />
</ItemTemplate>

and your method

 protected void MyButtonClick(object sender, System.EventArgs e)
{
     //Get the button that raised the event
Button btn = (Button)sender;

    //Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

For me, something different worked, that I found in on this answer from a similar question. Probably won't help OP, but maybe someone like me that had a similar problem.

You should indeed use rvm, but as no one explained to you how to do this without rvm, here you go:

sudo gem install tzinfo builder memcache-client rack rack-test rack-mount \
  abstract erubis activesupport mime-types mail text-hyphen text-format   \
  thor i18n rake bundler arel railties rails --prerelease --force

How to delete duplicate lines in a file without sorting it in Unix?

awk '!seen[$0]++' file.txt

seen is an associative-array that Awk will pass every line of the file to. If a line isn't in the array then seen[$0] will evaluate to false. The ! is the logical NOT operator and will invert the false to true. Awk will print the lines where the expression evaluates to true. The ++ increments seen so that seen[$0] == 1 after the first time a line is found and then seen[$0] == 2, and so on.
Awk evaluates everything but 0 and "" (empty string) to true. If a duplicate line is placed in seen then !seen[$0] will evaluate to false and the line will not be written to the output.

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

How to paste yanked text into the Vim command line

  1. "[a-z]y: Copy text to the [a-z] register

  2. Use :! to go to the edit command

  3. Ctrl + R: Follow the register identity to paste what you copy.

It used to CentOS 7.

How to change the hosts file on android

That didn't really work in my case - i.e. in order to overwrite hosts file you have to follow it's directions, ie:

./emulator -avd myEmulatorName -partition-size 280

and then in other term window (pushing new hosts file /tmp/hosts):

./adb remount
./adb push /tmp/hosts /system/etc

Copy files from one directory into an existing directory

Assuming t1 is the folder with files in it, and t2 is the empty directory. What you want is something like this:

sudo cp -R t1/* t2/

Bear in mind, for the first example, t1 and t2 have to be the full paths, or relative paths (based on where you are). If you want, you can navigate to the empty folder (t2) and do this:

sudo cp -R t1/* ./

Or you can navigate to the folder with files (t1) and do this:

sudo cp -R ./* t2/

Note: The * sign (or wildcard) stands for all files and folders. The -R flag means recursively (everything inside everything).

Splitting strings using a delimiter in python

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

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

How to download a file via FTP with Python ftplib

Please note if you are downloading from the FTP to your local, you will need to use the following:

with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

Otherwise, the script will at your local file storage rather than the FTP.

I spent a few hours making the mistake myself.

Script below:

import ftplib

# Open the FTP connection
ftp = ftplib.FTP()
ftp.cwd('/where/files-are/located')


filenames = ftp.nlst()

for filename in filenames:

    with open( filename, 'wb' ) as file :
        ftp.retrbinary('RETR %s' % filename, file.write)

        file.close()

ftp.quit()

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

What is the best way to determine a session variable is null or empty in C#?

In my opinion, the easiest way to do this that is clear and easy to read is:

 String sVar = (string)(Session["SessionVariable"] ?? "Default Value");

It may not be the most efficient method, since it casts the default string value even in the case of the default (casting a string as string), but if you make it a standard coding practice, you find it works for all data types, and is easily readable.

For example (a totally bogus example, but it shows the point):

 DateTime sDateVar = (datetime)(Session["DateValue"] ?? "2010-01-01");
 Int NextYear = sDateVar.Year + 1;
 String Message = "The Procrastinators Club will open it's doors Jan. 1st, " +
                  (string)(Session["OpeningDate"] ?? NextYear);

I like the Generics option, but it seems like overkill unless you expect to need this all over the place. The extensions method could be modified to specifically extend the Session object so that it has a "safe" get option like Session.StringIfNull("SessionVar") and Session["SessionVar"] = "myval"; It breaks the simplicity of accessing the variable via Session["SessionVar"], but it is clean code, and still allows validating if null or if string if you need it.

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

Use a negative lookahead and a negative lookbehind:

> s = "one two 3.4 5,6 seven.eight nine,ten"
> parts = re.split('\s|(?<!\d)[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten']

In other words, you always split by \s (whitespace), and only split by commas and periods if they are not followed (?!\d) or preceded (?<!\d) by a digit.

DEMO.

EDIT: As per @verdesmarald comment, you may want to use the following instead:

> s = "one two 3.4 5,6 seven.eight nine,ten,1.2,a,5"
> print re.split('\s|(?<!\d)[,.]|[,.](?!\d)', s)
['one', 'two', '3.4', '5,6', 'seven', 'eight', 'nine', 'ten', '1.2', 'a', '5']

This will split "1.2,a,5" into ["1.2", "a", "5"].

DEMO.

Move / Copy File Operations in Java

Not yet, but the New NIO (JSR 203) will have support for these common operations.

In the meantime, there are a few things to keep in mind.

File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.

When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.

CSS3 Fade Effect

The scrolling effect is cause by specifying the generic 'background' property in your css instead of the more specific background-image. By setting the background property, the animation will transition between all properties.. Background-Color, Background-Image, Background-Position.. Etc Thus causing the scrolling effect..

E.g.

a {
-webkit-transition-property: background-image 300ms ease-in 200ms;
-moz-transition-property: background-image 300ms ease-in 200ms;
-o-transition-property: background-image 300ms ease-in 200ms;
transition: background-image 300ms ease-in 200ms;
}

"Find next" in Vim

As discussed, there are several ways to search:

/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)

plus, navigating prev/next with N and n.

You can also edit/recall your search history by pulling up the search prompt with / and then cycle with C-p/C-n. Even more useful is q/, which takes you to a window where you can navigate the search history.

Also for consideration is the all-important 'hlsearch' (type :hls to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:

hi Search ctermfg=yellow ctermbg=red guifg=...

But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh. This is so common that a mapping is in order:

nmap <leader>z :noh<CR>

I easily remember this one as z since I used to constantly type /zz<CR> (which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh mapping is way better.

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

Disable color change of anchor tag when visited

For :hover to override :visited, and to make sure :visited is the same as the initial color, :hover must come after :visited.

So if you want to disable the color change, a:visited must come before a:hover. Like this:

a { color: gray; }
a:visited { color: orange; }
a:hover { color: red; }

To disable :visited change you would style it with non-pseudo class:

a, a:visited { color: gray; }
a:hover { color: red; }

What is the python "with" statement designed for?

An example of an antipattern might be to use the with inside a loop when it would be more efficient to have the with outside the loop

for example

for row in lines:
    with open("outfile","a") as f:
        f.write(row)

vs

with open("outfile","a") as f:
    for row in lines:
        f.write(row)

The first way is opening and closing the file for each row which may cause performance problems compared to the second way with opens and closes the file just once.

Get the year from specified date php

I would use this:

$parts = explode('-', '2068-06-15');
echo $parts[0];

It appears the date is coming from a source where it is always the same, much quicker this way using explode.

How can you print a variable name in python?

You can't, as there are no variables in Python but only names.

For example:

> a = [1,2,3]
> b = a
> a is b
True

Which of those two is now the correct variable? There's no difference between a and b.

There's been a similar question before.

select the TOP N rows from a table

select * from table_name LIMIT 100

remember this only works with MYSQL

How can I clear the Scanner buffer in Java?

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

in = new Scanner(System.in);

If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

(The above approach is specific to System.in. It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

Can I use jQuery with Node.js?

Yes, jQuery can be used with Node.js.

Steps to include jQuery in node project:-

npm i jquery --save Include jquery in codes

import jQuery from 'jquery';

const $ = jQuery;

I do use jquery in node.js projects all the time specifically in the chrome extension's project.

e.g. https://github.com/fxnoob/gesture-control-chrome-extension/blob/master/src/default_plugins/tab.js

How to enable CORS in ASP.NET Core

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAnyOrigin",
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
    });

    services.Configure<MvcOptions>(options => {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
    });            
}

TypeScript and array reduce function

It's actually the JavaScript array reduce function rather than being something specific to TypeScript.

As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

Here's an example which sums up the values of an array:

_x000D_
_x000D_
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
_x000D_
_x000D_

The snippet should produce 6.

How to set transparent background for Image Button in code?

Do it in your xml

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtonSettings"
        android:layout_gravity="right|bottom"
        android:src="@drawable/tabbar_settings_icon"
        android:background="@android:color/transparent"/>

How do I remove a CLOSE_WAIT socket connection

I'm also having the same issue with a very latest Tomcat server (7.0.40). It goes non-responsive once for a couple of days.

To see open connections, you may use:

sudo netstat -tonp | grep jsvc | grep --regexp="127.0.0.1:443" --regexp="127.0.0.1:80" | grep CLOSE_WAIT

As mentioned in this post, you may use /proc/sys/net/ipv4/tcp_keepalive_time to view the values. The value seems to be in seconds and defaults to 7200 (i.e. 2 hours).

To change them, you need to edit /etc/sysctl.conf.

Open/create `/etc/sysctl.conf`
Add `net.ipv4.tcp_keepalive_time = 120` and save the file
Invoke `sysctl -p /etc/sysctl.conf`
Verify using `cat /proc/sys/net/ipv4/tcp_keepalive_time`

Windows Batch: How to add Host-Entries?

Plain typo. hostspath vs hostpath ;)

@echo off 

set `hostspath`=%windir%\System32\drivers\etc\hosts 

echo 62.116.159.4 ns1.intranet.de >> `%hostspath%`   
echo 217.160.113.37 ns2.intranet.de >> `%hostpath%`  
echo 89.146.248.4 ns3.intranet.de >> `%hostpath%`   
echo 74.208.254.4 ns4.intranet.de >> `%hostpath%`   

exit 

Apache could not be started - ServerRoot must be a valid directory and Unable to find the specified module

If you open an editor and jump to the exact line shown in the error message (within the file httpd.conf), this is what you'd see:

#LoadModule access_compat_module modules/mod_access_compat.so
LoadModule actions_module modules/mod_actions.so
LoadModule alias_module modules/mod_alias.so
LoadModule allowmethods_module modules/mod_allowmethods.so
LoadModule asis_module modules/mod_asis.so
LoadModule auth_basic_module modules/mod_auth_basic.so
#LoadModule auth_digest_module modules/mod_auth_digest.so
#LoadModule auth_form_module modules/mod_auth_form.so

The paths to the modules, e.g. modules/mod_actions.so, are all stated relatively, and they are relative to the value set by ServerRoot. ServerRoot is defined at the top of httpd.conf (ctrl-F for ServerRoot ").

ServerRoot is usually set absolutely, which would be K:/../../../xampp/apache/ in your post.

But it can also be set relatively, relative to the working directory (cf.). If the working directory is the Apache bin folder, then use this line in your httpd.conf:

ServerRoot ../

If the working directory is the Apache folder, then this would suffice:

ServerRoot .

If the working directory is the C: folder (one folder above the Apache folder), then use this:

ServerRoot Apache

For apache services, the working directory would be C:\Windows\System32, so use this:

ServerRoot ../../Apache

How to preventDefault on anchor tags?

You can do as follows

1.Remove href attribute from anchor(a) tag

2.Set pointer cursor in css to ng click elements

 [ng-click],
 [data-ng-click],
 [x-ng-click] {
     cursor: pointer;
 }

Hibernate: How to set NULL query-parameter value with HQL?

You can use

Restrictions.eqOrIsNull("status", status)

insted of

status == null ? Restrictions.isNull("status") : Restrictions.eq("status", status)

How to add items to a spinner in Android?

It's just to clear the adapter, add all itens and notify change like below:

  public void show(List<Object> objLIst) {
    adapter.clear();
    adapter.addAll(objLIst);
    adapter.notifyDataSetChanged(); }

Regex AND operator

Maybe just an OR operator | could be enough for your problem:

String: foo,bar,baz

Regex: (foo)|(baz)

Result: ["foo", "baz"]

How to format DateTime in Flutter , How to get current time in flutter?

Here's my simple solution. That does not require any dependency.

However, the date will be in string format. If you want the time then change the substring values

print(new DateTime.now()
            .toString()
            .substring(0,10)
     );   // 2020-06-10

Add a new line to the end of a JtextArea

When you want to create a new line or wrap in your TextArea you have to add \n (newline) after the text.

TextArea t = new TextArea();
t.setText("insert text when you want a new line add \nThen more text....);
setBounds();
setFont();
add(t);

This is the only way I was able to do it, maybe there is a simpler way but I havent discovered that yet.

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

There's also AppGyver Steroids that unites PhoneGap and Native UI nicely.

With Steroids you can add things like native tabs, native navigation bar, native animations and transitions, native modal windows, native drawer/panel (facebooks side menu) etc. to your PhoneGap app.

Here's a demo: http://youtu.be/oXWwDMdoTCk?t=20m17s

Open web in new tab Selenium + Python

You can achieve the opening/closing of a tab by the combination of keys COMMAND + T or COMMAND + W (OSX). On other OSs you can use CONTROL + T / CONTROL + W.

In selenium you can emulate such behavior. You will need to create one webdriver and as many tabs as the tests you need.

Here it is the code.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://www.google.com/")

#open tab
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 't') 
# You can use (Keys.CONTROL + 't') on other OSs

# Load a page 
driver.get('http://stackoverflow.com/')
# Make the tests...

# close the tab
# (Keys.CONTROL + 'w') on other OSs.
driver.find_element_by_tag_name('body').send_keys(Keys.COMMAND + 'w') 


driver.close()

How to find SQL Server running port?

This is the one that works for me:

SELECT DISTINCT 
    local_tcp_port 
FROM sys.dm_exec_connections 
WHERE local_tcp_port IS NOT NULL 

Errors: Data path ".builders['app-shell']" should have required property 'class'

You can simply audit your code and then

#sudo su 
rm -rf package-lock.json node_modules
sudo npm i --save 

What is a method group in C#?

Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup).

So, for example, I have:

private string DoSomethingToMyString(string input)
{
    // blah
}

Instead of explicitly stating the variable to be used like this:

public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(str => DoSomethingToMyString(str));
}

I can just omit the name of the var:

public List<string> GetStringStuff()
{
    return something.getStringsFromSomewhere.Select(DoSomethingToMyString);
}

Is there a unique Android device ID?

To get a user id you can use Google Play Licensing Library.

To download this library open SDK Manager => SDK Tools. The path to downloaded library files is:

path_to_android_sdk_on_your_pc/extras/google/market_licensing/library

Include the library in your project (you can simply copy its files).

Next you need some implementation of Policy interface (you can simply use one of two files from the library: ServerManagedPolicy or StrictPolicy).

User id will be provided for you inside processServerResponse() function:

public void processServerResponse(int response, ResponseData rawData) {
    if(rawData != null) {
        String userId = rawData.userId
        // use/save the value
    }
    // ...
}

Next you need to construct the LicenseChecker with a policy and call checkAccess() function. Use MainActivity.java as an example of how to do it. MainActivity.java is located inside this folder:

path_to_android_sdk_on_your_pc/extras/google/market_licensing/sample/src/com/example/android/market/licensing

Don't forget to add CHECK_LICENSE permission to your AndroidManifest.xml.

More about Licensing Library: https://developer.android.com/google/play/licensing

What is the difference between public, private, and protected?

private - can be accessed from WITHIN the class only

protected - can be accessed from WITHIN the class and INHERITING classes

public - can be accessed from code OUTSIDE the class as well

This applies to functions as well as variables.

How do I deal with corrupted Git object files?

You can use "find" for remove all files in the /objects directory with 0 in size with the command:

find .git/objects/ -size 0 -delete

Backup is recommended.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

This can happen when trigger(s) execute additional DML (data modification) queries which affect the row counts. My solution was to add the following at the top of my trigger:

SET NOCOUNT ON;

Split string into individual words Java

Yet another method, using StringTokenizer :

String s = "I want to walk my dog";
StringTokenizer tokenizer = new StringTokenizer(s);

while(tokenizer.hasMoreTokens()) {
    System.out.println(tokenizer.nextToken());
}

How to square all the values in a vector in R?

This will also work

newData <- data*data

How to sort an array of objects by multiple fields?

Sorting on two date fields and a numeric field example:

var generic_date =  new Date(2070, 1, 1);
checkDate = function(date) {
  return Date.parse(date) ? new Date(date): generic_date;
}

function sortData() {  
  data.sort(function(a,b){
    var deltaEnd = checkDate(b.end) - checkDate(a.end);
    if(deltaEnd) return deltaEnd;

    var deltaRank = a.rank - b.rank;
    if (deltaRank) return deltaRank;

    var deltaStart = checkDate(b.start) - checkDate(a.start);
    if(deltaStart) return deltaStart;

    return 0;
  });
}

http://jsfiddle.net/hcWgf/57/