Programs & Examples On #N dimensional

Random / noise functions for GLSL

I have translated one of Ken Perlin's Java implementations into GLSL and used it in a couple projects on ShaderToy.

Below is the GLSL interpretation I did:

int b(int N, int B) { return N>>B & 1; }
int T[] = int[](0x15,0x38,0x32,0x2c,0x0d,0x13,0x07,0x2a);
int A[] = int[](0,0,0);

int b(int i, int j, int k, int B) { return T[b(i,B)<<2 | b(j,B)<<1 | b(k,B)]; }

int shuffle(int i, int j, int k) {
    return b(i,j,k,0) + b(j,k,i,1) + b(k,i,j,2) + b(i,j,k,3) +
        b(j,k,i,4) + b(k,i,j,5) + b(i,j,k,6) + b(j,k,i,7) ;
}

float K(int a, vec3 uvw, vec3 ijk)
{
    float s = float(A[0]+A[1]+A[2])/6.0;
    float x = uvw.x - float(A[0]) + s,
        y = uvw.y - float(A[1]) + s,
        z = uvw.z - float(A[2]) + s,
        t = 0.6 - x * x - y * y - z * z;
    int h = shuffle(int(ijk.x) + A[0], int(ijk.y) + A[1], int(ijk.z) + A[2]);
    A[a]++;
    if (t < 0.0)
        return 0.0;
    int b5 = h>>5 & 1, b4 = h>>4 & 1, b3 = h>>3 & 1, b2= h>>2 & 1, b = h & 3;
    float p = b==1?x:b==2?y:z, q = b==1?y:b==2?z:x, r = b==1?z:b==2?x:y;
    p = (b5==b3 ? -p : p); q = (b5==b4 ? -q : q); r = (b5!=(b4^b3) ? -r : r);
    t *= t;
    return 8.0 * t * t * (p + (b==0 ? q+r : b2==0 ? q : r));
}

float noise(float x, float y, float z)
{
    float s = (x + y + z) / 3.0;  
    vec3 ijk = vec3(int(floor(x+s)), int(floor(y+s)), int(floor(z+s)));
    s = float(ijk.x + ijk.y + ijk.z) / 6.0;
    vec3 uvw = vec3(x - float(ijk.x) + s, y - float(ijk.y) + s, z - float(ijk.z) + s);
    A[0] = A[1] = A[2] = 0;
    int hi = uvw.x >= uvw.z ? uvw.x >= uvw.y ? 0 : 1 : uvw.y >= uvw.z ? 1 : 2;
    int lo = uvw.x <  uvw.z ? uvw.x <  uvw.y ? 0 : 1 : uvw.y <  uvw.z ? 1 : 2;
    return K(hi, uvw, ijk) + K(3 - hi - lo, uvw, ijk) + K(lo, uvw, ijk) + K(0, uvw, ijk);
}

I translated it from Appendix B from Chapter 2 of Ken Perlin's Noise Hardware at this source:

https://www.csee.umbc.edu/~olano/s2002c36/ch02.pdf

Here is a public shade I did on Shader Toy that uses the posted noise function:

https://www.shadertoy.com/view/3slXzM

Some other good sources I found on the subject of noise during my research include:

https://thebookofshaders.com/11/

https://mzucker.github.io/html/perlin-noise-math-faq.html

https://rmarcus.info/blog/2018/03/04/perlin-noise.html

http://flafla2.github.io/2014/08/09/perlinnoise.html

https://mrl.nyu.edu/~perlin/noise/

https://rmarcus.info/blog/assets/perlin/perlin_paper.pdf

https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch05.html

I highly recommend the book of shaders as it not only provides a great interactive explanation of noise, but other shader concepts as well.

EDIT:

Might be able to optimize the translated code by using some of the hardware-accelerated functions available in GLSL. Will update this post if I end up doing this.

How to iterate over a column vector in Matlab?

If you just want to apply a function to each element and put the results in an output array, you can use arrayfun.

As others have pointed out, for most operations, it's best to avoid loops in MATLAB and vectorise your code instead.

Angles between two n-dimensional vectors in Python

For the few who may have (due to SEO complications) ended here trying to calculate the angle between two lines in python, as in (x0, y0), (x1, y1) geometrical lines, there is the below minimal solution (uses the shapely module, but can be easily modified not to):

from shapely.geometry import LineString
import numpy as np

ninety_degrees_rad = 90.0 * np.pi / 180.0

def angle_between(line1, line2):
    coords_1 = line1.coords
    coords_2 = line2.coords

    line1_vertical = (coords_1[1][0] - coords_1[0][0]) == 0.0
    line2_vertical = (coords_2[1][0] - coords_2[0][0]) == 0.0

    # Vertical lines have undefined slope, but we know their angle in rads is = 90° * p/180
    if line1_vertical and line2_vertical:
        # Perpendicular vertical lines
        return 0.0
    if line1_vertical or line2_vertical:
        # 90° - angle of non-vertical line
        non_vertical_line = line2 if line1_vertical else line1
        return abs((90.0 * np.pi / 180.0) - np.arctan(slope(non_vertical_line)))

    m1 = slope(line1)
    m2 = slope(line2)

    return np.arctan((m1 - m2)/(1 + m1*m2))

def slope(line):
    # Assignments made purely for readability. One could opt to just one-line return them
    x0 = line.coords[0][0]
    y0 = line.coords[0][1]
    x1 = line.coords[1][0]
    y1 = line.coords[1][1]
    return (y1 - y0) / (x1 - x0)

And the use would be

>>> line1 = LineString([(0, 0), (0, 1)]) # vertical
>>> line2 = LineString([(0, 0), (1, 0)]) # horizontal
>>> angle_between(line1, line2)
1.5707963267948966
>>> np.degrees(angle_between(line1, line2))
90.0

Detect if a NumPy array contains at least one non-numeric value?

(np.where(np.isnan(A)))[0].shape[0] will be greater than 0 if A contains at least one element of nan, A could be an n x m matrix.

Example:

import numpy as np

A = np.array([1,2,4,np.nan])

if (np.where(np.isnan(A)))[0].shape[0]: 
    print "A contains nan"
else:
    print "A does not contain nan"

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You want to simulate n-nested for loops.

Iterating through n-dimmensional array can be seen as increasing the n-digit number.

At each dimmension we have as many digits as the lenght of the dimmension.

Example:

Suppose we had array(matrix)

int[][][] T=new int[3][4][5];

in "for notation" we have:

for(int x=0;x<3;x++)
   for(int y=0;y<4;y++)
       for(int z=0;z<5;z++)
          T[x][y][z]=...

to simulate this you would have to use the "n-digit number notation"

We have 3 digit number, with 3 digits for first, 4 for second and five for third digit

We have to increase the number, so we would get the sequence

0 0 0
0 0 1
0 0 2    
0 0 3
0 0 4
0 1 0
0 1 1
0 1 2
0 1 3
0 1 4
0 2 0
0 2 1
0 2 2
0 2 3
0 2 4
0 3 0
0 3 1
0 3 2
0 3 3
0 3 4
and so on

So you can write the code for increasing such n-digit number. You can do it in such way that you can start with any value of the number and increase/decrease the digits by any numbers. That way you can simulate nested for loops that begin somewhere in the table and finish not at the end.

This is not an easy task though. I can't help with the matlab notation unfortunaly.

Calculating a 2D Vector's Cross Product

A useful 2D vector operation is a cross product that returns a scalar. I use it to see if two successive edges in a polygon bend left or right.

From the Chipmunk2D source:

/// 2D vector cross product analog.
/// The cross product of 2D vectors results in a 3D vector with only a z component.
/// This function returns the magnitude of the z value.
static inline cpFloat cpvcross(const cpVect v1, const cpVect v2)
{
        return v1.x*v2.y - v1.y*v2.x;
}

Git Symlinks in Windows

It ought to be implemented in msysgit, but there are two downsides:

  • Symbolic links are only available in Windows Vista and later (should not be an issue in 2011, and yet it is...), since older versions only support directory junctions.
  • (the big one) Microsoft considers symbolic links a security risk and so only administrators can create them by default. You'll need to elevate privileges of the git process or use fstool to change this behavior on every machine you work on.

I did a quick search and there is work being actively done on this, see issue 224.

How to force a checkbox and text on the same line?

Another way to do this solely with css:

input[type='checkbox'] {
  float: left;
  width: 20px;
}
input[type='checkbox'] + label {
  display: block;
  width: 30px;
}

Note that this forces each checkbox and its label onto a separate line, rather than only doing so only when there's overflow.

When is std::weak_ptr useful?

When using pointers it's important to understand the different types of pointers available and when it makes sense to use each one. There are four types of pointers in two categories as follows:

  • Raw pointers:
    • Raw Pointer [ i.e. SomeClass* ptrToSomeClass = new SomeClass(); ]
  • Smart pointers:
    • Unique Pointers [ i.e.
      std::unique_ptr<SomeClass> uniquePtrToSomeClass ( new SomeClass() );
      ]
    • Shared Pointers [ i.e.
      std::shared_ptr<SomeClass> sharedPtrToSomeClass ( new SomeClass() );
      ]
    • Weak Pointers [ i.e.
      std::weak_ptr<SomeClass> weakPtrToSomeWeakOrSharedPtr ( weakOrSharedPtr );
      ]

Raw pointers (sometimes referred to as "legacy pointers", or "C pointers") provide 'bare-bones' pointer behavior and are a common source of bugs and memory leaks. Raw pointers provide no means for keeping track of ownership of the resource and developers must call 'delete' manually to ensure they are not creating a memory leak. This becomes difficult if the resource is shared as it can be challenging to know whether any objects are still pointing to the resource. For these reasons, raw pointers should generally be avoided and only used in performance-critical sections of the code with limited scope.

Unique pointers are a basic smart pointer that 'owns' the underlying raw pointer to the resource and is responsible for calling delete and freeing the allocated memory once the object that 'owns' the unique pointer goes out of scope. The name 'unique' refers to the fact that only one object may 'own' the unique pointer at a given point in time. Ownership may be transferred to another object via the move command, but a unique pointer can never be copied or shared. For these reasons, unique pointers are a good alternative to raw pointers in the case that only one object needs the pointer at a given time, and this alleviates the developer from the need to free memory at the end of the owning object's lifecycle.

Shared pointers are another type of smart pointer that are similar to unique pointers, but allow for many objects to have ownership over the shared pointer. Like unique pointer, shared pointers are responsible for freeing the allocated memory once all objects are done pointing to the resource. It accomplishes this with a technique called reference counting. Each time a new object takes ownership of the shared pointer the reference count is incremented by one. Similarly, when an object goes out of scope or stops pointing to the resource, the reference count is decremented by one. When the reference count reaches zero, the allocated memory is freed. For these reasons, shared pointers are a very powerful type of smart pointer that should be used anytime multiple objects need to point to the same resource.

Finally, weak pointers are another type of smart pointer that, rather than pointing to a resource directly, they point to another pointer (weak or shared). Weak pointers can't access an object directly, but they can tell whether the object still exists or if it has expired. A weak pointer can be temporarily converted to a shared pointer to access the pointed-to object (provided it still exists). To illustrate, consider the following example:

  • You are busy and have overlapping meetings: Meeting A and Meeting B
  • You decide to go to Meeting A and your co-worker goes to Meeting B
  • You tell your co-worker that if Meeting B is still going after Meeting A ends, you will join
  • The following two scenarios could play out:
    • Meeting A ends and Meeting B is still going, so you join
    • Meeting A ends and Meeting B has also ended, so you can't join

In the example, you have a weak pointer to Meeting B. You are not an "owner" in Meeting B so it can end without you, and you do not know whether it ended or not unless you check. If it hasn't ended, you can join and participate, otherwise, you cannot. This is different than having a shared pointer to Meeting B because you would then be an "owner" in both Meeting A and Meeting B (participating in both at the same time).

The example illustrates how a weak pointer works and is useful when an object needs to be an outside observer, but does not want the responsibility of sharing ownership. This is particularly useful in the scenario that two objects need to point to each other (a.k.a. a circular reference). With shared pointers, neither object can be released because they are still 'strongly' pointed to by the other object. When one of the pointers is a weak pointer, the object holding the weak pointer can still access the other object when needed, provided it still exists.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

How to make nginx to listen to server_name:port

The server_namedocs directive is used to identify virtual hosts, they're not used to set the binding.

netstat tells you that nginx listens on 0.0.0.0:80 which means that it will accept connections from any IP.

If you want to change the IP nginx binds on, you have to change the listendocs rule.
So, if you want to set nginx to bind to localhost, you'd change that to:

listen 127.0.0.1:80;

In this way, requests that are not coming from localhost are discarded (they don't even hit nginx).

How do I view the SSIS packages in SQL Server Management Studio?

Came across SSIS package that schedule to run as sql job, you can identify where the SSIS package located by looking at the sql job properties; SQL job -> properties -> Steps (from select a page on left side) -> select job (from job list) -> edit -> job step properties shows up this got all the configuration for SSIS package, including its original path, in my case its under “MSDB”

Now connect to sql integration services; - open sql management studio - select server type to “integration services” - enter server name - you will see your SSIS package under “stored packages”

to edit the package right click and export to “file system” you’ll get file with extension .dtx it can be open in visual studio, I used the version visual studio 2012

How does facebook, gmail send the real time notification?

According to a slideshow about Facebook's Messaging system, Facebook uses the comet technology to "push" message to web browsers. Facebook's comet server is built on the open sourced Erlang web server mochiweb.

In the picture below, the phrase "channel clusters" means "comet servers".

System overview

Many other big web sites build their own comet server, because there are differences between every company's need. But build your own comet server on a open source comet server is a good approach.

You can try icomet, a C1000K C++ comet server built with libevent. icomet also provides a JavaScript library, it is easy to use as simple as:

var comet = new iComet({
    sign_url: 'http://' + app_host + '/sign?obj=' + obj,
    sub_url: 'http://' + icomet_host + '/sub',
    callback: function(msg){
        // on server push
        alert(msg.content);
    }
});

icomet supports a wide range of Browsers and OSes, including Safari(iOS, Mac), IEs(Windows), Firefox, Chrome, etc.

How can I change the color of my prompt in zsh (different from normal text)?

Put this in ~/.zshrc:

autoload -U colors && colors
PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%~ %{$reset_color%}%% "

Supported Colors:
red, blue, green, cyan, yellow, magenta, black, & white (from this answer) although different computers may have different valid options.

Surround color codes (and any other non-printable chars) with %{....%}. This is for the text wrapping to work correctly.

Additionally, here is how you can get this to work with the directory-trimming from here.

PS1="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg[yellow]%}%(5~|%-1~/.../%3~|%4~) %{$reset_color%}%% "

RESTful call in Java

You can use Async Http Client (The library also supports the WebSocket Protocol) like that:

    String clientChannel = UriBuilder.fromPath("http://localhost:8080/api/{id}").build(id).toString();

    try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient())
    {
        BoundRequestBuilder postRequest = asyncHttpClient.preparePost(clientChannel);
        postRequest.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        postRequest.setBody(message.toString()); // returns JSON
        postRequest.execute().get();
    }

subquery in codeigniter active record

It may be a little late for the original question but for future queries this might help. Best way to achieve this is Get the result of the inner query to an array like this

$this->db->select('id');
$result = $this->db->get('your_table');
return  $result->result_array();

And then use than array in the following active record clause

$this->db->where_not_in('id_of_another_table', 'previously_returned_array');

Hope this helps

index.php not loading by default

After reading all this and trying to fix it, I got a simple solution on ubuntu forum (https://help.ubuntu.com/community/ApacheMySQLPHP). The problem lies with libapache2-mod-php5 module. Thats why the browser downloads the index.php file rather than showing the web page. Do the following. If sudo a2enmod php5 returns module does not exist then the problem is with libapache2-mod-php5. Purge remove the module with command sudo apt-get --purge remove libapache2-mod-php5 Then install it again sudo apt-get install libapache2-mod-php5

Undo working copy modifications of one file in Git?

I always get confused with this, so here is a reminder test case; let's say we have this bash script to test git:

set -x
rm -rf test
mkdir test
cd test
git init
git config user.name test
git config user.email [email protected]
echo 1 > a.txt
echo 1 > b.txt
git add *
git commit -m "initial commit"
echo 2 >> b.txt
git add b.txt
git commit -m "second commit"
echo 3 >> b.txt

At this point, the change is not staged in the cache, so git status is:

$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

If from this point, we do git checkout, the result is this:

$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean

If instead we do git reset, the result is:

$ git reset HEAD -- b.txt
Unstaged changes after reset:
M   b.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

So, in this case - if the changes are not staged, git reset makes no difference, while git checkout overwrites the changes.


Now, let's say that the last change from the script above is staged/cached, that is to say we also did git add b.txt at the end.

In this case, git status at this point is:

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    modified:   b.txt

If from this point, we do git checkout, the result is this:

$ git checkout HEAD -- b.txt
$ git status
On branch master
nothing to commit, working directory clean

If instead we do git reset, the result is:

$ git reset HEAD -- b.txt
Unstaged changes after reset:
M   b.txt
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   b.txt

no changes added to commit (use "git add" and/or "git commit -a")

So, in this case - if the changes are staged, git reset will basically make staged changes into unstaged changes - while git checkout will overwrite the changes completely.

PreparedStatement with list of parameters in a IN clause

What you can do is dynamically build the select string (the 'IN (?)' part) by a simple for loop as soon as you know how many values you need to put inside the IN clause. You can then instantiate the PreparedStatement.

Stored procedure or function expects parameter which is not supplied

I came across this issue yesterday, but none of the solutions here worked exactly, however they did point me in the right direction.

Our application is a workflow tool written in C# and, overly simplified, has several stored procedures on the database, as well as a table of metadata about each parameter used by each stored procedure (name, order, data type, size, etc), allowing us to create as many new stored procedures as we need without having to change the C#.

Analysis of the problem showed that our code was setting all the correct parameters on the SqlCommand object, however once it was executed, it threw the same error as the OP got.

Further analysis revealed that some parameters had a value of null. I therefore must draw the conclusion that SqlCommand objects ignore any SqlParameter object in their .Parameters collection with a value of null.

There are two solutions to this problem that I found.

  1. In our stored procedures, give a default value to each parameter, so from @Parameter int to @Parameter int = NULL (or some other default value as required).

  2. In our code that generates the individual SqlParameter objects, assigning DBNull.Value instead of null where the intended value is a SQL NULL does the trick.

The original coder has moved on and the code was originally written with Solution 1 in mind, and having weighed up the benefits of both, I think I'll stick with Solution 1. It's much easier to specify a default value for a specific stored procedure when writing it, rather than it always being NULL as defined in the code.

Hope that helps someone.

Multiple bluetooth connection

Have you looked into the BluetoothAdapter Android class? You set up one device as a server and the other as a client. It may be possible (although I haven't looked into it myself) to connect multiple clients to the server.

I have had success connecting a BlueTooth audio device to a phone while it also had this BluetoothAdapter connection to another phone, but I haven't tried with three phones. At least this tells me that the Bluetooth radio can tolerate multiple simultaneous connections :)

How to use AND in IF Statement

If you are simply looking for the occurrence of "Miami" or "Florida" inside a string (since you put * at both ends), it's probably better to use the InStr function instead of Like. Not only are the results more predictable, but I believe you'll get better performance.

Also, VBA is not short-circuited so when you use the AND keyword, it will test both sides of the AND, regardless if the first test failed or not. In VBA, it is more optimal to use 2 if-statements in these cases, that way you aren't checking for "Florida" if you don't find "Miami".

The other advice I have is that a for-each loop is faster than a for-loop. Using .offset, you can achieve the same thing, but with better effeciency. Of course there are even better ways (like variant arrays), but those will add a layer of complexity not needed in this example.

Here is some sample code:

Sub test()

Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row

For Each cell In Range("A1:A" & lastRow)
    If InStr(1, cell.Value, "Miami") <> 0 Then
        If InStr(1, cell.Offset(, 3).Value, "Florida") <> 0 Then
            cell.Offset(, 2).Value = "BA"
        End If
    End If
Next

Application.ScreenUpdating = True
End Sub

I hope you find some of this helpful, and keep at it with VBA! ^^

How to remove the default arrow icon from a dropdown list (select element)?

There's no need for hacks or overflow. There's a pseudo-element for the dropdown arrow on IE:

select::-ms-expand {
    display: none;
}

Determine if JavaScript value is an "integer"?

Try this:

if(Math.floor(id) == id && $.isNumeric(id)) 
  alert('yes its an int!');

$.isNumeric(id) checks whether it's numeric or not
Math.floor(id) == id will then determine if it's really in integer value and not a float. If it's a float parsing it to int will give a different result than the original value. If it's int both will be the same.

How to pass the password to su/sudo/ssh without overriding the TTY?

Set SSH up for Public Key Authentication, with no pasphrase on the Key. Loads of guides on the net. You won't need a password to login then. You can then limit connections for a key based on client hostname. Provides reasonable security and is great for automated logins.

Linear regression with matplotlib / numpy

This code:

from scipy.stats import linregress

linregress(x,y) #x and y are arrays or lists.

gives out a list with the following:

slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate

Source

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

Alternative Windows shells, besides CMD.EXE?

I am a fan of Cmder, a package including clink, conemu, msysgit, and some cosmetic enhancements.

http://cmder.net/

https://github.com/cmderdev/cmder

https://chocolatey.org/packages/Cmder

enter image description here

How to remove carriage returns and new lines in Postgresql?

OP asked specifically about regexes since it would appear there's concern for a number of other characters as well as newlines, but for those just wanting strip out newlines, you don't even need to go to a regex. You can simply do:

select replace(field,E'\n','');

I think this is an SQL-standard behavior, so it should extend back to all but perhaps the very earliest versions of Postgres. The above tested fine for me in 9.4 and 9.2

Javascript .querySelector find <div> by innerTEXT

This solution does the following:

  • Uses the ES6 spread operator to convert the NodeList of all divs to an array.

  • Provides output if the div contains the query string, not just if it exactly equals the query string (which happens for some of the other answers). e.g. It should provide output not just for 'SomeText' but also for 'SomeText, text continues'.

  • Outputs the entire div contents, not just the query string. e.g. For 'SomeText, text continues' it should output that whole string, not just 'SomeText'.

  • Allows for multiple divs to contain the string, not just a single div.

_x000D_
_x000D_
[...document.querySelectorAll('div')]      // get all the divs in an array_x000D_
  .map(div => div.innerHTML)               // get their contents_x000D_
  .filter(txt => txt.includes('SomeText')) // keep only those containing the query_x000D_
  .forEach(txt => console.log(txt));       // output the entire contents of those
_x000D_
<div>SomeText, text continues.</div>_x000D_
<div>Not in this div.</div>_x000D_
<div>Here is more SomeText.</div>
_x000D_
_x000D_
_x000D_

How to install an npm package from GitHub directly?

You can also do npm install visionmedia/express to install from Github

or

npm install visionmedia/express#branch

There is also support for installing directly from a Gist, Bitbucket, Gitlab, and a number of other specialized formats. Look at the npm install documentation for them all.

Reverse a string without using reversed() or [::-1]?

Here is one using a list as a stack:

def reverse(s):
  rev = [_t for _t in s]
  t = ''
  while len(rev) != 0:
    t+=rev.pop()
  return t

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

How do I get a string format of the current date time, in python?

You can use the datetime module for working with dates and times in Python. The strftime method allows you to produce string representation of dates and times with a format you specify.

>>> import datetime
>>> datetime.date.today().strftime("%B %d, %Y")
'July 23, 2010'
>>> datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
'10:36AM on July 23, 2010'

Can Mockito stub a method without regard to the argument?

Use like this:

when(
  fooDao.getBar(
    Matchers.<Bazoo>any()
  )
).thenReturn(myFoo);

Before you need to import Mockito.Matchers

Is returning out of a switch statement considered a better practice than using break?

Neither, because both are quite verbose for a very simple task. You can just do:

let result = ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[opt] ?? 'Default'    // opt can be 1, 2, 3 or anything (default)

This, of course, also works with strings, a mix of both or without a default case:

let result = ({
  'first': 'One',
  'second': 'Two',
  3: 'Three'
})[opt]                // opt can be 'first', 'second' or 3

Explanation:

It works by creating an object where the options/cases are the keys and the results are the values. By putting the option into the brackets you access the value of the key that matches the expression via the bracket notation.

This returns undefined if the expression inside the brackets is not a valid key. We can detect this undefined-case by using the nullish coalescing operator ?? and return a default value.

Example:

_x000D_
_x000D_
console.log('Using a valid case:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[1] ?? 'Default')

console.log('Using an invalid case/defaulting:', ({
  1: 'One',
  2: 'Two',
  3: 'Three'
})[7] ?? 'Default')
_x000D_
.as-console-wrapper {max-height: 100% !important;top: 0;}
_x000D_
_x000D_
_x000D_

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

You can use the Logical NOT ! operator:

if (!$(this).parent().next().is('ul')){

Or equivalently (see comments below):

if (! ($(this).parent().next().is('ul'))){

For more information, see the Logical Operators section of the MDN docs.

Efficient way to do batch INSERTS with JDBC

The Statement gives you the following option:

Statement stmt = con.createStatement();

stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");
stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
stmt.addBatch("INSERT INTO emp_dept VALUES (1000, 260)");

// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();

Composer could not find a composer.json

  • Create a file called composer.json
  • Make sure the Composer can write in the directory you are looking for.
  • Update your composer.

    This worked for me

jQuery get textarea text

Normally, it's the value property

testArea.value

Or is there something I'm missing in what you need?

How to fire AJAX request Periodically?

Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here's how you might do it with setTimeout:

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

How do I download a file with Angular2 or greater

<a href="my_url" download="myfilename">Download file</a>

my_url should have the same origin, otherwise it will redirect to that location

Reading JSON POST using PHP

Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");

getUserLocation($ip_srv);

Function:

function getUserLocation($services) {

        $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout

        for ($i = 0; $i < count($services); $i++) {

            // Configuring curl options
            $options = array (
                CURLOPT_RETURNTRANSFER => true, // return web page
                //CURLOPT_HEADER => false, // don't return headers
                CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                CURLOPT_FOLLOWLOCATION => true, // follow redirects
                CURLOPT_ENCODING => "", // handle compressed
                CURLOPT_USERAGENT => "test", // who am i
                CURLOPT_AUTOREFERER => true, // set referer on redirect
                CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
                CURLOPT_TIMEOUT => 5, // timeout on response
                CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
            ); 

            // Initializing curl
            $ch = curl_init($services[$i]);
            curl_setopt_array ( $ch, $options );

            $content = curl_exec ( $ch );
            $err = curl_errno ( $ch );
            $errmsg = curl_error ( $ch );
            $header = curl_getinfo ( $ch );
            $httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

            curl_close ( $ch );

            //echo 'service: ' . $services[$i] . '</br>';
            //echo 'err: '.$err.'</br>';
            //echo 'errmsg: '.$errmsg.'</br>';
            //echo 'httpCode: '.$httpCode.'</br>';
            //print_r($header);
            //print_r(json_decode($content, true));

            if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {

                return json_decode($content, true);

            } 

        }
    }

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

The top answer is doing too much work and looks to be very slow for larger data sets. apply is slow and should be avoided if possible. ix is deprecated and should be avoided as well.

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index()

   A   B
1  1  20
3  2  40
4  3  10

Or simply group by all the other columns and take the max of the column you need. df.groupby('A', as_index=False).max()

How do you modify a CSS style in the code behind file for divs in ASP.NET?

If you're newing up an element with initializer syntax, you can do something like this:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Attributes = { ["style"] = "min-width: 35px;" }
    },
  }
};

Or if using the CssStyleCollection specifically:

var row = new HtmlTableRow
{
  Cells =
  {
    new HtmlTableCell
    {
        InnerText = text,
        Style = { ["min-width"] = "35px" }
    },
  }
};

Is it possible to serialize and deserialize a class in C++?

As far as "built-in" libraries go, the << and >> have been reserved specifically for serialization.

You should override << to output your object to some serialization context (usually an iostream) and >> to read data back from that context. Each object is responsible for outputting its aggregated child objects.

This method works fine so long as your object graph contains no cycles.

If it does, then you will have to use a library to deal with those cycles.

for each loop in groovy

Your code works fine.

def list = [["c":"d"], ["e":"f"], ["g":"h"]]
Map tmpHM = [1:"second (e:f)", 0:"first (c:d)", 2:"third (g:h)"]

for (objKey in tmpHM.keySet()) {   
    HashMap objHM = (HashMap) list.get(objKey);
    print("objHM: ${objHM}  , ")
}

prints objHM: [e:f] , objHM: [c:d] , objHM: [g:h] ,

See https://groovyconsole.appspot.com/script/5135817529884672

Then click "edit in console", "execute script"

Jenkins pipeline if else not working

        if ( params.build_deploy == '1' ) {
            println "build_deploy ? ${params.build_deploy}"
              jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                         string(name:'environment', value: "${params.environment}"),
                         string(name:'branch_name', value: "${params.branch_name}"),
                         string(name:'service_name', value: "${params.service_name}"),                      
                     ]
            println jobB.getResult()
        }

SQL Server default character encoding

If you need to know the default collation for a newly created database use:

SELECT SERVERPROPERTY('Collation')

This is the server collation for the SQL Server instance that you are running.

How do I determine the current operating system with Node.js

The variable to use would be process.platform

On Mac the variable returns darwin. On Windows, it returns win32 (even on 64 bit).

Current possible values are:

  • aix
  • darwin
  • freebsd
  • linux
  • openbsd
  • sunos
  • win32

I just set this at the top of my jakeFile:

var isWin = process.platform === "win32";

Bootstrap: How to center align content inside column?

You can do this by adding a div i.e. centerBlock. And give this property in CSS to center the image or any content. Here is the code:

<div class="container">
    <div class="row">
        <div class="col-sm-4 col-md-4 col-lg-4">
            <div class="centerBlock">
                <img class="img-responsive" src="img/some-image.png" title="This image needs to be centered">
            </div>
        </div>
        <div class="col-sm-8 col-md-8 col-lg-8">
            Some content not important at this moment
        </div>
    </div>
</div>


// CSS

.centerBlock {
  display: table;
  margin: auto;
}

How to test if string exists in file with Bash?

grep -Fxq "String to be found" | ls -a
  • grep will helps you to check content
  • ls will list all the Files

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Where does flask look for image files?

Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg in your static directory? If you move it to your static directory and update your HTML as such:

<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">

It should work.

Also, it is worth noting, there is a better way to structure this.

File structure:

app.py
static
   |----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
   |----index.html

app.py

from flask import Flask, render_template, url_for
app = Flask(__name__)

@app.route('/index', methods=['GET', 'POST'])
def lionel(): 
    return render_template('index.html')

if __name__ == '__main__':
    app.run()

templates/index.html

<html>
  <head>

  </head>
  <body>
    <h1>Hi Lionel Messi</h1>

  <img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />

  </body>

</html>

Doing it this way ensures that you are not hard-coding a URL path for your static assets.

The type arguments cannot be inferred from the usage. Try specifying the type arguments explicitly

I was actually searching for a similar error and Google sent me here to this question. The error was:

The type arguments for method 'IModelExpressionProvider.CreateModelExpression(ViewDataDictionary, Expression>)' cannot be inferred from the usage

I spent maybe 15 minutes trying to figure it out. It was happening inside a Razor .cshtml view file. I had to comment portions of the view code to get to where it was barking since the compiler didn't help much.

<div class="form-group col-2">
    <label asp-for="Organization.Zip"></label>
    <input asp-for="Organization.Zip" class="form-control">
    <span asp-validation-for="Zip" class="color-type-alert"></span>
</div>

Can you spot it? Yeah... I re-checked it maybe twice and didn't get it at first!

See that the ViewModel's property is just Zip when it should be Organization.Zip. That was it.

So re-check your view source code... :-)

Homebrew refusing to link OpenSSL

None of these solutions worked for me on OS X El Capitan 10.11.6. Probably because OS X has a native version of openssl that it believes is superior, and as such, does not like tampering.

So, I took the high road and started fresh...


Manually install and symlink

cd /usr/local/src  
  • If you're getting "No such file or directory", make it:

    cd /usr/local && mkdir src && cd src

Download openssl:

curl --remote-name https://www.openssl.org/source/openssl-1.0.2h.tar.gz

Extract and cd in:

tar -xzvf openssl-1.0.2h.tar.gz
cd openssl-1.0.2h

Compile and install:

./configure darwin64-x86_64-cc --prefix=/usr/local/openssl-1.0.2h shared
make depend
make
make install

Now symlink OS X's openssl to your new and updated openssl:

ln -s /usr/local/openssl-1.0.2h/bin/openssl /usr/local/bin/openssl

Close terminal, open a new session, and verify OS X is using your new openssl:

openssl version -a

How to make a form close when pressing the escape key?

If you have a cancel button on your form, you can set the Form.CancelButton property to that button and then pressing escape will effectively 'click the button'.

If you don't have such a button, check out the Form.KeyPreview property.

Changing the page title with Jquery

$(document).prop('title', 'test');

This is simply a JQuery wrapper for:

document.title = 'test';

To add a > periodically you can do:

function changeTitle() {
    var title = $(document).prop('title'); 
    if (title.indexOf('>>>') == -1) {
        setTimeout(changeTitle, 3000);  
        $(document).prop('title', '>'+title);
    }
}

changeTitle();

How to check whether a pandas DataFrame is empty?

I prefer going the long route. These are the checks I follow to avoid using a try-except clause -

  1. check if variable is not None
  2. then check if its a dataframe and
  3. make sure its not empty

Here, DATA is the suspect variable -

DATA is not None and isinstance(DATA, pd.DataFrame) and not DATA.empty

Concatenating strings in Razor

the plus works just fine, i personally prefer using the concat function.

var s = string.Concat(string 1, string 2, string, 3, etc)

How to consume REST in Java

If you also need to convert that xml string that comes as a response to the service call, an x object you need can do it as follows:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXB;
import javax.xml.bind.JAXBException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class RestServiceClient {

// http://localhost:8080/RESTfulExample/json/product/get
public static void main(String[] args) throws ParserConfigurationException,
SAXException {

try {

URL url = new URL(
    "http://localhost:8080/CustomerDB/webresources/co.com.mazf.ciudad");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");

if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
    + conn.getResponseCode());
}

BufferedReader br = new BufferedReader(new InputStreamReader(
    (conn.getInputStream())));

String output;

Ciudades ciudades = new Ciudades();
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println("12132312");
System.err.println(output);

DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);

    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);

    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

conn.disconnect();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "";
}
}

Note that the xml structure that I expected in the example was as follows:

<ciudad><idCiudad>1</idCiudad><nomCiudad>BOGOTA</nomCiudad></ciudad>

Safest way to run BAT file from Powershell script

@Rynant 's solution worked for me. I had a couple of additional requirements though:

  1. Don't PAUSE if encountered in bat file
  2. Optionally, append bat file output to log file

Here's what I got working (finally):

[PS script code]

& runner.bat bat_to_run.bat logfile.txt

[runner.bat]

@echo OFF

REM This script can be executed from within a powershell script so that the bat file
REM passed as %1 will not cause execution to halt if PAUSE is encountered.
REM If {logfile} is included, bat file output will be appended to logfile.
REM
REM Usage:
REM runner.bat [path of bat script to execute] {logfile}

if not [%2] == [] GOTO APPEND_OUTPUT
@echo | call %1
GOTO EXIT

:APPEND_OUTPUT
@echo | call %1  1> %2 2>&1

:EXIT

Read properties file outside JAR file

So, you want to treat your .properties file on the same folder as the main/runnable jar as a file rather than as a resource of the main/runnable jar. In that case, my own solution is as follows:

First thing first: your program file architecture shall be like this (assuming your main program is main.jar and its main properties file is main.properties):

./ - the root of your program
 |__ main.jar
 |__ main.properties

With this architecture, you can modify any property in the main.properties file using any text editor before or while your main.jar is running (depending on the current state of the program) since it is just a text-based file. For example, your main.properties file may contain:

app.version=1.0.0.0
app.name=Hello

So, when you run your main program from its root/base folder, normally you will run it like this:

java -jar ./main.jar

or, straight away:

java -jar main.jar

In your main.jar, you need to create a few utility methods for every property found in your main.properties file; let say the app.version property will have getAppVersion() method as follows:

/**
 * Gets the app.version property value from
 * the ./main.properties file of the base folder
 *
 * @return app.version string
 * @throws IOException
 */

import java.util.Properties;

public static String getAppVersion() throws IOException{

    String versionString = null;

    //to load application's properties, we use this class
    Properties mainProperties = new Properties();

    FileInputStream file;

    //the base folder is ./, the root of the main.properties file  
    String path = "./main.properties";

    //load the file handle for main.properties
    file = new FileInputStream(path);

    //load all the properties from this file
    mainProperties.load(file);

    //we have loaded the properties, so close the file handle
    file.close();

    //retrieve the property we are intrested, the app.version
    versionString = mainProperties.getProperty("app.version");

    return versionString;
}

In any part of the main program that needs the app.version value, we call its method as follows:

String version = null;
try{
     version = getAppVersion();
}
catch (IOException ioe){
    ioe.printStackTrace();
}

SQL distinct for 2 fields in a database

Share my stupid thought:

Maybe I can select distinct only on c1 but not on c2, so the syntax may be select ([distinct] col)+ where distinct is a qualifier for each column.

But after thought, I find that distinct on only one column is nonsense. Take the following relationship:

   | A | B
__________
  1| 1 | 2
  2| 1 | 1

If we select (distinct A), B, then what is the proper B for A = 1?

Thus, distinct is a qualifier for a statement.

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

include antiforgerytoken in ajax post ASP.NET MVC

In Asp.Net MVC when you use @Html.AntiForgeryToken() Razor creates a hidden input field with name __RequestVerificationToken to store tokens. If you want to write an AJAX implementation you have to fetch this token yourself and pass it as a parameter to the server so it can be validated.

Step 1: Get the token

var token = $('input[name="`__RequestVerificationToken`"]').val();

Step 2: Pass the token in the AJAX call

function registerStudent() {

var student = {     
    "FirstName": $('#fName').val(),
    "LastName": $('#lName').val(),
    "Email": $('#email').val(),
    "Phone": $('#phone').val(),
};

$.ajax({
    url: '/Student/RegisterStudent',
    type: 'POST',
    data: { 
     __RequestVerificationToken:token,
     student: student,
        },
    dataType: 'JSON',
    contentType:'application/x-www-form-urlencoded; charset=utf-8',
    success: function (response) {
        if (response.result == "Success") {
            alert('Student Registered Succesfully!')

        }
    },
    error: function (x,h,r) {
        alert('Something went wrong')
      }
})
};

Note: The content type should be 'application/x-www-form-urlencoded; charset=utf-8'

I have uploaded the project on Github; you can download and try it.

https://github.com/lambda2016/AjaxValidateAntiForgeryToken

Get domain name

If you want specific users to have access to all or part of the WMI object space, you need to permission them as shown here. Note that you have to be running on as an admin to perform this setting.

How to use sessions in an ASP.NET MVC 4 application?

Due to the stateless nature of the web, sessions are also an extremely useful way of persisting objects across requests by serialising them and storing them in a session.

A perfect use case of this could be if you need to access regular information across your application, to save additional database calls on each request, this data can be stored in an object and unserialised on each request, like so:

Our reusable, serializable object:

[Serializable]
public class UserProfileSessionData
{
    public int UserId { get; set; }

    public string EmailAddress { get; set; }

    public string FullName { get; set; }
}

Use case:

public class LoginController : Controller {

    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            var profileData = new UserProfileSessionData {
                UserId = model.UserId,
                EmailAddress = model.EmailAddress,
                FullName = model.FullName
            }

            this.Session["UserProfile"] = profileData;
        }
    }

    public ActionResult LoggedInStatusMessage()
    {
        var profileData = this.Session["UserProfile"] as UserProfileSessionData;

        /* From here you could output profileData.FullName to a view and
        save yourself unnecessary database calls */
    }

}

Once this object has been serialised, we can use it across all controllers without needing to create it or query the database for the data contained within it again.

Inject your session object using Dependency Injection

In a ideal world you would 'program to an interface, not implementation' and inject your serializable session object into your controller using your Inversion of Control container of choice, like so (this example uses StructureMap as it's the one I'm most familiar with).

public class WebsiteRegistry : Registry
{
    public WebsiteRegistry()
    {
        this.For<IUserProfileSessionData>().HybridHttpOrThreadLocalScoped().Use(() => GetUserProfileFromSession());   
    }

    public static IUserProfileSessionData GetUserProfileFromSession()
    {
        var session = HttpContext.Current.Session;
        if (session["UserProfile"] != null)
        {
            return session["UserProfile"] as IUserProfileSessionData;
        }

        /* Create new empty session object */
        session["UserProfile"] = new UserProfileSessionData();

        return session["UserProfile"] as IUserProfileSessionData;
    }
}

You would then register this in your Global.asax.cs file.

For those that aren't familiar with injecting session objects, you can find a more in-depth blog post about the subject here.

A word of warning:

It's worth noting that sessions should be kept to a minimum, large sessions can start to cause performance issues.

It's also recommended to not store any sensitive data in them (passwords, etc).

Checking host availability by using ping in bash scripts

You don't need the backticks in the if statement. You can use this check

if ping -c 1 some_ip_here &> /dev/null
then
  echo 1
else
  echo 0
fi

The if command checks the exit code of the following command (the ping). If the exit code is zero (which means that the command exited successfully) the then block will be executed. If it return a non-zero exit code, then the else block will be executed.

Setting a width and height on an A tag

You can also use display: inline-block. The advantage of this is that it will set the height and width like a block element but also set it inline so that you can have another a tag sitting right next to it, permitting the parent space.

You can find out more about display properties here

What's the difference between F5 refresh and Shift+F5 in Google Chrome browser?

It ignores the cached content when refreshing...

https://support.google.com/a/answer/3001912?hl=en

F5 or Control + R = Reload the current page
Control+Shift+R or Shift + F5 = Reload your current page, ignoring cached content

How to check whether a Storage item is set?

The getItem method in the WebStorage specification, explicitly returns null if the item does not exist:

... If the given key does not exist in the list associated with the object then this method must return null. ...

So, you can:

if (localStorage.getItem("infiniteScrollEnabled") === null) {
  //...
}

See this related question:

CSS3 Transition - Fade out effect

.fadeOut{
    background-color: rgba(255, 0, 0, 0.83);
    border-radius: 8px;
    box-shadow: silver 3px 3px 5px 0px;
    border: 2px dashed yellow;
    padding: 3px;
}
.fadeOut.end{
    transition: all 1s ease-in-out;
    background-color: rgba(255, 0, 0, 0.0);
    box-shadow: none;
    border: 0px dashed yellow;
    border-radius: 0px;
}

demo here.

How do I detect if Python is running as a 64-bit application?

import platform
platform.architecture()

From the Python docs:

Queries the given executable (defaults to the Python interpreter binary) for various architecture information.

Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.

NSURLErrorDomain error codes description

I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.

Summing elements in a list

def sumoflist(l):    
    total = 0    
    for i in l:
        total +=i
    return total

Strings in C, how to get subString

Generalized:

char* subString (const char* input, int offset, int len, char* dest)
{
  int input_len = strlen (input);

  if (offset + len > input_len)
  {
     return NULL;
  }

  strncpy (dest, input + offset, len);
  return dest;
}

char dest[80];
const char* source = "hello world";

if (subString (source, 0, 5, dest))
{
  printf ("%s\n", dest);
}

Is it possible to change the package name of an Android app on Google Play?

No, you cannot change package name unless you're okay with publishing it as a new app in Play Store:

Once you publish your application under its manifest package name, this is the unique identity of the application forever more. Switching to a different name results in an entirely new application, one that can’t be installed as an update to the existing application. Android manual confirms it as well here:

Caution: Once you publish your application, you cannot change the package name. The package name defines your application's identity, so if you change it, then it is considered to be a different application and users of the previous version cannot update to the new version. If you're okay with publishing new version of your app as a completely new entity, you can do it of course - just remove old app from Play Store (if you want) and publish new one, with different package name.

How to send custom headers with requests in Swagger UI?

DISCLAIMER: this solution is not using Header.

If someone is looking for a lazy-lazy manner (also in WebApi), I'd suggest:

public YourResult Authorize([FromBody]BasicAuthCredentials credentials)

You are not getting from header, but at least you have an easy alternative. You can always check the object for null and fallback to header mechanism.

Python Serial: How to use the read or readline function to read more than 1 character at a time

I use this small method to read Arduino serial monitor with Python

import serial
ser = serial.Serial("COM11", 9600)
while True:
     cc=str(ser.readline())
     print(cc[2:][:-5])

How to suppress binary file matching results in grep

There are three options, that you can use. -I is to exclude binary files in grep. Other are for line numbers and file names.

grep -I -n -H 


-I -- process a binary file as if it did not contain matching data; 
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match

So this might be a way to run grep:

grep -InH your-word *

Can't use Swift classes inside Objective-C

The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc, compile, then search for Swift.h in your Derived Data folder. You should find the Swift header there.

I had the problem, that Xcode renamed my my-Project-Swift.h to my_Project-Swift.h Xcode doesn't like "." "-" etc. symbols. With the method above you can find the filename and import it to a Objective-C class.

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

In Rails 3, 4, and 5 you can use:

Rails.application.routes.url_helpers

e.g.

Rails.application.routes.url_helpers.posts_path
Rails.application.routes.url_helpers.posts_url(:host => "example.com")

Bootstrap combining rows (rowspan)

Check this one. hope it will help full for you.

http://jsfiddle.net/j6amM/

.row-fix { margin-bottom:20px;}

.row-fix > [class*="span"]{ height:100px; background:#f1f1f1;}

.row-fix .two-col{ background:none;}

.two-col > [class*="col"]{ height:40px; background:#ccc;}

.two-col > .col1{margin-bottom:20px;}

javascript unexpected identifier

It looks like there is an extra curly bracket in the code.

function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        document.getElementById("content").innerHTML = xmlhttp.responseText;
    }
// extra bracket }
xmlhttp.open("GET", "data/" + id + ".html", true);
xmlhttp.send();
}

Iteration ng-repeat only X times in AngularJs

Angular comes with a limitTo:limit filter, it support limiting first x items and last x items:

<div ng-repeat="item in items|limitTo:4">{{item}}</div>

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

What is ANSI format?

When using single-byte characters, the ASCII format defines the first 127 characters. The extended characters from 128-255 are defined by various ANSI code pages to allow limited support for other languages. In order to make sense of an ANSI encoded string, you need to know which code page it uses.

How to set commands output as a variable in a batch file

To read a file...

set /P Variable=<File.txt

To Write a file

@echo %DataToWrite%>File.txt

note; having spaces before the <> character causes a space to be added at the end of the variable, also

To add to a file,like a logger program, First make a file with a single enter key in it called e.txt

set /P Data=<log0.log
set /P Ekey=<e.txt
@echo %Data%%Ekey%%NewData%>log0.txt

your log will look like this

Entry1
Entry2 

and so on

Anyways a couple useful things

How to get current instance name from T-SQL

To get the list of server and instance that you're connected to:

select * from Sys.Servers

To get the list of databases that connected server has:

SELECT * from sys.databases;

An existing connection was forcibly closed by the remote host

For anyone getting this exception while reading data from the stream, this may help. I was getting this exception when reading the HttpResponseMessage in a loop like this:

using (var remoteStream = await response.Content.ReadAsStreamAsync())
using (var content = File.Create(DownloadPath))
{
    var buffer = new byte[1024];
    int read;

    while ((read = await remoteStream.ReadAsync(buffer, 0, buffer.Length)) != 0)
    {
        await content.WriteAsync(buffer, 0, read);
        await content.FlushAsync();
    }
}

After some time I found out the culprit was the buffer size, which was too small and didn't play well with my weak Azure instance. What helped was to change the code to:

using (Stream remoteStream = await response.Content.ReadAsStreamAsync())
using (FileStream content = File.Create(DownloadPath))
{
    await remoteStream.CopyToAsync(content);
}

CopyTo() method has a default buffer size of 81920. The bigger buffer sped up the process and the errors stopped immediately, most likely because the overall download speeds increased. But why would download speed matter in preventing this error?

It is possible that you get disconnected from the server because the download speeds drop below minimum threshold the server is configured to allow. For example, in case the application you are downloading the file from is hosted on IIS, it can be a problem with http.sys configuration:

"Http.sys is the http protocol stack that IIS uses to perform http communication with clients. It has a timer called MinBytesPerSecond that is responsible for killing a connection if its transfer rate drops below some kb/sec threshold. By default, that threshold is set to 240 kb/sec."

The issue is described in this old blogpost from TFS development team and concerns IIS specifically, but may point you in a right direction. It also mentions an old bug related to this http.sys attribute: link

In case you are using Azure app services and increasing the buffer size does not eliminate the problem, try to scale up your machine as well. You will be allocated more resources including connection bandwidth.

Check if a div does NOT exist with javascript

All these answers do NOT take into account that you asked specifically about a DIV element.

document.querySelector("div#the-div-id")

@see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

How to grant permission to users for a directory using command line in Windows?

excellent point Calin Darie

I had a lot of scripts to use cacls I move them to icacls how ever I could not find a script to change the root mount volumes example: d:\datafolder. I finally crated the script below, which mounts the volume as a temporary drive then applies sec. then unmounts it. It is the only way I found that you can update the root mount security.

1 gets the folder mount GUID to a temp file then reads the GUID to mount the volume as a temp drive X: applies sec and logs the changes then unmounts the Volume only from the X: drive so the mounted folder is not altered or interrupted other then the applied sec.

here is sample of my script:

**mountvol "d:\%1" /L >tempDrive.temp && FOR /f "tokens=*" %%I IN (tempDrive.temp) DO mountvol X: %%I 
D:\tools\security\icacls.exe  %~2 /grant domain\group:(OI)(CI)F /T /C >>%~1LUNsec-%TDWEEK%-%TMONTH%-%TDAY%-%TYEAR%-%THOUR%-%TMINUTE%-%TAM%.txt
if exist x:\*.* mountvol X: /d**

How can I convert a comma-separated string to an array?

I had a similar issue, but more complex as I needed to transform a CSV file into an array of arrays (each line is one array element that inside has an array of items split by comma).

The easiest solution (and more secure I bet) was to use PapaParse which has a "no-header" option that transform the CSV file into an array of arrays, plus, it automatically detected the "," as my delimiter.

Plus, it is registered in Bower, so I only had to:

bower install papa-parse --save

And then use it in my code as follows:

var arrayOfArrays = Papa.parse(csvStringWithEnters), {header:false}).data;

I really liked it.

How to generate a create table script for an existing table in phpmyadmin?

This may be a late reply. But it may help others. It is very simple in MY SQL Workbench ( I am using Workbench version 6.3 and My SQL Version 5.1 Community edition): Right click on the table for which you want the create script, select 'Copy to Clipboard --> Create Statement' option. Simply paste in any text editor you want to get the create script.

How do I get the currently-logged username from a Windows service in .NET?

This is a WMI query to get the user name:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

You will need to add System.Management under References manually.

How to create a video from images with FFmpeg?

-pattern_type glob

This great option makes it easier to select the images in many cases.

Slideshow video with one image per second

ffmpeg -framerate 1 -pattern_type glob -i '*.png' \
  -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4

Add some music to it, cutoff when the presumably longer audio when the images end:

ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
  -c:a copy -shortest -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4

Here are two demos on YouTube:

Be a hippie and use the Theora patent-unencumbered video format:

ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
  -c:a copy -shortest -c:v libtheora -r 30 -pix_fmt yuv420p out.ogg

Your images should of course be sorted alphabetically, typically as:

0001-first-thing.jpg
0002-second-thing.jpg
0003-and-third.jpg

and so on.

I would also first ensure that all images to be used have the same aspect ratio, possibly by cropping them with imagemagick or nomacs beforehand, so that ffmpeg will not have to make hard decisions. In particular, the width has to be divisible by 2, otherwise conversion fails with: "width not divisible by 2".

Normal speed video with one image per frame at 30 FPS

ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
  -c:v libx264 -pix_fmt yuv420p out.mp4

Here's what it looks like:

GIF generated with: https://askubuntu.com/questions/648603/how-to-create-an-animated-gif-from-mp4-video-via-command-line/837574#837574

Add some audio to it:

ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
  -i audio.ogg -c:a copy -shortest -c:v libx264 -pix_fmt yuv420p out.mp4

Result: https://www.youtube.com/watch?v=HG7c7lldhM4

These are the test media I've used:a

wget -O opengl-rotating-triangle.zip https://github.com/cirosantilli/media/blob/master/opengl-rotating-triangle.zip?raw=true
unzip opengl-rotating-triangle.zip
cd opengl-rotating-triangle
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg

Images generated with: How to use GLUT/OpenGL to render to a file?

It is cool to observe how much the video compresses the image sequence way better than ZIP as it is able to compress across frames with specialized algorithms:

  • opengl-rotating-triangle.mp4: 340K
  • opengl-rotating-triangle.zip: 7.3M

Convert one music file to a video with a fixed image for YouTube upload

Answered at: https://superuser.com/questions/700419/how-to-convert-mp3-to-youtube-allowed-video-format/1472572#1472572

Full realistic slideshow case study setup step by step

There's a bit more to creating slideshows than running a single ffmpeg command, so here goes a more interesting detailed example inspired by this timeline.

Get the input media:

mkdir -p orig
cd orig
wget -O 1.png https://upload.wikimedia.org/wikipedia/commons/2/22/Australopithecus_afarensis.png
wget -O 2.jpg https://upload.wikimedia.org/wikipedia/commons/6/61/Homo_habilis-2.JPG
wget -O 3.jpg https://upload.wikimedia.org/wikipedia/commons/c/cb/Homo_erectus_new.JPG
wget -O 4.png https://upload.wikimedia.org/wikipedia/commons/1/1f/Homo_heidelbergensis_-_forensic_facial_reconstruction-crop.png
wget -O 5.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Sabaa_Nissan_Militiaman.jpg/450px-Sabaa_Nissan_Militiaman.jpg
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
cd ..

# Convert all to PNG for consistency.
# https://unix.stackexchange.com/questions/29869/converting-multiple-image-files-from-jpeg-to-pdf-format
# Hardlink the ones that are already PNG.
mkdir -p png
mogrify -format png -path png orig/*.jpg
ln -P orig/*.png png

Now we have a quick look at all image sizes to decide on the final aspect ratio:

identify png/*

which outputs:

png/1.png PNG 557x495 557x495+0+0 8-bit sRGB 653KB 0.000u 0:00.000
png/2.png PNG 664x800 664x800+0+0 8-bit sRGB 853KB 0.000u 0:00.000
png/3.png PNG 544x680 544x680+0+0 8-bit sRGB 442KB 0.000u 0:00.000
png/4.png PNG 207x238 207x238+0+0 8-bit sRGB 76.8KB 0.000u 0:00.000
png/5.png PNG 450x600 450x600+0+0 8-bit sRGB 627KB 0.000u 0:00.000

so the classic 480p (640x480 == 4/3) aspect ratio seems appropriate.

Do one conversion with minimal resizing to make widths even (TODO automate for any width, here I just manually looked at identify output and reduced width and height by one):

mkdir -p raw
convert png/1.png -resize 556x494 raw/1.png
ln -P png/2.png png/3.png png/4.png png/5.png raw
ffmpeg -framerate 1 -pattern_type glob -i 'raw/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p raw.mp4

This produces terrible output, because as seen from:

ffprobe raw.mp4

ffmpeg just takes the size of the first image, 556x494, and then converts all others to that exact size, breaking their aspect ratio.

Now let's convert the images to the target 480p aspect ratio automatically by cropping as per ImageMagick: how to minimally crop an image to a certain aspect ratio?

mkdir -p auto
mogrify -path auto -geometry 640x480^ -gravity center -crop 640x480+0+0 png/*.png
ffmpeg -framerate 1 -pattern_type glob -i 'auto/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p auto.mp4

So now, the aspect ratio is good, but inevitably some cropping had to be done, which kind of cut up interesting parts of the images.

The other option is to pad with black background to have the same aspect ratio as shown at: Resize to fit in a box and set background to black on "empty" part

mkdir -p black
ffmpeg -framerate 1 -pattern_type glob -i 'black/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p black.mp4

Generally speaking though, you will ideally be able to select images with the same or similar aspect ratios to avoid those problems in the first place.

About the CLI options

Note however that despite the name, -glob this is not as general as shell Glob patters, e.g.: -i '*' fails: https://trac.ffmpeg.org/ticket/3620 (apparently because filetype is deduced from extension).

-r 30 makes the -framerate 1 video 30 FPS to overcome bugs in players like VLC for low framerates: VLC freezes for low 1 FPS video created from images with ffmpeg Therefore it repeats each frame 30 times to keep the desired 1 image per second effect.

Next steps

You will also want to:

TODO: learn to cut and concatenate multiple audio files into the video without intermediate files, I'm pretty sure it's possible:

Tested on

ffmpeg 3.4.4, vlc 3.0.3, Ubuntu 18.04.

Bibliography

Horizontal scroll on overflow of table

   .search-table-outter {border:2px solid red; overflow-x:scroll;}
   .search-table{table-layout: fixed; margin:40px auto 0px auto;   }
   .search-table, td, th{border-collapse:collapse; border:1px solid #777;}
   th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
   td{padding:5px 10px; height:35px;}

You should provide scroll in div.

Best way to convert list to comma separated string in java

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");

String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
    total += s.length();
}

StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
    sb.append(separator).append(s);
}

String result = sb.substring(separator.length()); // remove leading separator

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

Ionic 2: Cordova is not available. Make sure to include cordova.js or run in a device/simulator (running in emulator)

In case anyone stumbles with this problem again, the accepted solution did work for older versions of ionic and app scripts, I had used it many times in the past, but last week, after I updated some stuff, it got broken again, and this fix wasn't working anymore as this was already solved on the current version of app-scripts, most of the info is referred on this post https://forum.ionicframework.com/t/ionic-cordova-run-android-livereload-cordova-not-available/116790/18 but I'll make it short here:

First make sure you have this versions on your system

cli packages: (xxxx\npm\node_modules)

@ionic/cli-utils  : 1.19.2
ionic (Ionic CLI) : 3.20.0

global packages:

cordova (Cordova CLI) : not installed

local packages:

@ionic/app-scripts : 3.1.9
Cordova Platforms  : android 7.0.0
Ionic Framework    : ionic-angular 3.9.2

System:

Node : v10.1.0
npm  : 5.6.0

An this on your package.json

"@angular/cli": "^6.0.3", "@ionic/app-scripts": "^3.1.9", "typescript": "~2.4.2"

Now remove your platform with ionic cordova platform rm what-ever Then DELETE the node_modules and plugins folder and MAKE SURE the platform was deleted inside the platforms folder.

Finally, run

npm install ionic cordova platform add what-ever ionic cordova run

And everything should be working again

What is polymorphism, what is it for, and how is it used?

Polymorphism is the ability to use an object in a given class, where all components that make up the object are inherited by subclasses of the given class. This means that once this object is declared by a class, all subclasses below it (and thier subclasses, and so on until you reach the farthest/lowest subclass) inherit the object and it's components (makeup).

Do remember that each class must be saved in separate files.

The following code exemplifies Polymorphism:

The SuperClass:

public class Parent {
    //Define things that all classes share
    String maidenName;
    String familyTree;

    //Give the top class a default method
    public void speak(){
         System.out.println("We are all Parents");
    }
}

The father, a subclass:

public class Father extends Parent{
    //Can use maidenName and familyTree here
    String name="Joe";
    String called="dad";

    //Give the top class a default method
    public void speak(){
        System.out.println("I am "+name+", the father.");
    }
}

The child, another subclass:

public class Child extends Father {
    //Can use maidenName, familyTree, called and name here

    //Give the top class a default method
    public void speak(){
        System.out.println("Hi "+called+". What are we going to do today?");
    }
}

The execution method, references Parent class to start:

public class Parenting{
    public static void main(String[] args) {
        Parent parents = new Parent();
        Parent parent = new Father();
        Parent child = new Child();

        parents.speak();
        parent.speak();
        child.speak();
    }
}

Note that each class needs to be declared in separate *.java files. The code should compile. Also notice that you can continually use maidenName and familyTree farther down. That is the concept of polymorphism. The concept of inheritance is also explored here, where one class is can be used or is further defined by a subclass.

Hope this helps and makes it clear. I will post the results when I find a computer that I can use to verify the code. Thanks for the patience!

Comparing strings by their alphabetical order

As others suggested, you can use String.compareTo(String).

But if you are sorting a list of Strings and you need a Comparator, you don't have to implement it, you can use Comparator.naturalOrder() or Comparator.reverseOrder().

How do I check my gcc C++ compiler version for my Eclipse?

The answer is:

gcc --version

Rather than searching on forums, for any possible option you can always type:

gcc --help

haha! :)

How can I remove the "No file chosen" tooltip from a file input in Chrome?

I found a solution that is very easy, just set an empty string into the title attribute.

<input type="file" value="" title=" " />

Python: How to increase/reduce the fontsize of x and y tick labels?

One shouldn't use set_yticklabels to change the fontsize, since this will also set the labels (i.e. it will replace any automatic formatter by a FixedFormatter), which is usually undesired. The easiest is to set the respective tick_params:

ax.tick_params(axis="x", labelsize=8)
ax.tick_params(axis="y", labelsize=20)

or

ax.tick_params(labelsize=8)

in case both axes shall have the same size.

Of course using the rcParams as in @tmdavison's answer is possible as well.

How to install gdb (debugger) in Mac OSX El Capitan?

Once you get the macports version of gdb installed you will need to disable SIP in order to make the proper edits to /System/Library/LaunchDaemons/com.apple.taskgated.plist. To disable SIP, you need to restart in recovery mode and execute the following command:

csrutil disable

Then restart. Then you will need to edit the bottom part of com.apple.taskgated.plist like this:

<array>
        <string>/usr/libexec/taskgated</string>
        <string>-sp</string>
</array>

Then you will have to restart to have the changes take effect. Then you should reenable SIP. The gdb command for the macports install is actually ggdb. You will need to code sign ggdb following the instructions here:

https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gnat_ugn_unw/Codesigning-the-Debugger.html

The only way I have been able to get the code signing to work is by running ggdb with sudo. Good luck!

How to fix Subversion lock error

We don't have an external SVN server. I was working on a PC with Windows 7 Enterprise, and I was using Eclipse subversion plugin as an SVN client. The problem in my case occurred when the commit of a file took to much time due to network problem that forced me to restart my PC.

After the restart I started getting this error: XXX file already locked.

The solution was to install (TortoiseSVN), right click on the SVN project folder --> TortoiseSVN --> cleanup.

I hope that this post would be a help to someone.

SQL is null and = null

In SQL, a comparison between a null value and any other value (including another null) using a comparison operator (eg =, !=, <, etc) will result in a null, which is considered as false for the purposes of a where clause (strictly speaking, it's "not true", rather than "false", but the effect is the same).

The reasoning is that a null means "unknown", so the result of any comparison to a null is also "unknown". So you'll get no hit on rows by coding where my_column = null.

SQL provides the special syntax for testing if a column is null, via is null and is not null, which is a special condition to test for a null (or not a null).

Here's some SQL showing a variety of conditions and and their effect as per above.

create table t (x int, y int);
insert into t values (null, null), (null, 1), (1, 1);

select 'x = null' as test , x, y from t where x = null
union all
select 'x != null', x, y from t where x != null
union all
select 'not (x = null)', x, y from t where not (x = null)
union all
select 'x = y', x, y from t where x = y
union all
select 'not (x = y)', x, y from t where not (x = y);

returns only 1 row (as expected):

TEST    X   Y
x = y   1   1

See this running on SQLFiddle

How do I set hostname in docker-compose?

As of docker-compose version 3 and later, you can just use the hostname key:

version: '3'
services:
  dns:
    hostname: 'your-name'

How can I have grep not print out 'No such file or directory' errors?

I have seen that happening several times, with broken links (symlinks that point to files that do not exist), grep tries to search on the target file, which does not exist (hence the correct and accurate error message).

I normally don't bother while doing sysadmin tasks over the console, but from within scripts I do look for text files with "find", and then grep each one:

find /etc -type f -exec grep -nHi -e "widehat" {} \;

Instead of:

grep -nRHi -e "widehat" /etc

How to check if a file exists before creating a new file

Try this (copied-ish from Erik Garrison: https://stackoverflow.com/a/3071528/575530)

#include <sys/stat.h>

bool FileExists(char* filename) 
{
    struct stat fileInfo;
    return stat(filename, &fileInfo) == 0;
}

stat returns 0 if the file exists and -1 if not.

Return different type of data from a method in java?

the approach you took is good. Just Implementation may need to be better. For instance ReturningValues should be well defined and Its better if you can make ReturningValues as immutable.

// this approach is better
public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues("value", 12);
    return rv;
}


public final class ReturningValues {
    private final String value;
    private final int index;


    public ReturningValues(String value, int index) {
      this.value = value;
      this.index = index;
     }

} 

Or if you have lots of key value pairs you can use HashMap then

public static Map<String,Object> myMethod() {
  Map<String,Object> map = new HashMap<String,Object>();
  map.put(VALUE, "value");
  map.put(INDEX, 12);
  return Collections.unmodifiableMap(map); // try to use this 
}

Creating java date object from year,month,day

Make your life easy when working with dates, timestamps and durations. Use HalDateTime from

http://sourceforge.net/projects/haldatetime/?source=directory

For example you can just use it to parse your input like this:

HalDateTime mydate = HalDateTime.valueOf( "25.12.1988" );
System.out.println( mydate );   // will print in ISO format: 1988-12-25

You can also specify patterns for parsing and printing.

ValueError: max() arg is an empty sequence

When the length of v will be zero, it'll give you the value error.

You should check the length or you should check the list first whether it is none or not.

if list:
    k.index(max(list))

or

len(list)== 0

Ruby capitalize every word first letter

"hello world".split.each{|i| i.capitalize!}.join(' ')

PHP mail not working for some reason

The mail function do not guarantee the actual delivery of mail. All it do is to pass the message to external program (usually sendmail). You need a properly configured SMTP server in order for this to work. Also keep in mind it does not support SMTP authentication. You may check out the PEAR::Mail library of SwiftMailer, both of them give you more options.

Proper way to declare custom exceptions in modern Python?

Maybe I missed the question, but why not:

class MyException(Exception):
    pass

Edit: to override something (or pass extra args), do this:

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super(ValidationError, self).__init__(message)

        # Now for your custom code...
        self.errors = errors

That way you could pass dict of error messages to the second param, and get to it later with e.errors


Python 3 Update: In Python 3+, you can use this slightly more compact use of super():

class ValidationError(Exception):
    def __init__(self, message, errors):

        # Call the base class constructor with the parameters it needs
        super().__init__(message)

        # Now for your custom code...
        self.errors = errors

Change Button color onClick

Every time setColor gets hit, you are setting count = 1. You would need to define count outside of the scope of the function. Example:

var count=1;
function setColor(btn, color){
    var property = document.getElementById(btn);
    if (count == 0){
        property.style.backgroundColor = "#FFFFFF"
        count=1;        
    }
    else{
        property.style.backgroundColor = "#7FFF00"
        count=0;
    }

}

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I Solved this problem adding @Cascade to the @ManyToOne attribute.

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@ManyToOne
@JoinColumn(name="BLOODGRUPID")
@Cascade({CascadeType.MERGE, CascadeType.SAVE_UPDATE})
private Bloodgroup bloodgroup;

JavaScript operator similar to SQL "like"

You can use regular expressions in Javascript to do pattern matching of strings.

For example:

var s = "hello world!";
if (s.match(/hello.*/)) {
  // do something
}

The match() test is much like WHERE s LIKE 'hello%' in SQL.

Is it possible to get all arguments of a function as single object inside that function?

In ES6, use Array.from:

function foo()
  {
  foo.bar = Array.from(arguments);
  foo.baz = foo.bar.join();
  }

foo(1,2,3,4,5,6,7);
foo.bar // Array [1, 2, 3, 4, 5, 6, 7]
foo.baz // "1,2,3,4,5,6,7"

For non-ES6 code, use JSON.stringify and JSON.parse:

function foo()
  {
  foo.bar = JSON.stringify(arguments); 
  foo.baz = JSON.parse(foo.bar); 
  }

/* Atomic Data */
foo(1,2,3,4,5,6,7);
foo.bar // "{"0":1,"1":2,"2":3,"3":4,"4":5,"5":6,"6":7}"
foo.baz // [object Object]

/* Structured Data */
foo({1:2},[3,4],/5,6/,Date())
foo.bar //"{"0":{"1":2},"1":[3,4],"2":{},"3":"Tue Dec 17 2013 16:25:44 GMT-0800 (Pacific Standard Time)"}"
foo.baz // [object Object]

If preservation is needed instead of stringification, use the internal structured cloning algorithm.

If DOM nodes are passed, use XMLSerializer as in an unrelated question.

with (new XMLSerializer()) {serializeToString(document.documentElement) }

If running as a bookmarklet, you may need to wrap the each structured data argument in an Error constructor for JSON.stringify to work properly.

References

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

Setting focus on an HTML input box on page load

This line:

<input type="password" name="PasswordInput"/>

should have an id attribute, like so:

<input type="password" name="PasswordInput" id="PasswordInput"/>

UNIX export command

export is a built-in command of the bash shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.

Apache 13 permission denied in user's home directory

Apache's errorlog will explain why you get a permission denied. Also, serverfault.com is a better forum for a question like this.

If the error log simply says "permission denied", su to the user that the webserver is running as and try to read from the file in question. So for example:

sudo -s
su - nobody
cd /
cd /home
cd user
cd xxx
cat index.html

See if one of those gives you the "permission denied" error.

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my EPiServer solution on several controllers there was a ContentOutputCache attribute on the Index action which accepted HttpGet. Each view for those actions contained a form which was posting to a HttpPost action to the same controller or to a different one. As soon as I removed that attribute from all of those Index actions problem was gone.

How to vertically align text inside a flexbox?

Instead of using align-self: center use align-items: center.

There's no need to change flex-direction or use text-align.

Here's your code, with one adjustment, to make it all work:

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  /* align-self: center;    <---- REMOVE */
  align-items: center;   /* <---- NEW    */
  background: silver;
  width: 100%;
  height: 20%; 
}

The align-self property applies to flex items. Except your li is not a flex item because its parent – the ul – does not have display: flex or display: inline-flex applied.

Therefore, the ul is not a flex container, the li is not a flex item, and align-self has no effect.

The align-items property is similar to align-self, except it applies to flex containers.

Since the li is a flex container, align-items can be used to vertically center the child elements.

_x000D_
_x000D_
* {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
ul {_x000D_
  height: 100%;_x000D_
}_x000D_
li {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  /* align-self: center; */_x000D_
  align-items: center;_x000D_
  background: silver;_x000D_
  width: 100%;_x000D_
  height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
  <li>This is the text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

codepen demo


Technically, here's how align-items and align-self work...

The align-items property (on the container) sets the default value of align-self (on the items). Therefore, align-items: center means all flex items will be set to align-self: center.

But you can override this default by adjusting the align-self on individual items.

For example, you may want equal height columns, so the container is set to align-items: stretch. However, one item must be pinned to the top, so it is set to align-self: flex-start.

example


How is the text a flex item?

Some people may be wondering how a run of text...

<li>This is the text</li>

is a child element of the li.

The reason is that text that is not explicitly wrapped by an inline-level element is algorithmically wrapped by an inline box. This makes it an anonymous inline element and child of the parent.

From the CSS spec:

9.2.2.1 Anonymous inline boxes

Any text that is directly contained inside a block container element must be treated as an anonymous inline element.

The flexbox specification provides for similar behavior.

4. Flex Items

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.

Hence, the text in the li is a flex item.

Cannot get OpenCV to compile because of undefined references?

For me, this type of error:

mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'

meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv... just like that, that order. And putting them right next to each other helped too, don't put -lTransform360 all the way at the beginning...or you'll get, for some freaky reason:

undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'

...

Unicode (UTF-8) reading and writing to files in Python

Well, your favorite text editor does not realize that \xc3\xa1 are supposed to be character literals, but it interprets them as text. That's why you get the double backslashes in the last line -- it's now a real backslash + xc3, etc. in your file.

If you want to read and write encoded files in Python, best use the codecs module.

Pasting text between the terminal and applications is difficult, because you don't know which program will interpret your text using which encoding. You could try the following:

>>> s = file("f1").read()
>>> print unicode(s, "Latin-1")
Capitán

Then paste this string into your editor and make sure that it stores it using Latin-1. Under the assumption that the clipboard does not garble the string, the round trip should work.

Strangest language feature

APL (other than ALL of it), the ability to write any program in just one line.

e.g. Conway's Game of Life in one line in APL:

alt text http://catpad.net/michael/APLLife.gif

If that line isn't WTF, then nothing is!

And here is a video

How to check Network port access and display useful message?

I improved Salselvaprabu's answer in several ways:

  1. It is now a function - you can put in your powershell profile and use anytime you need
  2. It can accept host as hostname or as ip address
  3. No more exceptions if host or port unavaible - just text

Call it like this:

Test-Port example.com 999
Test-Port 192.168.0.1 80

function Test-Port($hostname, $port)
{
    # This works no matter in which form we get $host - hostname or ip address
    try {
        $ip = [System.Net.Dns]::GetHostAddresses($hostname) | 
            select-object IPAddressToString -expandproperty  IPAddressToString
        if($ip.GetType().Name -eq "Object[]")
        {
            #If we have several ip's for that address, let's take first one
            $ip = $ip[0]
        }
    } catch {
        Write-Host "Possibly $hostname is wrong hostname or IP"
        return
    }
    $t = New-Object Net.Sockets.TcpClient
    # We use Try\Catch to remove exception info from console if we can't connect
    try
    {
        $t.Connect($ip,$port)
    } catch {}

    if($t.Connected)
    {
        $t.Close()
        $msg = "Port $port is operational"
    }
    else
    {
        $msg = "Port $port on $ip is closed, "
        $msg += "You may need to contact your IT team to open it. "                                 
    }
    Write-Host $msg
}

Oracle query to fetch column names

The below query worked for me in Oracle database.

select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='MyTableName';

Invalid http_host header

In your project settings.py file,set ALLOWED_HOSTS like this :

ALLOWED_HOSTS = ['62.63.141.41', 'namjoosadr.com']

and then restart your apache. in ubuntu:

/etc/init.d/apache2 restart

How to style a select tag's option element?

Since version 49+, Chrome has supported styling <option> elements with font-weight. Source: https://code.google.com/p/chromium/issues/detail?id=44917#c22

New SELECT Popup: font-weight style should be applied.

This CL removes themeChromiumSkia.css. |!important| in it prevented to apply font-weight. Now html.css has |font-weight:normal|, and |!important| should be unnecessary.

There was a Chrome stylesheet, themeChromiumSkia.css, that used font-weight: normal !important; in it all this time. It was introduced to the stable Chrome channel in version 49.0.

How to determine if a list of polygon points are in clockwise order?

Here is a simple C# implementation of the algorithm based on this answer.

Let's assume that we have a Vector type having X and Y properties of type double.

public bool IsClockwise(IList<Vector> vertices)
{
    double sum = 0.0;
    for (int i = 0; i < vertices.Count; i++) {
        Vector v1 = vertices[i];
        Vector v2 = vertices[(i + 1) % vertices.Count];
        sum += (v2.X - v1.X) * (v2.Y + v1.Y);
    }
    return sum > 0.0;
}

% is the modulo or remainder operator performing the modulo operation which (according to Wikipedia) finds the remainder after division of one number by another.

Validating email addresses using jQuery and regex

I would recommend that you use the jQuery plugin for Verimail.js.

Why?

  • IANA TLD validation
  • Syntax validation (according to RFC 822)
  • Spelling suggestion for the most common TLDs and email domains
  • Deny temporary email account domains such as mailinator.com

How?

Include verimail.jquery.js on your site and use the function:

$("input#email-address").verimail({
    messageElement: "p#status-message"
});

If you have a form and want to validate the email on submit, you can use the getVerimailStatus-function:

if($("input#email-address").getVerimailStatus() < 0){
    // Invalid email
}else{
    // Valid email
}

How do I scroll to an element using JavaScript?

In case you want to use html, you could just use this:

a href="samplewebsite.com/subdivision.html#id

and make it an html link to the specific element id. Its basically getElementById html version.

How do I enumerate through a JObject?

The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.

This is the answer that worked for me:

foreach (var x in jobj)
{
    var key = ((JProperty) (x)).Name;
    var jvalue = ((JProperty)(x)).Value ;
}

Get Android shared preferences value in activity/normal class

I tried this code, to retrieve shared preferences from an activity, and could not get it to work:

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPreferences.getAll();
    Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
    Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());

Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.

getPreferenceManager().setSharedPreferencesName("defaultPreferences");

After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

In my case, this error happened because my HTML had a trailing linebreak.

var myHtml = '<p>\
    This should work.\
    But does not.\
</p>\
';

jQuery('.something').append(myHtml); // this causes the error

To avoid the error, you just need to trim the HTML.

jQuery('.something').append(jQuery.trim(myHtml)); // this works

see if two files have the same content in python

Yes, I think hashing the file would be the best way if you have to compare several files and store hashes for later comparison. As hash can clash, a byte-by-byte comparison may be done depending on the use case.

Generally byte-by-byte comparison would be sufficient and efficient, which filecmp module already does + other things too.

See http://docs.python.org/library/filecmp.html e.g.

>>> import filecmp
>>> filecmp.cmp('file1.txt', 'file1.txt')
True
>>> filecmp.cmp('file1.txt', 'file2.txt')
False

Speed consideration: Usually if only two files have to be compared, hashing them and comparing them would be slower instead of simple byte-by-byte comparison if done efficiently. e.g. code below tries to time hash vs byte-by-byte

Disclaimer: this is not the best way of timing or comparing two algo. and there is need for improvements but it does give rough idea. If you think it should be improved do tell me I will change it.

import random
import string
import hashlib
import time

def getRandText(N):
    return  "".join([random.choice(string.printable) for i in xrange(N)])

N=1000000
randText1 = getRandText(N)
randText2 = getRandText(N)

def cmpHash(text1, text2):
    hash1 = hashlib.md5()
    hash1.update(text1)
    hash1 = hash1.hexdigest()

    hash2 = hashlib.md5()
    hash2.update(text2)
    hash2 = hash2.hexdigest()

    return  hash1 == hash2

def cmpByteByByte(text1, text2):
    return text1 == text2

for cmpFunc in (cmpHash, cmpByteByByte):
    st = time.time()
    for i in range(10):
        cmpFunc(randText1, randText2)
    print cmpFunc.func_name,time.time()-st

and the output is

cmpHash 0.234999895096
cmpByteByByte 0.0

hadoop No FileSystem for scheme: file

I assume you build sample using maven.

Please check content of the JAR you're trying to run. Especially META-INFO/services directory, file org.apache.hadoop.fs.FileSystem. There should be list of filsystem implementation classes. Check line org.apache.hadoop.hdfs.DistributedFileSystem is present in the list for HDFS and org.apache.hadoop.fs.LocalFileSystem for local file scheme.

If this is the case, you have to override referred resource during the build.

Other possibility is you simply don't have hadoop-hdfs.jar in your classpath but this has low probability. Usually if you have correct hadoop-client dependency it is not an option.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

Above two answers are correct but didn't work for me.

  1. I kept on seeing blank like below for docker container lsenter image description here
  2. then I tried, docker container ls -a and after that it showed all the process previously exited and running.
  3. Then docker stop <container id> or docker container stop <container id> didn't work
  4. then I tried docker rm -f <container id> and it worked.
  5. Now at this I tried docker container ls -a and this process wasn't present.

Eclipse says: “Workspace in use or cannot be created, chose a different one.” How do I unlock a workspace?

i was faced this issue when ever the eclipse is not closed (kill eclipse process the from task manager or computer power off), i was tried below steps, it worked for me.

1) Remove the file names start with ".fileTable" from this folder

C:\eclipse\configuration\org.eclipse.osgi.manager

2) Remove the log files like text files start with numeric names from this folder

C:\eclipse\configuration

3) Open Command prompt(cmd) navigate to this folder

C:\eclipse

type below command

eclipse clean start

enter image description here

Android Studio SDK location

C:\Users\username\AppData\Local\Android\sdk\extras\intel\Hardware_Accelerated_Execution_Manager\intelhaxm-android.exe

check this location in windows

Convert python datetime to timestamp in milliseconds

For those who searches for an answer without parsing and loosing milliseconds, given dt_obj is a datetime:

python3 only, elegant

int(dt_obj.timestamp() * 1000)

both python2 and python3 compatible:

import time

int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)

How to establish a connection pool in JDBC?

Pool

  • Pooling Mechanism is the way of creating the Objects in advance. When a class is loaded.
  • It improves the application performance [By re using same object's to perform any action on Object-Data] & memory [allocating and de-allocating many objects creates a significant memory management overhead].
  • Object clean-up is not required as we are using same Object, reducing the Garbage collection load.

« Pooling [ Object pool, String Constant Pool, Thread Pool, Connection pool]

String Constant pool

  • String literal pool maintains only one copy of each distinct string value. which must be immutable.
  • When the intern method is invoked, it check object availability with same content in pool using equals method. « If String-copy is available in the Pool then returns the reference. « Otherwise, String object is added to the pool and returns the reference.

Example: String to verify Unique Object from pool.

public class StringPoolTest {
    public static void main(String[] args) { // Integer.valueOf(), String.equals()
        String eol = System.getProperty("line.separator"); //java7 System.lineSeparator();

        String s1 = "Yash".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s1, s1.hashCode(), System.identityHashCode(s1));
        String s2 = "Yas"+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s2, s2.hashCode(), System.identityHashCode(s2));
        String s3 = "Yas".intern()+"h".intern();
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s3, s3.hashCode(), System.identityHashCode(s3));
        String s4 = "Yas"+"h";
        System.out.format("Val:%s Hash:%s SYS:%s "+eol, s4, s4.hashCode(), System.identityHashCode(s4));
    }
}

Connection pool using Type-4 Driver using 3rd party libraries[ DBCP2, c3p0, Tomcat JDBC]

Type 4 - The Thin driver converts JDBC calls directly into the vendor-specific database protocol Ex[Oracle - Thick, MySQL - Quora]. wiki

In Connection pool mechanism, when the class is loaded it get's the physical JDBC connection objects and provides a wrapped physical connection object to user. PoolableConnection is a wrapper around the actual connection.

  • getConnection() pick one of the free wrapped-connection form the connection objectpool and returns it.
  • close() instead of closing it returns the wrapped-connection back to pool.

Example: Using ~ DBCP2 Connection Pool with Java 7[try-with-resources]

public class ConnectionPool {
    static final BasicDataSource ds_dbcp2 = new BasicDataSource();
    static final ComboPooledDataSource ds_c3p0 = new ComboPooledDataSource();
    static final DataSource ds_JDBC = new DataSource();

    static Properties prop = new Properties();
    static {
        try {
            prop.load(ConnectionPool.class.getClassLoader().getResourceAsStream("connectionpool.properties"));

            ds_dbcp2.setDriverClassName( prop.getProperty("DriverClass") );
            ds_dbcp2.setUrl( prop.getProperty("URL") );
            ds_dbcp2.setUsername( prop.getProperty("UserName") );
            ds_dbcp2.setPassword( prop.getProperty("Password") );
            ds_dbcp2.setInitialSize( 5 );

            ds_c3p0.setDriverClass( prop.getProperty("DriverClass") );
            ds_c3p0.setJdbcUrl( prop.getProperty("URL") );
            ds_c3p0.setUser( prop.getProperty("UserName") );
            ds_c3p0.setPassword( prop.getProperty("Password") );
            ds_c3p0.setMinPoolSize(5);
            ds_c3p0.setAcquireIncrement(5);
            ds_c3p0.setMaxPoolSize(20);

            PoolProperties pool = new PoolProperties();
            pool.setUrl( prop.getProperty("URL") );
            pool.setDriverClassName( prop.getProperty("DriverClass") );
            pool.setUsername( prop.getProperty("UserName") );
            pool.setPassword( prop.getProperty("Password") );
            pool.setValidationQuery("SELECT 1");// SELECT 1(mysql) select 1 from dual(oracle)

            pool.setInitialSize(5);
            pool.setMaxActive(3);
            ds_JDBC.setPoolProperties( pool );
        } catch (IOException e) {   e.printStackTrace();
        } catch (PropertyVetoException e) { e.printStackTrace(); }
    }

    public static Connection getDBCP2Connection() throws SQLException {
        return ds_dbcp2.getConnection();
    }

    public static Connection getc3p0Connection() throws SQLException {
        return ds_c3p0.getConnection();
    }

    public static Connection getJDBCConnection() throws SQLException {
        return ds_JDBC.getConnection();
    }
}
public static boolean exists(String UserName, String Password ) throws SQLException {
    boolean exist = false;
    String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
    try ( Connection connection = ConnectionPool.getDBCP2Connection();
          PreparedStatement pstmt = connection.prepareStatement(SQL_EXIST); ) {
        pstmt.setString(1, UserName );
        pstmt.setString(2, Password );

        try (ResultSet resultSet = pstmt.executeQuery()) {
            exist = resultSet.next(); // Note that you should not return a ResultSet here.
        }
    }
    System.out.println("User : "+exist);
    return exist;
}

jdbc:<DB>:<drivertype>:<HOST>:<TCP/IP PORT>:<dataBaseName> jdbc:oracle:thin:@localhost:1521:myDBName jdbc:mysql://localhost:3306/myDBName

connectionpool.properties

URL         : jdbc:mysql://localhost:3306/myDBName
DriverClass : com.mysql.jdbc.Driver
UserName    : root
Password    :

Web Application: To avoid connection problem when all the connection's are closed[MySQL "wait_timeout" default 8 hours] in-order to reopen the connection with underlying DB.

You can do this to Test Every Connection by setting testOnBorrow = true and validationQuery= "SELECT 1" and donot use autoReconnect for MySQL server as it is deprecated. issue

===== ===== context.xml ===== =====
<?xml version="1.0" encoding="UTF-8"?>
<!-- The contents of this file will be loaded for a web application -->
<Context>
    <Resource name="jdbc/MyAppDB" auth="Container" 
        factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" 
        type="javax.sql.DataSource" 

        initialSize="5" minIdle="5" maxActive="15" maxIdle="10"

        testWhileIdle="true"
            timeBetweenEvictionRunsMillis="30000"

        testOnBorrow="true"
            validationQuery="SELECT 1"
            validationInterval="30000"


        driverClassName="com.mysql.jdbc.Driver" 
        url="jdbc:mysql://localhost:3306/myDBName" 
        username="yash" password="777"
    />
</Context>

===== ===== web.xml ===== =====
<resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/MyAppDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
===== ===== DBOperations ===== =====
servlet «   init() {}
Normal call used by sevlet  « static {}

static DataSource ds;
static {
    try {
        Context ctx=new InitialContext();
        Context envContext = (Context)ctx.lookup("java:comp/env");
        ds  =   (DataSource) envContext.lookup("jdbc/MyAppDB");
    } catch (NamingException e) {   e.printStackTrace();    }
}

See these also:

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

For Windows/WSL/Cygwin etc users:

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

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


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

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

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

Chrome - ERR_CACHE_MISS

If you are using WebView in Android developing the problem is that you didn't add uses permission

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

Reading from stdin

From the man read:

#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);

Input parameters:

  • int fd file descriptor is an integer and not a file pointer. The file descriptor for stdin is 0

  • void *buf pointer to buffer to store characters read by the read function

  • size_t count maximum number of characters to read

So you can read character by character with the following code:

char buf[1];

while(read(0, buf, sizeof(buf))>0) {
   // read() here read from stdin charachter by character
   // the buf[0] contains the character got by read()
   ....
}

Are HTTP headers case-sensitive?

officially, headers are case insensitive, however, it is common practice to capitalize the first letter of every word.
but, because it is common practice, certain programs like IE assume the headers are capitalized.
so while the docs say the are case insensitive, bad programmers have basically changed the docs.

What is the best way to implement a "timer"?

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();

Prevent linebreak after </div>

I don't think I've seen this version:

<div class="label">My Label:<span class="text">My text</span></div>

How to add a classname/id to React-Bootstrap Component?

1st way is to use props

<Row id = "someRandomID">

Wherein, in the Definition, you may just go

const Row = props  => {
 div id = {props.id}
}

The same could be done with class, replacing id with className in the above example.


You might as well use react-html-id, that is an npm package. This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.

Ref: react-html-id


Peace.

Compiling LaTex bib source

I am using texmaker as the editor. you have to compile it in terminal as following:

  1. pdflatex filename (with or without extensions)
  2. bibtex filename (without extensions)
  3. pdflatex filename (with or without extensions)
  4. pdflatex filename (with or without extensions)

but sometimes, when you use \citep{}, the names of the references don't show up. In this case, I had to open the references.bib file , so that texmaker could capture the references from the references.bib file. After every edition of the bib file, I had to close and reopen it!! So that texmaker could capture the content of new .bbl file each time. But remember, you have to also run your code in texmaker too.

What is the difference between sscanf or atoi to convert a string to an integer?

To @R.. I think it's not enough to check errno for error detection in strtol call.

long strtol (const char *String, char **EndPointer, int Base)

You'll also need to check EndPointer for errors.

dyld: Library not loaded ... Reason: Image not found

I got here trying to run a program I just compiled using CMake. When I try to run it, it complains saying:

dyld: Library not loaded: libboost_system.dylib
  Referenced from: /Users/path/to/my/executable
  Reason: image not found

I circumvented the problem telling CMake to use the static version of Boost, instead of letting it use the dynamic one:

set(Boost_USE_STATIC_LIBS ON)

jQuery UI Dialog with ASP.NET button postback

$('#divname').parent().appendTo($("form:first"));

Using this code solved my problem and it worked in every browser, Internet Explorer 7, Firefox 3, and Google Chrome. I start to love jQuery... It's a cool framework.

I have tested with partial render too, exactly what I was looking for. Great!

<script type="text/javascript">
    function openModalDiv(divname) {
        $('#' + divname).dialog({ autoOpen: false, bgiframe: true, modal: true });
        $('#' + divname).dialog('open');
        $('#' + divname).parent().appendTo($("form:first"));
    }

    function closeModalDiv(divname) {
        $('#' + divname).dialog('close');
    }
</script>
...
...
<input id="Button1" type="button" value="Open 1" onclick="javascript:openModalDiv('Div1');" />
...
...
<div id="Div1" title="Basic dialog" >
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
       <ContentTemplate>
          postback test<br />
          <asp:Button ID="but_OK" runat="server" Text="Send request" /><br />
          <asp:TextBox ID="tb_send" runat="server"></asp:TextBox><br />
          <asp:Label ID="lbl_result" runat="server" Text="prova" BackColor="#ff0000></asp:Label>
        </ContentTemplate>
    <asp:UpdatePanel>
    <input id="Button2" type="button" value="cancel" onclick="javascript:closeModalDiv('Div1');" />
</div>

SQL Developer is returning only the date, not the time. How do I fix this?

Date format can also be set by using below query :-

alter SESSION set NLS_DATE_FORMAT = 'date_format'

e.g. : alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'

Find where python is installed (if it isn't default dir)

For Windows Users:

If the python command is not in your $PATH environment var.

Open PowerShell and run these commands to find the folder

cd \
ls *ython* -Recurse -Directory

That should tell you where python is installed

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

Android emulator failed to allocate memory 8

Reducing the RAM size in the AVD settings worked for me. The AVD being slow can eat up a lot of RAM, so keeping it at a minimum is feasible.

Stratified Train/Test-split in scikit-learn

[update for 0.17]

See the docs of sklearn.model_selection.train_test_split:

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y,
                                                    stratify=y, 
                                                    test_size=0.25)

[/update for 0.17]

There is a pull request here. But you can simply do train, test = next(iter(StratifiedKFold(...))) and use the train and test indices if you want.

download file using an ajax request

This solution is not very different from those above, but for me it works very well and i think it's clean.

I suggest to base64 encode the file server side (base64_encode(), if you are using PHP) and send the base64 encoded data to the client

On the client you do this:

 let blob = this.dataURItoBlob(THE_MIME_TYPE + "," + response.file);
 let uri = URL.createObjectURL(blob);
 let link = document.createElement("a");
 link.download = THE_FILE_NAME,
 link.href = uri;
 document.body.appendChild(link);
 link.click();
 document.body.removeChild(link);

This code puts the encoded data in a link and simulates a click on the link, then it removes it.

How to Set Focus on JTextField?

If you want your JTextField to be focused when your GUI shows up, you can use this:

in = new JTextField(40);
f.addWindowListener( new WindowAdapter() {
    public void windowOpened( WindowEvent e ){
        in.requestFocus();
    }
}); 

Where f would be your JFrame and in is your JTextField.

Hadoop: «ERROR : JAVA_HOME is not set»

In some distributives(CentOS/OpenSuSe,...) will work only if you set JAVA_HOME in the /etc/environment.

Using Jasmine to spy on a function without an object

TypeScript users:

I know the OP asked about javascript, but for any TypeScript users who come across this who want to spy on an imported function, here's what you can do.

In the test file, convert the import of the function from this:

import {foo} from '../foo_functions';

x = foo(y);

To this:

import * as FooFunctions from '../foo_functions';

x = FooFunctions.foo(y);

Then you can spy on FooFunctions.foo :)

spyOn(FooFunctions, 'foo').and.callFake(...);
// ...
expect(FooFunctions.foo).toHaveBeenCalled();

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

For me this was caused by using a dynamic ipadress using installation. I reinstalled Oracle using a static ipadress and then everything was fine

Display Yes and No buttons instead of OK and Cancel in Confirm box?

If you switch to the jQuery UI Dialog box, you can initialize the buttons array with the appropriate names like:

$("#id").dialog({
  buttons: {
    "Yes": function() {},
    "No": function() {}
  }
});

Embed YouTube Video with No Ads

I'd just like to add, and please correct me if I'm wrong, that when I embed the HTML5 version of the videos, it doesn't play ads on top.

Not sure if this will ever change. They're probably just trying to work out the best way to show ads on the HTML5 player.

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

wordpress contactform7 textarea cols and rows change in smaller screens

I was able to get this work. I added the following to my custom CSS:

.wpcf7-form textarea{ 
    width: 100% !important;
    height:50px;
}

Maven: How to rename the war file for the project?

You can use the following in the web module that produces the war:

<build>
  <finalName>bird</finalName>
 . . .
</build>

This leads to a file called bird.war to be created when goal "war:war" is used.

Python list sort in descending order

Since your list is already in ascending order, we can simply reverse the list.

>>> timestamps.reverse()
>>> timestamps
['2010-04-20 10:25:38', 
'2010-04-20 10:12:13', 
'2010-04-20 10:12:13', 
'2010-04-20 10:11:50', 
'2010-04-20 10:10:58', 
'2010-04-20 10:10:37', 
'2010-04-20 10:09:46', 
'2010-04-20 10:08:22',
'2010-04-20 10:08:22', 
'2010-04-20 10:07:52', 
'2010-04-20 10:07:38', 
'2010-04-20 10:07:30']

Get just the filename from a path in a Bash script

Here is an easy way to get the file name from a path:

echo "$PATH" | rev | cut -d"/" -f1 | rev

To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

cut -d"." -f1

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

ValueErrors :In Python, a value is the information that is stored within a certain object. To encounter a ValueError in Python means that is a problem with the content of the object you tried to assign the value to.

in your case name,lastname and email 3 parameters are there but unpaidmembers only contain 2 of them.

name, lastname, email in unpaidMembers.items() so you should refer data or your code might be
lastname, email in unpaidMembers.items() or name, email in unpaidMembers.items()

Change Screen Orientation programmatically using a Button

A working code:

private void changeScreenOrientation() {
    int orientation = yourActivityName.this.getResources().getConfiguration().orientation;
    if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        showMediaDescription();
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        hideMediaDescription();
    }
    if (Settings.System.getInt(getContentResolver(),
            Settings.System.ACCELEROMETER_ROTATION, 0) == 1) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
            }
        }, 4000);
    }
}

call this method in your button click

Facebook Graph API, how to get users email?

Make sure your Facebook application is published. In order to receive data for email, public_profile and user_friends your app must be made available to public.

You can disable it later for development purposes and still get email field.

Check if a file is executable

First you need to remember that in Unix and Linux, everything is a file, even directories. For a file to have the rights to be executed as a command, it needs to satisfy 3 conditions:

  1. It needs to be a regular file
  2. It needs to have read-permissions
  3. It needs to have execute-permissions

So this can be done simply with:

[ -f "${file}" ] && [ -r "${file}" ] && [ -x "${file}" ]

If your file is a symbolic link to a regular file, the test command will operate on the target and not the link-name. So the above command distinguishes if a file can be used as a command or not. So there is no need to pass the file first to realpath or readlink or any of those variants.

If the file can be executed on the current OS, that is a different question. Some answers above already pointed to some possibilities for that, so there is no need to repeat it here.

What exactly is LLVM?

According to 'Getting Started With LLVM Core Libraries' book (c):

In fact, the name LLVM might refer to any of the following:

  • The LLVM project/infrastructure: This is an umbrella for several projects that, together, form a complete compiler: frontends, backends, optimizers, assemblers, linkers, libc++, compiler-rt, and a JIT engine. The word "LLVM" has this meaning, for example, in the following sentence: "LLVM is comprised of several projects".

  • An LLVM-based compiler: This is a compiler built partially or completely with the LLVM infrastructure. For example, a compiler might use LLVM for the frontend and backend but use GCC and GNU system libraries to perform the final link. LLVM has this meaning in the following sentence, for example: "I used LLVM to compile C programs to a MIPS platform".

  • LLVM libraries: This is the reusable code portion of the LLVM infrastructure. For example, LLVM has this meaning in the sentence: "My project uses LLVM to generate code through its Just-in-Time compilation framework".

  • LLVM core: The optimizations that happen at the intermediate language level and the backend algorithms form the LLVM core where the project started. LLVM has this meaning in the following sentence: "LLVM and Clang are two different projects".

  • The LLVM IR: This is the LLVM compiler intermediate representation. LLVM has this meaning when used in sentences such as "I built a frontend that translates my own language to LLVM".

Java "?" Operator for checking null - What is it? (Not Ternary!)

It is possible to define util methods which solves this in an almost pretty way with Java 8 lambda.

This is a variation of H-MANs solution but it uses overloaded methods with multiple arguments to handle multiple steps instead of catching NullPointerException.

Even if I think this solution is kind of cool I think I prefer Helder Pereira's seconds one since that doesn't require any util methods.

void example() {
    Entry entry = new Entry();
    // This is the same as H-MANs solution 
    Person person = getNullsafe(entry, e -> e.getPerson());    
    // Get object in several steps
    String givenName = getNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.getGivenName());
    // Call void methods
    doNullsafe(entry, e -> e.getPerson(), p -> p.getName(), n -> n.nameIt());        
}

/** Return result of call to f1 with o1 if it is non-null, otherwise return null. */
public static <R, T1> R getNullsafe(T1 o1, Function<T1, R> f1) {
    if (o1 != null) return f1.apply(o1);
    return null; 
}

public static <R, T0, T1> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, R> f2) {
    return getNullsafe(getNullsafe(o0, f1), f2);
}

public static <R, T0, T1, T2> R getNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Function<T2, R> f3) {
    return getNullsafe(getNullsafe(o0, f1, f2), f3);
}


/** Call consumer f1 with o1 if it is non-null, otherwise do nothing. */
public static <T1> void doNullsafe(T1 o1, Consumer<T1> f1) {
    if (o1 != null) f1.accept(o1);
}

public static <T0, T1> void doNullsafe(T0 o0, Function<T0, T1> f1, Consumer<T1> f2) {
    doNullsafe(getNullsafe(o0, f1), f2);
}

public static <T0, T1, T2> void doNullsafe(T0 o0, Function<T0, T1> f1, Function<T1, T2> f2, Consumer<T2> f3) {
    doNullsafe(getNullsafe(o0, f1, f2), f3);
}


class Entry {
    Person getPerson() { return null; }
}

class Person {
    Name getName() { return null; }
}

class Name {
    void nameIt() {}
    String getGivenName() { return null; }
}

Revert to a commit by a SHA hash in Git?

This might work:

git checkout 56e05f
echo ref: refs/heads/master > .git/HEAD
git commit

Python Decimals format

Here's a function that will do the trick:

def myformat(x):
    return ('%.2f' % x).rstrip('0').rstrip('.')

And here are your examples:

>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'

Edit:

From looking at other people's answers and experimenting, I found that g does all of the stripping stuff for you. So,

'%.3g' % x

works splendidly too and is slightly different from what other people are suggesting (using '{0:.3}'.format() stuff). I guess take your pick.

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

You can see in this List of useful HTTP headers.

X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.

How to install SignTool.exe for Windows 10

If you only want SignTool and really want to minimize the install, here is a way that I just reverse-engineered my way to:

  1. Download the .iso file from https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk (current download link is http://go.microsoft.com/fwlink/p/?LinkID=2022797) The .exe download will not work, since it's an online installer that pulls down its dependencies at runtime.
  2. Unpack the .iso with a tool such as 7-zip.
  3. Install the Installers/Windows SDK Signing Tools-x86_en-us.msi file - it's only 388 KiB large. For reference, it pulls in its files from the following .cab files, so these are also needed for a standalone install:
    • 4c3ef4b2b1dc72149f979f4243d2accf.cab (339 KiB)
    • 685f3d4691f444bc382762d603a99afc.cab (1002 KiB)
    • e5c4b31ff9997ac5603f4f28cd7df602.cab (389 KiB)
    • e98fa5eb5fee6ce17a7a69d585870b7c.cab (1.2 MiB)

There we go - you will now have the signtool.exe file and companions in C:\Program Files (x86)\Windows Kits\10\bin\10.0.17763.0\x64 (replace x64 with x86, arm or arm64 if you need it for another CPU architecture.)


It is also possible to commit signtool.exe and the other files from this folder into your version control repository if want to use it in e.g. CI scenarios. I have tried it and it seems to work fine.

(All files are probably not necessary since there are also some other .exe tools in this folder that might be responsible for these dependencies, but I am not sure which ones could be removed to make the set of files even smaller. Someone else is free to investigate further in this area. :) I tried to just copy signtool.* and that didn't work, so at least some of the other files are needed.)

CSS Font "Helvetica Neue"

Helvetica Neue is a paid font, so you shouldn't @font-face it, as you'd be freely distributing a copyrighted font. It's included in Mac systems but not in windows/linux ones, so yes, plenty of your users wont have it installed. Anyway, you can use 'Arial Narrow' as a windows substitute, which is it's windows equivalent.

how to modify the size of a column

This was done using Toad for Oracle 12.8.0.49

ALTER TABLE SCHEMA.TABLENAME 
    MODIFY (COLUMNNAME NEWDATATYPE(LENGTH)) ;

For example,

ALTER TABLE PAYROLL.EMPLOYEES 
    MODIFY (JOBTITLE VARCHAR2(12)) ;

Can you split a stream into two streams?

Shorter version that uses Lombok

import java.util.function.Consumer;
import java.util.function.Predicate;

import lombok.RequiredArgsConstructor;

/**
 * Forks a Stream using a Predicate into postive and negative outcomes.
 */
@RequiredArgsConstructor
@FieldDefaults(makeFinal = true, level = AccessLevel.PROTECTED)
public class StreamForkerUtil<T> implements Consumer<T> {
    Predicate<T> predicate;
    Consumer<T> positiveConsumer;
    Consumer<T> negativeConsumer;

    @Override
    public void accept(T t) {
        (predicate.test(t) ? positiveConsumer : negativeConsumer).accept(t);
    }
}

Save the console.log in Chrome to a file

If you're running an Apache server on your localhost (don't do this on a production server), you can also post the results to a script instead of writing it to console.

So instead of console.log, you can write:

JSONP('http://localhost/save.php', {fn: 'filename.txt', data: json});

Then save.php can do this

<?php

 $fn = $_REQUEST['fn'];
 $data = $_REQUEST['data'];

 file_put_contents("path/$fn", $data);

Is calculating an MD5 hash less CPU intensive than SHA family functions?

Yes, MD5 is somewhat less CPU-intensive. On my Intel x86 (Core2 Quad Q6600, 2.4 GHz, using one core), I get this in 32-bit mode:

MD5       411
SHA-1     218
SHA-256   118
SHA-512    46

and this in 64-bit mode:

MD5       407
SHA-1     312
SHA-256   148
SHA-512   189

Figures are in megabytes per second, for a "long" message (this is what you get for messages longer than 8 kB). This is with sphlib, a library of hash function implementations in C (and Java). All implementations are from the same author (me) and were made with comparable efforts at optimizations; thus the speed differences can be considered as really intrinsic to the functions.

As a point of comparison, consider that a recent hard disk will run at about 100 MB/s, and anything over USB will top below 60 MB/s. Even though SHA-256 appears "slow" here, it is fast enough for most purposes.

Note that OpenSSL includes a 32-bit implementation of SHA-512 which is quite faster than my code (but not as fast as the 64-bit SHA-512), because the OpenSSL implementation is in assembly and uses SSE2 registers, something which cannot be done in plain C. SHA-512 is the only function among those four which benefits from a SSE2 implementation.

Edit: on this page (archive), one can find a report on the speed of many hash functions (click on the "Telechargez maintenant" link). The report is in French, but it is mostly full of tables and numbers, and numbers are international. The implemented hash functions do not include the SHA-3 candidates (except SHABAL) but I am working on it.

ConcurrentModificationException for ArrayList

We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.

Check this post for ConcurrentHashMap

http://www.journaldev.com/122/hashmap-vs-concurrenthashmap-%E2%80%93-example-and-exploring-iterator

Bootstrap Modal Backdrop Remaining

Just in case anybody else runs into a similar issue: I found taking the class "fade" off of the modal will prevent this backdrop from sticking to the screen even after the modal is hidden. It appears to be a bug in the bootstrap.js for modals.

Another (while keeping the fade effects) would be to replace the call to jQueryElement.modal with your own custom javascript that adds the "in" class, sets display: block, and add a backdrop when showing, then to perform the opposite operations when you want to hide the modal.

Simply removing fade was sufficient for my project.

How to uninstall Ruby from /usr/local?

If ruby was installed in the following way:

./configure --prefix=/usr/local
make
sudo make install

You can uninstall it in the following way:

Check installed ruby version; lets assume 2.1.2

wget http://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.bz2
bunzip ...
tar xfv ...
cd ruby-2.1.2
./configure --prefix=/usr/local
make
sudo checkinstall
  # will build deb or rpm package and try to install it

After installation, you can now remove the package and it will remove the directories/files/etc.

sudo rpm -e ruby # or dpkg -P ruby (for Debian-like systems)

There might be some artifacts left:

Removing ruby ...
  warning: while removing ruby, directory '/usr/local/lib/ruby/gems/2.1.0/gems' not empty so not removed.
  ...

Remove them manually.

Add views below toolbar in CoordinatorLayout

I managed to fix this by adding:

android:layout_marginTop="?android:attr/actionBarSize"

to the FrameLayout like so:

 <FrameLayout
        android:id="@+id/content"
        android:layout_marginTop="?android:attr/actionBarSize"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
       />

.htaccess not working on localhost with XAMPP

Just had a similar issue

Resolved it by checking in httpd.conf

     # AllowOverride controls what directives may be placed in .htaccess files.
     # It can be "All", "None", or any combination of the keywords:
     #   Options FileInfo AuthConfig Limit
     #
     AllowOverride All   <--- make sure this is not set to "None"

It is worth bearing in mind I tried (from Mark's answer) the "put garbage in the .htaccess" which did give a server error - but even though it was being read, it wasn't being acted on due to no overrides allowed.

Get checkbox values using checkbox name using jquery

You should include the brackets as well . . .

<input type="checkbox" name="bla[]" value="1" />

therefore referencing it should be as be name='bla[]'

$(document).ready( function () { 

   $("input[name='bla[]']").each( function () {
       alert( $(this).val() );
   });

});

How do I sort a Set to a List in Java?

You can convert a set into an ArrayList, where you can sort the ArrayList using Collections.sort(List).

Here is the code:

keySet = (Set) map.keySet();
ArrayList list = new ArrayList(keySet);     
Collections.sort(list);

REST API Authentication

  1. Use HTTP Basic Auth to authenticate clients, but treat username/password only as temporary session token.

    The session token is just a header attached to every HTTP request, eg: Authorization: Basic Ym9ic2Vzc2lvbjE6czNjcmV0

    The string Ym9ic2Vzc2lvbjE6czNjcmV0 above is just the string "bobsession1:s3cret" (which is a username/password) encoded in Base64.

  2. To obtain the temporary session token above, provide an API function (eg: http://mycompany.com/apiv1/login) which takes master-username and master-password as an input, creates a temporary HTTP Basic Auth username / password on the server side, and returns the token (eg: Ym9ic2Vzc2lvbjE6czNjcmV0). This username / password should be temporary, it should expire after 20min or so.

  3. For added security ensure your REST service are served over HTTPS so that information are not transferred plaintext

If you're on Java, Spring Security library provides good support to implement above method

SSIS package creating Hresult: 0x80004005 Description: "Login timeout expired" error

I finally found the problem. The error was not the good one.

Apparently, Ole DB source have a bug that might make it crash and throw that error. I replaced the OLE DB destination with a OLE DB Command with the insert statement in it and it fixed it.

The link the got me there: http://social.msdn.microsoft.com/Forums/en-US/sqlintegrationservices/thread/fab0e3bf-4adf-4f17-b9f6-7b7f9db6523c/

Strange Bug, Hope it will help other people.