Programs & Examples On #Xserver

How to check if X server is running?

The bash script solution:

if ! xset q &>/dev/null; then
    echo "No X server at \$DISPLAY [$DISPLAY]" >&2
    exit 1
fi

Doesn't work if you login from another console (Ctrl+Alt+F?) or ssh. For me this solution works in my Archlinux:

#!/bin/sh
ps aux|grep -v grep|grep "/usr/lib/Xorg"
EXITSTATUS=$?
if [ $EXITSTATUS -eq 0 ]; then
  echo "X server running"
  exit 1
fi

You can change /usr/lib/Xorg for only Xorg or the proper command on your system.

wkhtmltopdf: cannot connect to X server

If you config wkhtmltopdf for Rails or Somethings in Centos, you can follow these step bellow:

  1. Go to https://wkhtmltopdf.org/downloads.html and copied the link of rpm file.

In centos server bash.

  1. wget link_of_wkhtmltopdf_rpm.rpm

  2. rpm -ivh link_of_wkhtmltopdf_rpm.rpm

  3. which wkhtmltopdf

=> You will get path of wkhtmltopdf.

  1. Setup for wicked_pdf or pdfkit with path in step 4. This is sample config with wickedpdf. config/initializers/wicked_pdf.rb

    if Rails.env != "production"
        path = %x[which wkhtmltopdf].gsub(/\n/, "")
    else
        path = "path_of_wkhtmltopdf_in_step_4"
    end
    WickedPdf.config = { exe_path: path }
    
  2. Restart server.

DONE.

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

In my case there was no space left in my machine and I faced the same issue. Some times it could be the space issue. Check the space in your Linux/Unix environment and make sure your machine have enough space.

Create Local SQL Server database

After installation you need to connect to Server Name : localhost to start using the local instance of SQL Server.

Once you are connected to the local instance, right click on Databases and create a new database.

Parsing json and searching through it

You can use jsonpipe if you just need the output (and more comfortable with command line):

cat bookmarks.json | jsonpipe |grep uri

Create Git branch with current changes

To add new changes to a new branch and push to remote:

git branch branch/name
git checkout branch/name
git push origin branch/name

Often times I forget to add the origin part to push and get confused why I don't see the new branch/commit in bitbucket

cleanup php session files

Debian/Ubuntu handles this with a cronjob defined in /etc/cron.d/php5

# /etc/cron.d/php5: crontab fragment for php5
#  This purges session files older than X, where X is defined in seconds
#  as the largest value of session.gc_maxlifetime from all your php.ini
#  files, or 24 minutes if not defined.  See /usr/lib/php5/maxlifetime

# Look for and purge old sessions every 30 minutes
09,39 *     * * *     root   [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm

The maxlifetime script simply returns the number of minutes a session should be kept alive by checking php.ini, it looks like this

#!/bin/sh -e

max=1440

for ini in /etc/php5/*/php.ini; do
        cur=$(sed -n -e 's/^[[:space:]]*session.gc_maxlifetime[[:space:]]*=[[:space:]]*\([0-9]\+\).*$/\1/p' $ini 2>/dev/null || true);
        [ -z "$cur" ] && cur=0
        [ "$cur" -gt "$max" ] && max=$cur
done

echo $(($max/60))

exit 0

How can I remove the last character of a string in python?

Answering the question: to remove the last character, just use:string = string[:-1].

If you want to remove the last '\' if there is one (or if there is more than one):

while string[-1]=='\\':
    string = string[:-1]

If it's a path, then use the os.path functions:

dir = "dir1\\dir2\\file.jpg\\"   #I'm using windows by the way
os.path.dirname(dir)

although I would 'add' a slash in the end to prevent missing the filename in case there's no slash at the end of the original string:

dir = "dir1\\dir2\\file.jpg"
os.path.dirname(dir + "\\")

When using abspath, (if the path isn't absolute I guess,) will add the current working directory to the path.

os.path.abspath(dir)

How to vertically align into the center of the content of a div with defined width/height?

I would say to add a paragraph with a period in it and style it like so:

<p class="center">.</p>

<style>
.center {font-size: 0px; margin-bottom: anyPercentage%;}
</style>

You may need to toy around with the percentages to get it right

How can I convert an HTML table to CSV?

Here is an example using pQuery and Spreadsheet::WriteExcel:

use strict;
use warnings;

use Spreadsheet::WriteExcel;
use pQuery;

my $workbook = Spreadsheet::WriteExcel->new( 'data.xls' );
my $sheet    = $workbook->add_worksheet;
my $row = 0;

pQuery( 'http://www.blahblah.site' )->find( 'tr' )->each( sub{
    my $col = 0;
    pQuery( $_ )->find( 'td' )->each( sub{
        $sheet->write( $row, $col++, $_->innerHTML );
    });
    $row++;
});

$workbook->close;

The example simply extracts all tr tags that it finds into an excel file. You can easily tailor it to pick up specific table or even trigger a new excel file per table tag.

Further things to consider:

  • You may want to pick up td tags to create excel header(s).
  • And you may have issues with rowspan & colspan.

To see if rowspan or colspan is being used you can:

pQuery( $data )->find( 'td' )->each( sub{ 
    my $number_of_cols_spanned = $_->getAttribute( 'colspan' );
});

Is it possible to write data to file using only JavaScript?

I found good answers here, but also found a simpler way.

The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)

You can style the link as a button using bootstrap, which is still pure javascript, except for styling.

Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.

This example needs only one button click to create the text-blob and download it:

<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary" 
   onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
   Write To File
</a>

<script>
    // URL pointing to the Blob with the file contents
    var objUrl = null;
    // create the blob with file content, and attach the URL to the downloadlink; 
    // NB: link must have the download attribute
    // this method can go to your library
    function exportFile(fileContent, downloadLinkId) {
        // revoke the old object URL to avoid memory leaks.
        if (objUrl !== null) {
            window.URL.revokeObjectURL(objUrl);
        }
        // create the object that contains the file data and that can be referred to with a URL
        var data = new Blob([fileContent], { type: 'text/plain' });
        objUrl = window.URL.createObjectURL(data);
        // attach the object to the download link (styled as button)
        var downloadLinkButton = document.getElementById(downloadLinkId);
        downloadLinkButton.href = objUrl;
    };
</script>

Android Studio - mergeDebugResources exception

inside your project directory, run:

./gradlew clean build

or from Android Studio select:

Build > Clean Project

Updated: As @VinceFior pointed out in a comment below

Windows batch files: .bat vs .cmd?

I believe if you change the value of the ComSpec environment variable to %SystemRoot%system32\cmd.exe(CMD) then it doesn't matter if the file extension is .BAT or .CMD. I'm not sure, but this may even be the default for WinXP and above.

Is std::vector copying the objects with a push_back?

Relevant in C++11 is the emplace family of member functions, which allow you to transfer ownership of objects by moving them into containers.

The idiom of usage would look like

std::vector<Object> objs;

Object l_value_obj { /* initialize */ };
// use object here...

objs.emplace_back(std::move(l_value_obj));

The move for the lvalue object is important as otherwise it would be forwarded as a reference or const reference and the move constructor would not be called.

Graphical DIFF programs for linux

Kompare is fine for diff, but I use dirdiff. Although it looks ugly, dirdiff can do 3-way merge - and you can get everything done inside the tool (both diff and merge).

Converting string to double in C#

You can try this example out. A simple C# progaram to convert string to double

class Calculations{

protected double length;
protected double height;
protected double width;

public void get_data(){

this.length = Convert.ToDouble(Console.ReadLine());
this.width  = Convert.ToDouble(Console.ReadLine());
this.height = Convert.ToDouble(Console.ReadLine());

   }
}

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

Install pip:

sudo easy_install pip

Install brew:

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

Install mysql:

brew install mysql

Install MySQLdb

sudo pip install MySQL-python

If you have compilation problems, try editing the ~/.profile file like in one of the answers here.

Casting string to enum

Use Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);

Get root view from current activity

I tested this in android 4.0.3, only:

getWindow().getDecorView().getRootView()

give the same view what we get from

anyview.getRootView();

com.android.internal.policy.impl.PhoneWindow$DecorView@#########

and

getWindow().getDecorView().findViewById(android.R.id.content)

giving child of its

android.widget.FrameLayout@#######

Please confirm.

How to change the default browser to debug with in Visual Studio 2008?

I find that the Browse With.. menu item only appears in Visual Studio 2010 when I Run as administrator. And in that case it is available even while in debug mode.

Get first day of week in SQL Server

I don't have any issues with any of the answers given here, however I do think mine is a lot simpler to implement, and understand. I have not run any performance tests on it, but it should be neglegable.

So I derived my answer from the fact that dates are stored in SQL server as integers, (I am talking about the date component only). If you don't believe me, try this SELECT CONVERT(INT, GETDATE()), and vice versa.

Now knowing this, you can do some cool math equations. You might be able to come up with a better one, but here is mine.

/*
TAKEN FROM http://msdn.microsoft.com/en-us/library/ms181598.aspx
First day of the week is
1 -- Monday
2 -- Tuesday
3 -- Wednesday
4 -- Thursday
5 -- Friday
6 -- Saturday
7 (default, U.S. English) -- Sunday
*/

--Offset is required to compensate for the fact that my @@DATEFIRST setting is 7, the default. 
DECLARE @offSet int, @testDate datetime
SELECT @offSet = 1, @testDate = GETDATE()

SELECT CONVERT(DATETIME, CONVERT(INT, @testDate) - (DATEPART(WEEKDAY, @testDate) - @offSet))

How can I check if an ip is in a network in Python?

This code is working for me on Linux x86. I haven't really given any thought to endianess issues, but I have tested it against the "ipaddr" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code.

def addressInNetwork(ip, net):
   import socket,struct
   ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
   netstr, bits = net.split('/')
   netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16)
   mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
   return (ipaddr & mask) == (netaddr & mask)

Example:

>>> print addressInNetwork('10.9.8.7', '10.9.1.0/16')
True
>>> print addressInNetwork('10.9.8.7', '10.9.1.0/24')
False

Iterate Multi-Dimensional Array with Nested Foreach Statement

int[,] arr =  { 
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
              };
 for(int i = 0; i < arr.GetLength(0); i++){
      for (int j = 0; j < arr.GetLength(1); j++)
           Console.Write( "{0}\t",arr[i, j]);
      Console.WriteLine();
    }

output:  1  2  3
         4  5  6
         7  8  9

When should I use UNSIGNED and SIGNED INT in MySQL?

For negative integer value, SIGNED is used and for non-negative integer value, UNSIGNED is used. It always suggested to use UNSIGNED for id as a PRIMARY KEY.

ReferenceError: describe is not defined NodeJs

You can also do like this:

  var mocha = require('mocha')
  var describe = mocha.describe
  var it = mocha.it
  var assert = require('chai').assert

  describe('#indexOf()', function() {
    it('should return -1 when not present', function() {
      assert.equal([1,2,3].indexOf(4), -1)
    })
  })

Reference: http://mochajs.org/#require

Why are elementwise additions much faster in separate loops than in a combined loop?

The first loop alternates writing in each variable. The second and third ones only make small jumps of element size.

Try writing two parallel lines of 20 crosses with a pen and paper separated by 20 cm. Try once finishing one and then the other line and try another time by writting a cross in each line alternately.

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

  • In this problem is solved in following three steps: 1. Divide - Dividing into number of sub-problems 2. Conquer - Conquering by solving sub-problems recursively 3. Combine - Combining sub-problem solutions to get original problem's solution
  • Recursive approach
  • Top Down technique
  • Example: Merge Sort

Dynamic Programming

  • In this the problem is solved in following steps: 1. Defining structure of optimal solution 2. Defines value of optimal solutions repeatedly. 3. Obtaining values of optimal solution in bottom-up fashion 4. Getting final optimal solution from obtained values
  • Non-Recursive
  • Bottom Up Technique
  • Example: Strassen's Matrix Multiplication

Count characters in textarea

HTML

<form method="post">
<textarea name="postes" id="textAreaPost" placeholder="Write what's you new" maxlength="500"></textarea>

<div id="char_namb" style="padding: 4px; float: right; font-size: 20px; font-family: Cocon; text-align: center;">500 : 0</div>
</form>

jQuery

$(function(){
    $('#textAreaPost').keyup(function(){
      var charsno = $(this).val().length;
      $('#char_namb').html("500 : " + charsno);
    });
});

How can you encode a string to Base64 in JavaScript?

You can use btoa (to base-64) and atob (from base-64).

For IE 9 and below, try the jquery-base64 plugin:

$.base64.encode("this is a test");
$.base64.decode("dGhpcyBpcyBhIHRlc3Q=");

Catch checked change event of a checkbox

<input type="checkbox" id="something" />

$("#something").click( function(){
   if( $(this).is(':checked') ) alert("checked");
});

Edit: Doing this will not catch when the checkbox changes for other reasons than a click, like using the keyboard. To avoid this problem, listen to changeinstead of click.

For checking/unchecking programmatically, take a look at Why isn't my checkbox change event triggered?

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

and if you don't have the option to go on java8 better use 'yyyy-MM-dd'T'HH:mm:ssXXX' as this gets correctly parsed again (while with only one X this may not be the case... depending on your parsing function)

X generates: +01

XXX generates: +01:00

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

I had the similar issue. The problem was in the passwords: the Keystore and private key used different passwords. (KeyStore explorer was used)

After creating Keystore with the same password as private key had the issue was resolved.

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

await vs Task.Wait - Deadlock?

Based on what I read from different sources:

An await expression does not block the thread on which it is executing. Instead, it causes the compiler to sign up the rest of the async method as a continuation on the awaited task. Control then returns to the caller of the async method. When the task completes, it invokes its continuation, and execution of the async method resumes where it left off.

To wait for a single task to complete, you can call its Task.Wait method. A call to the Wait method blocks the calling thread until the single class instance has completed execution. The parameterless Wait() method is used to wait unconditionally until a task completes. The task simulates work by calling the Thread.Sleep method to sleep for two seconds.

This article is also a good read.

What does yield mean in PHP?

With yield you can easily describe the breakpoints between multiple tasks in a single function. That's all, there is nothing special about it.

$closure = function ($injected1, $injected2, ...){
    $returned = array();
    //task1 on $injected1
    $returned[] = $returned1;
//I need a breakpoint here!!!!!!!!!!!!!!!!!!!!!!!!!
    //task2 on $injected2
    $returned[] = $returned2;
    //...
    return $returned;
};
$returned = $closure($injected1, $injected2, ...);

If task1 and task2 are highly related, but you need a breakpoint between them to do something else:

  • free memory between processing database rows
  • run other tasks which provide dependency to the next task, but which are unrelated by understanding the current code
  • doing async calls and wait for the results
  • and so on ...

then generators are the best solution, because you don't have to split up your code into many closures or mix it with other code, or use callbacks, etc... You just use yield to add a breakpoint, and you can continue from that breakpoint if you are ready.

Add breakpoint without generators:

$closure1 = function ($injected1){
    //task1 on $injected1
    return $returned1;
};
$closure2 = function ($injected2){
    //task2 on $injected2
    return $returned1;
};
//...
$returned1 = $closure1($injected1);
//breakpoint between task1 and task2
$returned2 = $closure2($injected2);
//...

Add breakpoint with generators

$closure = function (){
    $injected1 = yield;
    //task1 on $injected1
    $injected2 = (yield($returned1));
    //task2 on $injected2
    $injected3 = (yield($returned2));
    //...
    yield($returnedN);
};
$generator = $closure();
$returned1 = $generator->send($injected1);
//breakpoint between task1 and task2
$returned2 = $generator->send($injected2);
//...
$returnedN = $generator->send($injectedN);

note: It is easy to make mistake with generators, so always write unit tests before you implement them! note2: Using generators in an infinite loop is like writing a closure which has infinite length...

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

Find the smallest positive integer that does not occur in a given sequence

Late joining the conversation. Based on:

https://codereview.stackexchange.com/a/179091/184415

There is indeed an O(n) complexity solution to this problem even if duplicate ints are involved in the input:

solution(A)
Filter out non-positive values from A
For each int in filtered
    Let a zero-based index be the absolute value of the int - 1
    If the filtered range can be accessed by that index  and  filtered[index] is not negative
        Make the value in filtered[index] negative

For each index in filtered
    if filtered[index] is positive
        return the index + 1 (to one-based)

If none of the elements in filtered is positive
    return the length of filtered + 1 (to one-based)

So an array A = [1, 2, 3, 5, 6], would have the following transformations:

abs(A[0]) = 1, to_0idx = 0, A[0] = 1, make_negative(A[0]), A = [-1,  2,  3,  5,  6]
abs(A[1]) = 2, to_0idx = 1, A[1] = 2, make_negative(A[1]), A = [-1, -2,  3,  5,  6]
abs(A[2]) = 3, to_0idx = 2, A[2] = 3, make_negative(A[2]), A = [-1, -2, -3,  5,  6]
abs(A[3]) = 5, to_0idx = 4, A[4] = 6, make_negative(A[4]), A = [-1, -2, -3,  5, -6]
abs(A[4]) = 6, to_0idx = 5, A[5] is inaccessible,          A = [-1, -2, -3,  5, -6]

A linear search for the first positive value returns an index of 3. Converting back to a one-based index results in solution(A)=3+1=4

Here's an implementation of the suggested algorithm in C# (should be trivial to convert it over to Java lingo - cut me some slack common):

public int solution(int[] A)
{
    var positivesOnlySet = A
        .Where(x => x > 0)
        .ToArray();

    if (!positivesOnlySet.Any())
        return 1;

    var totalCount = positivesOnlySet.Length;
    for (var i = 0; i < totalCount; i++) //O(n) complexity
    {
        var abs = Math.Abs(positivesOnlySet[i]) - 1;
        if (abs < totalCount && positivesOnlySet[abs] > 0) //notice the greater than zero check 
            positivesOnlySet[abs] = -positivesOnlySet[abs];
    }

    for (var i = 0; i < totalCount; i++) //O(n) complexity
    {
        if (positivesOnlySet[i] > 0)
            return i + 1;
    }

    return totalCount + 1;
}

Error: Jump to case label

C++11 standard on jumping over some initializations

JohannesD gave an explanation, now for the standards.

The C++11 N3337 standard draft 6.7 "Declaration statement" says:

3 It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (87) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

87) The transfer from the condition of a switch statement to a case label is considered a jump in this respect.

[ Example:

void f() {
   // ...
  goto lx;    // ill-formed: jump into scope of a
  // ...
ly:
  X a = 1;
  // ...
lx:
  goto ly;    // OK, jump implies destructor
              // call for a followed by construction
              // again immediately following label ly
}

— end example ]

As of GCC 5.2, the error message now says:

crosses initialization of

C

C allows it: c99 goto past initialization

The C99 N1256 standard draft Annex I "Common warnings" says:

2 A block with initialization of an object that has automatic storage duration is jumped into

Multiple Inheritance in C#

We all seem to be heading down the interface path with this, but the obvious other possibility, here, is to do what OOP is supposed to do, and build up your inheritance tree... (isn't this what class design is all about?)

class Program
{
    static void Main(string[] args)
    {
        human me = new human();
        me.legs = 2;
        me.lfType = "Human";
        me.name = "Paul";
        Console.WriteLine(me.name);
    }
}

public abstract class lifeform
{
    public string lfType { get; set; }
}

public abstract class mammal : lifeform 
{
    public int legs { get; set; }
}

public class human : mammal
{
    public string name { get; set; }
}

This structure provides reusable blocks of code and, surely, is how OOP code should be written?

If this particular approach doesn't quite fit the bill the we simply create new classes based on the required objects...

class Program
{
    static void Main(string[] args)
    {
        fish shark = new fish();
        shark.size = "large";
        shark.lfType = "Fish";
        shark.name = "Jaws";
        Console.WriteLine(shark.name);
        human me = new human();
        me.legs = 2;
        me.lfType = "Human";
        me.name = "Paul";
        Console.WriteLine(me.name);
    }
}

public abstract class lifeform
{
    public string lfType { get; set; }
}

public abstract class mammal : lifeform 
{
    public int legs { get; set; }
}

public class human : mammal
{
    public string name { get; set; }
}

public class aquatic : lifeform
{
    public string size { get; set; }
}

public class fish : aquatic
{
    public string name { get; set; }
}

Conversion of Char to Binary in C

Your code is very vague and not understandable, but I can provide you with an alternative.

First of all, if you want temp to go through the whole string, you can do something like this:

char *temp;
for (temp = your_string; *temp; ++temp)
    /* do something with *temp */

The term *temp as the for condition simply checks whether you have reached the end of the string or not. If you have, *temp will be '\0' (NUL) and the for ends.

Now, inside the for, you want to find the bits that compose *temp. Let's say we print the bits:

for (as above)
{
    int bit_index;
    for (bit_index = 7; bit_index >= 0; --bit_index)
    {
        int bit = *temp >> bit_index & 1;
        printf("%d", bit);
    }
    printf("\n");
}

To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7 to bit_index = sizeof(*temp)*8-1

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

Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.

    //simpleExample
    Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u,  someTable s WHERE s.user_id = u.id", 
NameSomething.class);
    List list = (List<NameSomething.class>) query.getResultList();

Entity class:

    @Entity
    public class NameSomething {

        @Id
        private String name;

        private String something;

        // getters/setters



        /**
         * Generic put method to map JPA native Query to this object.
         *
         * @param column
         * @param value
         */
        public void put(Object column, Object value) {
            if (((String) column).equals("name")) {
                setName(String) value);
            } else if (((String) column).equals("something")) {
                setSomething((String) value);
            }
        }
    }

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

In SQL Server 2012, 2014:

USE mydb
GO

ALTER ROLE db_datareader ADD MEMBER MYUSER
GO
ALTER ROLE db_datawriter ADD MEMBER MYUSER
GO

In SQL Server 2008:

use mydb
go

exec sp_addrolemember db_datareader, MYUSER 
go
exec sp_addrolemember db_datawriter, MYUSER 
go

To also assign the ability to execute all Stored Procedures for a Database:

GRANT EXECUTE TO MYUSER;

To assign the ability to execute specific stored procedures:

GRANT EXECUTE ON dbo.sp_mystoredprocedure TO MYUSER;

How to read a configuration file in Java

It depends.

Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding

And if none of those meet your particular needs, you could even look at using some kind of Database

How to set an environment variable from a Gradle build?

You can also "prepend" the environment variable setting by using 'environment' command:

run.doFirst { environment 'SPARK_LOCAL_IP', 'localhost' }

hide/show a image in jquery

Use the .css() jQuery manipulators, or better yet just call .show()/.hide() on the image once you've obtained a handle to it (e.g. $('#img' + id)).

BTW, you should not write javascript handlers with the "javascript:" prefix.

android: how to use getApplication and getApplicationContext from non activity / service class

Casting a Context object to an Activity object compiles fine.

Try this:

((Activity) mContext).getApplication(...)

Remove HTML Tags in Javascript with Regex

Here is how TextAngular (WYSISYG Editor) is doing it. I also found this to be the most consistent answer, which is NO REGEX.

@license textAngular
Author : Austin Anderson
License : 2013 MIT
Version 1.5.16
// turn html into pure text that shows visiblity
function stripHtmlToText(html)
{
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    var res = tmp.textContent || tmp.innerText || '';
    res.replace('\u200B', ''); // zero width space
    res = res.trim();
    return res;
}

Cast int to varchar

I solved a problem to comparing a integer Column x a varchar column with

where CAST(Column_name AS CHAR CHARACTER SET latin1 ) collate latin1_general_ci = varchar_column_name

String contains - ignore case

You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:

Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();

How to draw checkbox or tick mark in GitHub Markdown table?

You can use emojis

Done? | Name
:---:| ---
??| Nope
?| Yep

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

Why is "cursor:pointer" effect in CSS not working

Position the element as relative and then use z-index, it worked for me :)

Get the list of stored procedures created and / or modified on a particular date?

Here is the "newer school" version.

SELECT * FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = N'PROCEDURE' and ROUTINE_SCHEMA = N'dbo' 
and CREATED = '20120927'

How to remove all non-alpha numeric characters from a string in MySQL?

Since MySQL 8.0 you can use regular expression to remove non alphanumeric characters from a string. There is method REGEXP_REPLACE

Here is the code to remove non-alphanumeric characters:

UPDATE {table} SET {column} = REGEXP_REPLACE({column}, '[^0-9a-zA-Z ]', '')

How to read HDF5 files in Python

from keras.models import load_model 

h= load_model('FILE_NAME.h5')

Removing array item by value

Your solutions only work if you have unique values in your array

See:

<?php
$trans = array("a" => 1, "b" => 1, "c" => 2);
$trans = array_flip($trans);
print_r($trans);
?>

A better way would be unset with array_search, in a loop if neccessary.

How to register multiple implementations of the same interface in Asp.Net Core?

How about a service for services?

If we had an INamedService interface (with .Name property), we could write an IServiceCollection extension for .GetService(string name), where the extension would take that string parameter, and do a .GetServices() on itself, and in each returned instance, find the instance whose INamedService.Name matches the given name.

Like this:

public interface INamedService
{
    string Name { get; }
}

public static T GetService<T>(this IServiceProvider provider, string serviceName)
    where T : INamedService
{
    var candidates = provider.GetServices<T>();
    return candidates.FirstOrDefault(s => s.Name == serviceName);
}

Therefore, your IMyService must implement INamedService, but you'll get the key-based resolution you want, right?

To be fair, having to even have this INamedService interface seems ugly, but if you wanted to go further and make things more elegant, then a [NamedServiceAttribute("A")] on the implementation/class could be found by the code in this extension, and it'd work just as well. To be even more fair, Reflection is slow, so an optimization may be in order, but honestly that's something the DI engine should've been helping with. Speed and simplicity are each grand contributors to TCO.

All in all, there's no need for an explicit factory, because "finding a named service" is such a reusable concept, and factory classes don't scale as a solution. And a Func<> seems fine, but a switch block is so bleh, and again, you'll be writing Funcs as often as you'd be writing Factories. Start simple, reusable, with less code, and if that turns out not to do it for ya, then go complex.

How to keep the header static, always on top while scrolling?

_x000D_
_x000D_
.header {_x000D_
  position: fixed;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 88px;_x000D_
  z-index: 10;_x000D_
  background: #eeeeee;_x000D_
  -webkit-box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
  -moz-box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
  box-shadow: 0 7px 8px rgba(0, 0, 0, 0.12);_x000D_
}_x000D_
_x000D_
.header__content-text {_x000D_
  text-align: center;_x000D_
  padding: 15px 20px;_x000D_
}_x000D_
_x000D_
.page__content-container {_x000D_
  margin: 100px auto;_x000D_
  width: 975px;_x000D_
  padding: 30px;_x000D_
}
_x000D_
<div class="header">_x000D_
  <h1 class="header__content-text">_x000D_
    Header content will come here_x000D_
  </h1>_x000D_
</div>_x000D_
<div class="page__content-container">_x000D_
  <div style="height:600px;">_x000D_
    <a href="http://imgur.com/k9hz3">_x000D_
      <img src="http://i.imgur.com/k9hz3.jpg" title="Hosted by imgur.com" alt="" />_x000D_
    </a>_x000D_
  </div>_x000D_
  <div style="height:600px;">_x000D_
    <a href="http://imgur.com/TXuFQ">_x000D_
      <img src="http://i.imgur.com/TXuFQ.jpg" title="Hosted by imgur.com" alt="" />_x000D_
    </a>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Do standard windows .ini files allow comments?

Windows INI API support for:

  • Line comments: yes, using semi-colon ;
  • Trailing comments: No

The authoritative source is the Windows API function that reads values out of INI files

GetPrivateProfileString

Retrieves a string from the specified section in an initialization file.

The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini file contents:

[Application]
UseLiveData=1
;coke=zero
pepsi=diet   ;gag
#stackoverflow=splotchy

Reading the values:

  • UseLiveData: 1
  • coke: not present
  • ;coke: not present
  • pepsi: diet ;gag
  • stackoverflow: not present
  • #stackoverflow: splotchy

Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow is because the name stackoverflow no longer exists. And it turns out that semi-colon (;) is a line-comment.

But there is no support for trailing comments.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Go to Xcode's breakpoints tab. Use the button at the bottom to add an exception breakpoint. Now you'll see what code is invoking setValue:forKey: and the associated stack. With luck that'll point you straight at the problem's source.

Odd that your class is LoginScreen, yet the error is saying someone is using "LoginScreen" as a key. Check that LoginScreen.m is part of your target.

enter image description here


Footnote: with Swift a common problem arises if you change the name of a class (so, you rename it everywhere in your code). Storyboard struggles with this, and you usually have to re-drag any connections involving that class. And in particular, re-enter the name of the class anywhere used in IdentityInspector tab on the right. (In the picture example I deliberately misspelled the class name. But the same thing often happens when you rename a class; even though it's seemingly correct in IdentityInspector, you need to enter the name again; it will correctly autocomplete and you're good to go.)

Install Node.js on Ubuntu

Simply follow the instructions given here:

Example install:

sudo apt-get install python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

It installs current stable Node on the current stable Ubuntu. Quantal (12.10) users may need to install the software-properties-common package for the add-apt-repository command to work: sudo apt-get install software-properties-common

As of Node.js v0.10.0, the nodejs package from Chris Lea's repo includes both npm and nodejs-dev.

Don't give sudo apt-get install nodejs npm. Just sudo apt-get install nodejs.

Why I got " cannot be resolved to a type" error?

Maybe wrong path..? Check your .classpath file.

How to overwrite existing files in batch?

If destination file is read only use /y/r

xcopy /y/r source.txt dest.txt

Create nice column output in python

Here is a variation of the Shawn Chin's answer. The width is fixed per column, not over all columns. There is also a border below the first row and between the columns. (icontract library is used to enforce the contracts.)

@icontract.pre(
    lambda table: not table or all(len(row) == len(table[0]) for row in table))
@icontract.post(lambda table, result: result == "" if not table else True)
@icontract.post(lambda result: not result.endswith("\n"))
def format_table(table: List[List[str]]) -> str:
    """
    Format the table as equal-spaced columns.

    :param table: rows of cells
    :return: table as string
    """
    cols = len(table[0])

    col_widths = [max(len(row[i]) for row in table) for i in range(cols)]

    lines = []  # type: List[str]
    for i, row in enumerate(table):
        parts = []  # type: List[str]

        for cell, width in zip(row, col_widths):
            parts.append(cell.ljust(width))

        line = " | ".join(parts)
        lines.append(line)

        if i == 0:
            border = []  # type: List[str]

            for width in col_widths:
                border.append("-" * width)

            lines.append("-+-".join(border))

    result = "\n".join(lines)

    return result

Here is an example:

>>> table = [['column 0', 'another column 1'], ['00', '01'], ['10', '11']]
>>> result = packagery._format_table(table=table)
>>> print(result)
column 0 | another column 1
---------+-----------------
00       | 01              
10       | 11              

Is it not possible to stringify an Error using JSON.stringify?

You can also just redefine those non-enumerable properties to be enumerable.

Object.defineProperty(Error.prototype, 'message', {
    configurable: true,
    enumerable: true
});

and maybe stack property too.

How many parameters are too many?

One thing I would point out from a performance perspective is that depending on how you pass parameters to a method, passing lots of parameters by value will slow the program down because each parameter has to be copied and then placed on the stack.

Using a single class to encompass all of the parameters would work better because a single parameter passed by reference would be elegant and cleaner, and quicker!

Local dependency in package.json

This works for me.

Place the following in your package.json file

"scripts": {
    "preinstall": "npm install ../my-own-module/"
}

How to set a default value for an existing column

ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]

How do I increase the capacity of the Eclipse output console?

Window > Preferences, go to the Run/Debug > Console section >> "Limit console output.>>Console buffer size(characters):" (This option can be seen in Eclipse Indigo ,but it limits buffer size at 1,000,000 )

Most useful NLog configurations

Reporting to an external website/database

I wanted a way to simply and automatically report errors (since users often don't) from our applications. The easiest solution I could come up with was a public URL - a web page which could take input and store it to a database - that is sent data upon an application error. (The database could then be checked by a dev or a script to know if there are new errors.)

I wrote the web page in PHP and created a mysql database, user, and table to store the data. I decided on four user variables, an id, and a timestamp. The possible variables (either included in the URL or as POST data) are:

  • app (application name)
  • msg (message - e.g. Exception occurred ...)
  • dev (developer - e.g. Pat)
  • src (source - this would come from a variable pertaining to the machine on which the app was running, e.g. Environment.MachineName or some such)
  • log (a log file or verbose message)

(All of the variables are optional, but nothing is reported if none of them are set - so if you just visit the website URL nothing is sent to the db.)

To send the data to the URL, I used NLog's WebService target. (Note, I had a few problems with this target at first. It wasn't until I looked at the source that I figured out that my url could not end with a /.)

All in all, it's not a bad system for keeping tabs on external apps. (Of course, the polite thing to do is to inform your users that you will be reporting possibly sensitive data and to give them a way to opt in/out.)

MySQL stuff

(The db user has only INSERT privileges on this one table in its own database.)

CREATE TABLE `reports` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `ts` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `applicationName` text,
  `message` text,
  `developer` text,
  `source` text,
  `logData` longtext,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='storage place for reports from external applications'

Website code

(PHP 5.3 or 5.2 with PDO enabled, file is index.php in /report folder)

<?php
$app = $_REQUEST['app'];
$msg = $_REQUEST['msg'];
$dev = $_REQUEST['dev'];
$src = $_REQUEST['src'];
$log = $_REQUEST['log'];

$dbData =
    array(  ':app' => $app,
            ':msg' => $msg,
            ':dev' => $dev,
            ':src' => $src,
            ':log' => $log
    );
//print_r($dbData); // For debugging only! This could allow XSS attacks.
if(isEmpty($dbData)) die("No data provided");

try {
$db = new PDO("mysql:host=$host;dbname=reporting", "reporter", $pass, array(
    PDO::ATTR_PERSISTENT => true
));
$s = $db->prepare("INSERT INTO reporting.reports 
    (
    applicationName, 
    message, 
    developer, 
    source, 
    logData
    )
    VALUES
    (
    :app, 
    :msg, 
    :dev, 
    :src, 
    :log
    );"
    );
$s->execute($dbData);
print "Added report to database";
} catch (PDOException $e) {
// Sensitive information can be displayed if this exception isn't handled
//print "Error!: " . $e->getMessage() . "<br/>";
die("PDO error");
}

function isEmpty($array = array()) {
    foreach ($array as $element) {
        if (!empty($element)) {
            return false;
        }
    }
    return true;
}
?>

App code (NLog config file)

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      throwExceptions="true" internalLogToConsole="true" internalLogLevel="Warn" internalLogFile="nlog.log">
    <variable name="appTitle" value="My External App"/>
    <variable name="csvPath" value="${specialfolder:folder=Desktop:file=${appTitle} log.csv}"/>
    <variable name="developer" value="Pat"/>

    <targets async="true">
        <!--The following will keep the default number of log messages in a buffer and write out certain levels if there is an error and other levels if there is not. Messages that appeared before the error (in code) will be included, since they are buffered.-->
        <wrapper-target xsi:type="BufferingWrapper" name="smartLog">
            <wrapper-target xsi:type="PostFilteringWrapper">
                <target xsi:type="File" fileName="${csvPath}"
                archiveAboveSize="4194304" concurrentWrites="false" maxArchiveFiles="1" archiveNumbering="Sequence"
                >
                    <layout xsi:type="CsvLayout" delimiter="Comma" withHeader="false">
                        <column name="time" layout="${longdate}" />
                        <column name="level" layout="${level:upperCase=true}"/>
                        <column name="message" layout="${message}" />
                        <column name="callsite" layout="${callsite:includeSourcePath=true}" />
                        <column name="stacktrace" layout="${stacktrace:topFrames=10}" />
                        <column name="exception" layout="${exception:format=ToString}"/>
                        <!--<column name="logger" layout="${logger}"/>-->
                    </layout>
                </target>

                 <!--during normal execution only log certain messages--> 
                <defaultFilter>level >= LogLevel.Warn</defaultFilter>

                 <!--if there is at least one error, log everything from trace level--> 
                <when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
            </wrapper-target>
        </wrapper-target>

        <target xsi:type="WebService" name="web"
                url="http://example.com/report" 
                methodName=""
                namespace=""
                protocol="HttpPost"
                >
            <parameter name="app" layout="${appTitle}"/>
            <parameter name="msg" layout="${message}"/>
            <parameter name="dev" layout="${developer}"/>
            <parameter name="src" layout="${environment:variable=UserName} (${windows-identity}) on ${machinename} running os ${environment:variable=OSVersion} with CLR v${environment:variable=Version}"/>
            <parameter name="log" layout="${file-contents:fileName=${csvPath}}"/>
        </target>

    </targets>

    <rules>
        <logger name="*" minlevel="Trace" writeTo="smartLog"/>
        <logger name="*" minlevel="Error" writeTo="web"/>
    </rules>
</nlog>

Note: there may be some issues with the size of the log file, but I haven't figured out a simple way to truncate it (e.g. a la *nix's tail command).

Omitting all xsi and xsd namespaces when serializing an object in .NET?

This is the first of my two answers to the question.

If you want fine control over the namespaces - for example if you want to omit some of them but not others, or if you want to replace one namespace with another, you can do this using XmlAttributeOverrides.

Suppose you have this type definition:

// explicitly specify a namespace for this type,
// to be used during XML serialization.
[XmlRoot(Namespace="urn:Abracadabra")]
public class MyTypeWithNamespaces
{
    // private fields backing the properties
    private int _Epoch;
    private string _Label;

    // explicitly define a distinct namespace for this element
    [XmlElement(Namespace="urn:Whoohoo")]
    public string Label
    {
        set {  _Label= value; } 
        get { return _Label; } 
    }

    // this property will be implicitly serialized to XML using the
    // member name for the element name, and inheriting the namespace from
    // the type.
    public int Epoch
    {
        set {  _Epoch= value; } 
        get { return _Epoch; } 
    }
}

And this serialization pseudo-code:

        var o2= new MyTypeWithNamespaces() { ..initializers...};
        ns.Add( "", "urn:Abracadabra" );
        XmlSerializer s2 = new XmlSerializer(typeof(MyTypeWithNamespaces));
        s2.Serialize(System.Console.Out, o2, ns);

You would get something like this XML:

<MyTypeWithNamespaces xmlns="urn:Abracadabra">
  <Label xmlns="urn:Whoohoo">Cimsswybclaeqjh</Label>
  <Epoch>97</Epoch>
</MyTypeWithNamespaces>

Notice that there is a default namespace on the root element, and there is also a distinct namespace on the "Label" element. These namespaces were dictated by the attributes decorating the type, in the code above.

The Xml Serialization framework in .NET includes the possibility to explicitly override the attributes that decorate the actual code. You do this with the XmlAttributesOverrides class and friends. Suppose I have the same type, and I serialize it this way:

        // instantiate the container for all attribute overrides
        XmlAttributeOverrides xOver = new XmlAttributeOverrides();

        // define a set of XML attributes to apply to the root element
        XmlAttributes xAttrs1 = new XmlAttributes();

        // define an XmlRoot element (as if [XmlRoot] had decorated the type)
        // The namespace in the attribute override is the empty string. 
        XmlRootAttribute xRoot = new XmlRootAttribute() { Namespace = ""};

        // add that XmlRoot element to the container of attributes
        xAttrs1.XmlRoot= xRoot;

        // add that bunch of attributes to the container holding all overrides
        xOver.Add(typeof(MyTypeWithNamespaces), xAttrs1);

        // create another set of XML Attributes
        XmlAttributes xAttrs2 = new XmlAttributes();

        // define an XmlElement attribute, for a type of "String", with no namespace
        var xElt = new XmlElementAttribute(typeof(String)) { Namespace = ""};

        // add that XmlElement attribute to the 2nd bunch of attributes
        xAttrs2.XmlElements.Add(xElt);

        // add that bunch of attributes to the container for the type, and
        // specifically apply that bunch to the "Label" property on the type.
        xOver.Add(typeof(MyTypeWithNamespaces), "Label", xAttrs2);

        // instantiate a serializer with the overrides 
        XmlSerializer s3 = new XmlSerializer(typeof(MyTypeWithNamespaces), xOver);

        // serialize
        s3.Serialize(System.Console.Out, o2, ns2);

The result looks like this;

<MyTypeWithNamespaces>
  <Label>Cimsswybclaeqjh</Label>
  <Epoch>97</Epoch>
</MyTypeWithNamespaces>

You have stripped the namespaces.

A logical question is, can you strip all namespaces from arbitrary types during serialization, without going through the explicit overrides? The answer is YES, and how to do it is in my next response.

using jQuery .animate to animate a div from right to left?

I think the reason it doesn't work has something to do with the fact that you have the right position set, but not the left.

If you manually set the left to the current position, it seems to go:

Live example: http://jsfiddle.net/XqqtN/

var left = $('#coolDiv').offset().left;  // Get the calculated left position

$("#coolDiv").css({left:left})  // Set the left to its calculated position
             .animate({"left":"0px"}, "slow");

EDIT:

Appears as though Firefox behaves as expected because its calculated left position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto for the left position.

Because auto is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o)

Setting the left position manually before the animate as above fixes the issue.


If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable:

$("#coolDiv").css('left', function(){ return $(this).offset().left; })
             .animate({"left":"0px"}, "slow");    ?

Copying data from one SQLite database to another

You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.

INSERT INTO X.TABLE SELECT * FROM Y.TABLE;

Or, if the columns are not matched up in order:

INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;

Which type of folder structure should be used with Angular 2?

Maybe something like this structure:

|-- app
     |-- modules
       |-- home
           |-- [+] components
           |-- pages
              |-- home
              |-- home.component.ts|html|scss|spec
           |-- home-routing.module.ts
           |-- home.module.ts
     |-- core
       |-- authentication
           |-- authentication.service.ts|spec.ts
       |-- footer
           |-- footer.component.ts|html|scss|spec.ts
       |-- guards
           |-- auth.guard.ts
           |-- no-auth-guard.ts
           |-- admin-guard.ts 
       |-- http
           |-- user
               |-- user.service.ts|spec.ts
           |-- api.service.ts|spec.ts
       |-- interceptors
           |-- api-prefix.interceptor.ts
           |-- error-handler.interceptor.ts
           |-- http.token.interceptor.ts
       |-- mocks
           |-- user.mock.ts
       |-- services
           |-- srv1.service.ts|spec.ts
           |-- srv2.service.ts|spec.ts
       |-- header
           |-- header.component.ts|html|scss|spec.ts
       |-- core.module.ts
       |-- ensureModuleLoadedOnceGuard.ts
       |-- logger.service.ts
     |-- shared
          |-- components
              |-- loader
                  |-- loader.component.ts|html|scss|spec.ts
          |-- buttons
              |-- favorite-button
                  |-- favorite-button.component.ts|html|scss|spec.ts
              |-- collapse-button
                  |-- collapse-button.component.ts|html|scss|spec.ts
          |-- directives
              |-- auth.directive.ts|spec.ts
          |-- pipes
              |-- capitalize.pipe.ts
              |-- safe.pipe.ts
     |-- configs
         |-- app-settings.config.ts
         |-- dt-norwegian.config.ts
     |-- scss
          |-- [+] partials
          |-- _base.scss
          |-- styles.scss
     |-- assets

Import SQL file into mysql

From the mysql console:

mysql> use DATABASE_NAME;

mysql> source path/to/file.sql;


make sure there is no slash before path if you are referring to a relative path... it took me a while to realize that! lol

How to get the device's IMEI/ESN programmatically in android?

New Update:

For Android Version 6 And Above, WLAN MAC Address has been deprecated , follow Trevor Johns answer

Update:

For uniquely Identification of devices, You can Use Secure.ANDROID_ID.

Old Answer:

Disadvantages of using IMEI as Unique Device ID:

  • IMEI is dependent on the Simcard slot of the device, so it is not possible to get the IMEI for the devices that do not use Simcard. In Dual sim devices, we get 2 different IMEIs for the same device as it has 2 slots for simcard.

You can Use The WLAN MAC Address string (Not Recommended For Marshmallow and Marshmallow+ as WLAN MAC Address has been deprecated on Marshmallow forward. So you'll get a bogus value)

We can get the Unique ID for android phones using the WLAN MAC address also. The MAC address is unique for all devices and it works for all kinds of devices.

Advantages of using WLAN MAC address as Device ID:

  • It is unique identifier for all type of devices (smart phones and tablets).

  • It remains unique if the application is reinstalled

Disadvantages of using WLAN MAC address as Device ID:

  • Give You a Bogus Value from Marshmallow and above.

  • If device doesn’t have wifi hardware then you get null MAC address, but generally it is seen that most of the Android devices have wifi hardware and there are hardly few devices in the market with no wifi hardware.

SOURCE : technetexperts.com

Pass a PHP string to a JavaScript variable (and escape newlines)

If you use a templating engine to construct your HTML then you can fill it with what ever you want!

Check out XTemplates. It's a nice, open source, lightweight, template engine.

Your HTML/JS there would look like this:

<script>
    var myvar = {$MyVarValue};
</script>

How to undo a git pull?

From https://git-scm.com/docs/git-reset#Documentation/git-reset.txt-Undoamergeorpullinsideadirtyworkingtree

Undo a merge or pull inside a dirty working tree

$ git pull           (1)
Auto-merging nitfol
Merge made by recursive.
 nitfol               |   20 +++++----
 ...
$ git reset --merge ORIG_HEAD      (2)

Even if you may have local modifications in your working tree, you can safely say git pull when you know that the change in the other branch does not overlap with them.

After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running git reset --hard ORIG_HEAD will let you go back to where you were, but it will discard your local changes, which you do not want. git reset --merge keeps your local changes.

See also https://stackoverflow.com/a/30345382/621690

JavaScript - Replace all commas in a string

var mystring = "this,is,a,test"
mystring.replace(/,/g, "newchar");

Use the global(g) flag

Simple DEMO

img tag displays wrong orientation

If you have access to Linux, then open a terminal, cd to the directory containing your images and then run

mogrify -auto-orient *

This should permanently fix the orientation issues on all the images.

How does autowiring work in Spring?

In simple words Autowiring, wiring links automatically, now comes the question who does this and which kind of wiring. Answer is: Container does this and Secondary type of wiring is supported, primitives need to be done manually.

Question: How container know what type of wiring ?

Answer: We define it as byType,byName,constructor.

Question: Is there are way we do not define type of autowiring ?

Answer: Yes, it's there by doing one annotation, @Autowired.

Question: But how system know, I need to pick this type of secondary data ?

Answer: You will provide that data in you spring.xml file or by using sterotype annotations to your class so that container can themselves create the objects for you.

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

How do I get rid of the b-prefix in a string in python?

Assuming you don't want to immediately decode it again like others are suggesting here, you can parse it to a string and then just strip the leading 'b and trailing '.

>>> x = "Hi there " 
>>> x = "Hi there ".encode("utf-8") 
>>> x
b"Hi there \xef\xbf\xbd"
>>> str(x)[2:-1]
"Hi there \\xef\\xbf\\xbd"   

How to use a jQuery plugin inside Vue

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

Conversion failed when converting the varchar value to data type int in sql

The problem located on the following line

SELECT  @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))

Use this instead

SELECT  @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))

Full Code:

CREATE PROC [dbo].[getVoucherNo]

AS

BEGIN

    DECLARE @Prefix VARCHAR(10)='J'

    DECLARE @startFrom INT=1

    DECLARE @maxCode VARCHAR(100)

    DECLARE @sCode INT

    IF((SELECT COUNT(*) FROM dbo.Journal_Entry) > 0)
    BEGIN
        SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(VoucharNo,LEN(@startFrom)+1,LEN(VoucharNo)- LEN(@Prefix)) AS INT))+1 AS varchar(100)) FROM dbo.Journal_Entry;
        SET @sCode=CAST(@maxCode AS INT)
        SELECT  @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))
    END
    ELSE
    BEGIN
        SELECT(@Prefix + CAST(@startFrom AS VARCHAR)) 
    END
END

How to determine SSL cert expiration date from a PEM encoded certificate?

One line checking on true/false if cert of domain will be expired in some time later(ex. 15 days):

openssl x509 -checkend $(( 24*3600*15 )) -noout -in <(openssl s_client -showcerts -connect my.domain.com:443 </dev/null 2>/dev/null | openssl x509 -outform PEM)
if [ $? -eq 0 ]; then
  echo 'good'
else
  echo 'bad'
fi

Delete files or folder recursively on Windows CMD

For file deletion, I wrote following simple batch file which deleted all .pdf's recursively:

del /s /q "\\ad1pfrtg001\AppDev\ResultLogs\*.pdf"
del /s /q "\\ad1pfrtg001\Project\AppData\*.pdf"

Even for the local directory we can use it as:

del /s /q "C:\Project\*.pdf"

The same can be applied for directory deletion where we just need to change del with rmdir.

How do you set your pythonpath in an already-created virtualenv?

I modified my activate script to source the file .virtualenvrc, if it exists in the current directory, and to save/restore PYTHONPATH on activate/deactivate.

You can find the patched activate script here.. It's a drop-in replacement for the activate script created by virtualenv 1.11.6.

Then I added something like this to my .virtualenvrc:

export PYTHONPATH="${PYTHONPATH:+$PYTHONPATH:}/some/library/path"

Delayed rendering of React components

In your father component <Father />, you could create an initial state where you track each child (using and id for instance), assigning a boolean value, which means render or not:

getInitialState() {
    let state = {};
    React.Children.forEach(this.props.children, (child, index) => {
        state[index] = false;
    });
    return state;
}

Then, when the component is mounted, you start your timers to change the state:

componentDidMount() {
    this.timeouts = React.Children.forEach(this.props.children, (child, index) => {
         return setTimeout(() => {
              this.setState({ index: true; }); 
         }, child.props.delay);
    });
}

When you render your children, you do it by recreating them, assigning as a prop the state for the matching child that says if the component must be rendered or not.

let children = React.Children.map(this.props.children, (child, index) => {
    return React.cloneElement(child, {doRender: this.state[index]});
});

So in your <Child /> component

render() {
    if (!this.props.render) return null;
    // Render method here
}

When the timeout is fired, the state is changed and the father component is rerendered. The children props are updated, and if doRender is true, they will render themselves.

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

Switch to another Git tag

Clone the repository as normal:

git clone git://github.com/rspec/rspec-tmbundle.git RSpec.tmbundle

Then checkout the tag you want like so:

git checkout tags/1.1.4

This will checkout out the tag in a 'detached HEAD' state. In this state, "you can look around, make experimental changes and commit them, and [discard those commits] without impacting any branches by performing another checkout".

To retain any changes made, move them to a new branch:

git checkout -b 1.1.4-jspooner

You can get back to the master branch by using:

git checkout master

Note, as was mentioned in the first revision of this answer, there is another way to checkout a tag:

git checkout 1.1.4

But as was mentioned in a comment, if you have a branch by that same name, this will result in git warning you that the refname is ambiguous and checking out the branch by default:

warning: refname 'test' is ambiguous.
Switched to branch '1.1.4'

The shorthand can be safely used if the repository does not share names between branches and tags.

JPA eager fetch does not join

I had exactly this problem with the exception that the Person class had a embedded key class. My own solution was to join them in the query AND remove

@Fetch(FetchMode.JOIN)

My embedded id class:

@Embeddable
public class MessageRecipientId implements Serializable {

    @ManyToOne(targetEntity = Message.class, fetch = FetchType.LAZY)
    @JoinColumn(name="messageId")
    private Message message;
    private String governmentId;

    public MessageRecipientId() {
    }

    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public String getGovernmentId() {
        return governmentId;
    }

    public void setGovernmentId(String governmentId) {
        this.governmentId = governmentId;
    }

    public MessageRecipientId(Message message, GovernmentId governmentId) {
        this.message = message;
        this.governmentId = governmentId.getValue();
    }

}

Learning Ruby on Rails

I learnt Ruby with the help of Mr. Neighborly's Humble Little Ruby Book. It's an excellent free-to-download introduction to Ruby with lots of examples, which I'd 100% recommend.

Blur the edges of an image or background image with CSS

If you set the image in div, you also must set both height and width. This may cause the image to lose its proportion. In addition, you must set the image URL in CSS instead of HTML.

Instead, you can set the image using the IMG tag. In the container class you can only set the width in percent or pixel and the height will automatically maintain proportion.

This is also more effective for accessibility of search engines and reading engines to define an image using an IMG tag.

_x000D_
_x000D_
.container {_x000D_
 margin: auto;_x000D_
 width: 200px;_x000D_
 position: relative;_x000D_
}_x000D_
_x000D_
img {_x000D_
 width: 100%;_x000D_
}_x000D_
_x000D_
.block {_x000D_
 width: 100%;_x000D_
 position: absolute;_x000D_
 bottom: 0px;_x000D_
 top: 0px;_x000D_
 box-shadow: inset 0px 0px 10px 20px white;_x000D_
}
_x000D_
<div class="container">_x000D_
 <img src="http://lorempixel.com/200/200/city">_x000D_
 <div class="block"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set Radiobuttonlist Selected from Codebehind

You could do:

radio1.SelectedIndex = 1;

But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index!

Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately. For instance:

//omitting possible null reference checks...
var wantedOption = radio1.FindControl("option2").Selected = true;

javascript if number greater than number

Do this.

var x=parseInt(document.forms["frmOrder"]["txtTotal"].value);
var y=parseInt(document.forms["frmOrder"]["totalpoints"].value);

How can I create a copy of an Oracle table without copying the data?

In other way you can get ddl of table creation from command listed below, and execute the creation.

SELECT DBMS_METADATA.GET_DDL('TYPE','OBJECT_NAME','DATA_BASE_USER') TEXT FROM DUAL 
  • TYPE is TABLE,PROCEDURE etc.

With this command you can get majority of ddl from database objects.

Python argparse: default value or specified value

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)

% test.py 
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)

  • nargs='?' means 0-or-1 arguments
  • const=1 sets the default when there are 0 arguments
  • type=int converts the argument to int

If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

then

% test.py 
Namespace(example=1)

Jquery If radio button is checked

Something like this:

if($('#postageyes').is(':checked')) {
// do stuff
}

How to use curl in a shell script?

Firstly, your example is looking quite correct and works well on my machine. You may go another way.

curl $CURLARGS $RVMHTTP > ./install.sh

All output now storing in ./install.sh file, which you can edit and execute.

How to sum digits of an integer in java?

This should be working fine for any number of digits and it will return individual digit's sum

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("enter a string");
    String numbers = input.nextLine();  //String would be 55
    int sum = 0;
    for (char c : numbers.toCharArray()) {
        sum += c - '0';
    }
    System.out.println(sum); //the answer is 10
}

How to refresh an access form

No, it is like I want to run Form_Load of Form A,if it is possible

-- Varun Mahajan

The usual way to do this is to put the relevant code in a procedure that can be called by both forms. It is best put the code in a standard module, but you could have it on Form a:

Form B:

Sub RunFormALoad()
   Forms!FormA.ToDoOnLoad
End Sub

Form A:

Public Sub Form_Load()
    ToDoOnLoad
End Sub    

Sub ToDoOnLoad()
    txtText = "Hi"
End Sub

Extract a substring from a string in Ruby using a regular expression

A simpler scan would be:

String1.scan(/<(\S+)>/).last

How to assign a NULL value to a pointer in python?

left = None

left is None #evaluates to True

Difference between Running and Starting a Docker container

run - Create a container using image and Start the same. (Create & Start)

enter image description here

start - Start the container(s) in docker list which was in stopped state.

enter image description here

How to echo or print an array in PHP?

Human readable: (eg. can be log to text file..)

print_r( $arr_name , TRUE);

What is the standard way to add N seconds to datetime.time in Python?

Old question, but I figured I'd throw in a function that handles timezones. The key parts are passing the datetime.time object's tzinfo attribute into combine, and then using timetz() instead of time() on the resulting dummy datetime. This answer partly inspired by the other answers here.

def add_timedelta_to_time(t, td):
    """Add a timedelta object to a time object using a dummy datetime.

    :param t: datetime.time object.
    :param td: datetime.timedelta object.

    :returns: datetime.time object, representing the result of t + td.

    NOTE: Using a gigantic td may result in an overflow. You've been
    warned.
    """
    # Create a dummy date object.
    dummy_date = date(year=100, month=1, day=1)

    # Combine the dummy date with the given time.
    dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)

    # Add the timedelta to the dummy datetime.
    new_datetime = dummy_datetime + td

    # Return the resulting time, including timezone information.
    return new_datetime.timetz()

And here's a really simple test case class (using built-in unittest):

import unittest
from datetime import datetime, timezone, timedelta, time

class AddTimedeltaToTimeTestCase(unittest.TestCase):
    """Test add_timedelta_to_time."""

    def test_wraps(self):
        t = time(hour=23, minute=59)
        td = timedelta(minutes=2)
        t_expected = time(hour=0, minute=1)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)

    def test_tz(self):
        t = time(hour=4, minute=16, tzinfo=timezone.utc)
        td = timedelta(hours=10, minutes=4)
        t_expected = time(hour=14, minute=20, tzinfo=timezone.utc)
        t_actual = add_timedelta_to_time(t=t, td=td)
        self.assertEqual(t_expected, t_actual)


if __name__ == '__main__':
    unittest.main()

How to ignore a property in class if null, using json.net

Similar to @sirthomas's answer, JSON.NET also respects the EmitDefaultValue property on DataMemberAttribute:

[DataMember(Name="property_name", EmitDefaultValue=false)]

This may be desirable if you are already using [DataContract] and [DataMember] in your model type and don't want to add JSON.NET-specific attributes.

How do you extract a JAR in a UNIX filesystem with a single command and specify its target directory using the JAR command?

I don't think the jar tool supports this natively, but you can just unzip a JAR file with "unzip" and specify the output directory with that with the "-d" option, so something like:

$ unzip -d /home/foo/bar/baz /home/foo/bar/Portal.ear Binaries.war

Handling exceptions from Java ExecutorService tasks

The explanation for this behavior is right in the javadoc for afterExecute:

Note: When actions are enclosed in tasks (such as FutureTask) either explicitly or via methods such as submit, these task objects catch and maintain computational exceptions, and so they do not cause abrupt termination, and the internal exceptions are not passed to this method.

What is base 64 encoding used for?

The usage of Base64 I'm going to describe here is somewhat a hack. So if you don't like hacks, please do not go on.

I went into trouble when I discovered that MySQL's utf8 does not support 4-byte unicode characters since it uses a 3-byte version of utf8. So what I did to support full 4-byte unicode over MySQL's utf8? Well, base64 encode strings when storing into the database and base64 decode when retrieving.

Since base64 encoding and decoding is very fast, the above worked perfectly.

You have the following points to take note of:

  • Base64 encoding uses 33% more storage

  • Strings stored in the database wont be human readable (You could sell that as a feature that database strings use a basic form of encryption).

You could use the above method for any storage engine that does not support unicode.

Ignore .classpath and .project from Git

If the .project and .classpath are already committed, then they need to be removed from the index (but not the disk)

git rm --cached .project
git rm --cached .classpath

Then the .gitignore would work (and that file can be added and shared through clones).
For instance, this gitignore.io/api/eclipse file will then work, which does include:

# Eclipse Core      
.project

# JDT-specific (Eclipse Java Development Tools)     
.classpath

Note that you could use a "Template Directory" when cloning (make sure your users have an environment variable $GIT_TEMPLATE_DIR set to a shared folder accessible by all).
That template folder can contain an info/exclude file, with ignore rules that you want enforced for all repos, including the new ones (git init) that any user would use.


As commented by Abdollah

When you change the index, you need to commit the change and push it.
Then the file is removed from the repository. So the newbies cannot checkout the files .classpath and .project from the repo.

How to count string occurrence in string?

       var myString = "This is a string.";
        var foundAtPosition = 0;
        var Count = 0;
        while (foundAtPosition != -1)
        {
            foundAtPosition = myString.indexOf("is",foundAtPosition);
            if (foundAtPosition != -1)
            {
                Count++;
                foundAtPosition++;
            }
        }
        document.write("There are " + Count + " occurrences of the word IS");

Refer :- count a substring appears in the string for step by step explanation.

Java - Reading XML file

Avoid hardcoding try making the code that is dynamic below is the code it will work for any xml I have used SAX Parser you can use dom,xpath it's upto you I am storing all the tags name and values in the map after that it becomes easy to retrieve any values you want I hope this helps
SAMPLE XML:

<parent>
<child >
    <child1> value 1 </child1>
    <child2> value 2 </child2>
    <child3> value 3 </child3>
    </child>
    <child >
     <child4> value 4 </child4>
    <child5> value 5</child5>
    <child6> value 6 </child6>
    </child>
  </parent>

JAVA CODE:

 import java.io.File;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.LinkedHashMap;
    import java.util.Map;
    import javax.xml.parsers.ParserConfigurationException;
    import javax.xml.parsers.SAXParser;
    import javax.xml.parsers.SAXParserFactory;
    import org.xml.sax.Attributes;
    import org.xml.sax.SAXException;
    import org.xml.sax.helpers.DefaultHandler;


    public class saxParser {
           static Map<String,String> tmpAtrb=null;
           static Map<String,String> xmlVal= new LinkedHashMap<String, String>();
        public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException, VerifyError {

            /**
             * We can pass the class name of the XML parser
             * to the SAXParserFactory.newInstance().
             */

            //SAXParserFactory saxDoc = SAXParserFactory.newInstance("com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", null);

            SAXParserFactory saxDoc = SAXParserFactory.newInstance();
            SAXParser saxParser = saxDoc.newSAXParser();

            DefaultHandler handler = new DefaultHandler() {
                String tmpElementName = null;
                String tmpElementValue = null;


                @Override
                public void startElement(String uri, String localName, String qName, 
                                                                    Attributes attributes) throws SAXException {
                    tmpElementValue = "";
                    tmpElementName = qName;
                    tmpAtrb=new HashMap();
                    //System.out.println("Start Element :" + qName);
                    /**
                     * Store attributes in HashMap
                     */
                    for (int i=0; i<attributes.getLength(); i++) {
                        String aname = attributes.getLocalName(i);
                        String value = attributes.getValue(i);
                        tmpAtrb.put(aname, value);
                    }

                }

                @Override
                public void endElement(String uri, String localName, String qName) 
                                                            throws SAXException { 

                    if(tmpElementName.equals(qName)){
                        System.out.println("Element Name :"+tmpElementName);
                    /**
                     * Retrive attributes from HashMap
                     */                    for (Map.Entry<String, String> entrySet : tmpAtrb.entrySet()) {
                            System.out.println("Attribute Name :"+ entrySet.getKey() + "Attribute Value :"+ entrySet.getValue());
                        }
                        System.out.println("Element Value :"+tmpElementValue);
                        xmlVal.put(tmpElementName, tmpElementValue);
                        System.out.println(xmlVal);
                      //Fetching The Values From The Map
                        String getKeyValues=xmlVal.get(tmpElementName);
                        System.out.println("XmlTag:"+tmpElementName+":::::"+"ValueFetchedFromTheMap:"+getKeyValues);   
                    }   
                }
                @Override
                public void characters(char ch[], int start, int length) throws SAXException {
                    tmpElementValue = new String(ch, start, length) ;  
                } 
            };
            /**
             * Below two line used if we use SAX 2.0
             * Then last line not needed.
             */

            //saxParser.setContentHandler(handler);
            //saxParser.parse(new InputSource("c:/file.xml"));
            saxParser.parse(new File("D:/Test _ XML/file.xml"), handler);
        }  
    }

OUTPUT:

Element Name :child1
Element Value : value 1 
XmlTag:<child1>:::::ValueFetchedFromTheMap: value 1 
Element Name :child2
Element Value : value 2 
XmlTag:<child2>:::::ValueFetchedFromTheMap: value 2 
Element Name :child3
Element Value : value 3 
XmlTag:<child3>:::::ValueFetchedFromTheMap: value 3 
Element Name :child4
Element Value : value 4 
XmlTag:<child4>:::::ValueFetchedFromTheMap: value 4 
Element Name :child5
Element Value : value 5
XmlTag:<child5>:::::ValueFetchedFromTheMap: value 5
Element Name :child6
Element Value : value 6 
XmlTag:<child6>:::::ValueFetchedFromTheMap: value 6 
Values Inside The Map:{child1= value 1 , child2= value 2 , child3= value 3 , child4= value 4 , child5= value 5, child6= value 6 }

CREATE TABLE IF NOT EXISTS equivalent in SQL Server

if not exists (select * from sysobjects where name='cars' and xtype='U')
    create table cars (
        Name varchar(64) not null
    )
go

The above will create a table called cars if the table does not already exist.

Concat scripts in order with Gulp

Try stream-series. It works like merge-stream/event-stream.merge() except that instead of interleaving, it appends to the end. It doesn't require you to specify the object mode like streamqueue, so your code comes out cleaner.

var series = require('stream-series');

gulp.task('minifyInOrder', function() {
    return series(gulp.src('vendor/*'),gulp.src('extra'),gulp.src('house/*'))
        .pipe(concat('a.js'))
        .pipe(uglify())
        .pipe(gulp.dest('dest'))
});

java.io.InvalidClassException: local class incompatible:

If you are using the Eclipse IDE, check your Debug/Run configuration. At Classpath tab, select the runner project and click Edit button. Only include exported entries must be checked.

FileNotFoundException while getting the InputStream object from HttpURLConnection

For anybody else stumbling over this, the same happened to me while trying to send a SOAP request header to a SOAP service. The issue was a wrong order in the code, I requested the input stream first before sending the XML body. In the code snipped below, the line InputStream in = conn.getInputStream(); came immediately after ByteArrayOutputStream out = new ByteArrayOutputStream(); which is the incorrect order of things.

ByteArrayOutputStream out = new ByteArrayOutputStream();
// send SOAP request as part of HTTP body 
byte[] data = request.getHttpBody().getBytes("UTF-8");
conn.getOutputStream().write(data); 

if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
  Log.d(TAG, "http response code is " + conn.getResponseCode());
  return null;
}

InputStream in = conn.getInputStream();

FileNotFound in this case was an unfortunate way to encode HTTP response code 400.

How do you import a large MS SQL .sql file?

From the command prompt, start up sqlcmd:

sqlcmd -S <server> -i C:\<your file here>.sql 

Just replace <server> with the location of your SQL box and <your file here> with the name of your script. Don't forget, if you're using a SQL instance the syntax is:

sqlcmd -S <server>\instance.

Here is the list of all arguments you can pass sqlcmd:

Sqlcmd            [-U login id]          [-P password]
  [-S server]            [-H hostname]          [-E trusted connection]
  [-d use database name] [-l login timeout]     [-t query timeout] 
  [-h headers]           [-s colseparator]      [-w screen width]
  [-a packetsize]        [-e echo input]        [-I Enable Quoted Identifiers]
  [-c cmdend]            [-L[c] list servers[clean output]]
  [-q "cmdline query"]   [-Q "cmdline query" and exit] 
  [-m errorlevel]        [-V severitylevel]     [-W remove trailing spaces]
  [-u unicode output]    [-r[0|1] msgs to stderr]
  [-i inputfile]         [-o outputfile]        [-z new password]
  [-f  | i:[,o:]] [-Z new password and exit] 
  [-k[1|2] remove[replace] control characters]
  [-y variable length type display width]
  [-Y fixed length type display width]
  [-p[1] print statistics[colon format]]
  [-R use client regional setting]
  [-b On error batch abort]
  [-v var = "value"...]  [-A dedicated admin connection]
  [-X[1] disable commands, startup script, environment variables [and exit]]
  [-x disable variable substitution]
  [-? show syntax summary] 

SQL Server table creation date query

For 2005 up, you can use

SELECT
        [name]
       ,create_date
       ,modify_date
FROM
        sys.tables

I think for 2000, you need to have enabled auditing.

How to run a makefile in Windows?

Check out GnuWin's make (for windows), which provides a native port for Windows (without requiring a full runtime environment like Cygwin)

If you have winget, you can install via the CLI like this:

winget install GnuWin32.Make

Also, be sure to add the install path to your system PATH:

C:\Program Files (x86)\GnuWin32\bin

How do I mock a REST template exchange?

You don't need MockRestServiceServer object. The annotation is @InjectMocks not @Inject. Below is an example code that should work

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private SomeService underTest;

    @Test
    public void testGetObjectAList() {
        ObjectA myobjectA = new ObjectA();
        //define the entity you want the exchange to return
        ResponseEntity<List<ObjectA>> myEntity = new ResponseEntity<List<ObjectA>>(HttpStatus.ACCEPTED);
        Mockito.when(restTemplate.exchange(
            Matchers.eq("/objects/get-objectA"),
            Matchers.eq(HttpMethod.POST),
            Matchers.<HttpEntity<List<ObjectA>>>any(),
            Matchers.<ParameterizedTypeReference<List<ObjectA>>>any())
        ).thenReturn(myEntity);

        List<ObjectA> res = underTest.getListofObjectsA();
        Assert.assertEquals(myobjectA, res.get(0));
    }

How to get just the responsive grid from Bootstrap 3?

It looks like you can download just the grid now on Bootstrap 4s new download features.

SQL SERVER: Get total days between two dates

DECLARE @FDate DATETIME='05-05-2019' /*This is first date*/
 GETDATE()/*This is Current date*/
SELECT (DATEDIFF(DAY,(@LastDate),GETDATE())) As DifferenceDays/*this query will return no of days between firstdate & Current date*/

Switch between two frames in tkinter

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

how to check if a file is a directory or regular file in python?

An educational example from the stat documentation:

import os, sys
from stat import *

def walktree(top, callback):
    '''recursively descend the directory tree rooted at top,
       calling the callback function for each regular file'''

    for f in os.listdir(top):
        pathname = os.path.join(top, f)
        mode = os.stat(pathname)[ST_MODE]
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            walktree(pathname, callback)
        elif S_ISREG(mode):
            # It's a file, call the callback function
            callback(pathname)
        else:
            # Unknown file type, print a message
            print 'Skipping %s' % pathname

def visitfile(file):
    print 'visiting', file

if __name__ == '__main__':
    walktree(sys.argv[1], visitfile)

Appending to an existing string

You can use << to append to a string in-place.

s = "foo"
old_id = s.object_id
s << "bar"
s                      #=> "foobar"
s.object_id == old_id  #=> true

Difference between $.ajax() and $.get() and $.load()

Important note : jQuery.load() method can do not only GET but also POST requests, if data parameter is supplied (see: http://api.jquery.com/load/)

data Type: PlainObject or String A plain object or string that is sent to the server with the request.

Request Method The POST method is used if data is provided as an object; otherwise, GET is assumed.

Example: pass arrays of data to the server (POST request)
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

How to disassemble a binary executable in Linux to get the assembly code?

ht editor can disassemble binaries in many formats. It is similar to Hiew, but open source.

To disassemble, open a binary, then press F6 and then select elf/image.

Multi value Dictionary

I think this is quite overkill for a dictionary semantics, since dictionary is by definition is a collection of keys and its respective values, just like the way we see a book of language dictionary that contains a word as the key and its descriptive meaning as the value.

But you can represent a dictionary that can contain collection of values, for example:

Dictionary<String,List<Customer>>

Or a dictionary of a key and the value as a dictionary:

Dictionary<Customer,Dictionary<Order,OrderDetail>>

Then you'll have a dictionary that can have multiple values.

Set initial value in datepicker with jquery?

I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.

If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.

Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.

<script>
    $(document).ready(function () {
        $('#DateChanger').click(function() {
             $('#dtFrom').val("2012-12-22");
        });
    });
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>

Remember to include JQuery reference.

Declaring variables inside loops, good practice or bad practice?

Since your second question is more concrete, I'm going to address it first, and then take up your first question with the context given by the second. I wanted to give a more evidence-based answer than what's here already.

Question #2: Do most compilers realize that the variable has already been declared and just skip that portion, or does it actually create a spot for it in memory each time?

You can answer this question for yourself by stopping your compiler before the assembler is run and looking at the asm. (Use the -S flag if your compiler has a gcc-style interface, and -masm=intel if you want the syntax style I'm using here.)

In any case, with modern compilers (gcc 10.2, clang 11.0) for x86-64, they only reload the variable on each loop pass if you disable optimizations. Consider the following C++ program—for intuitive mapping to asm, I'm keeping things mostly C-style and using an integer instead of a string, although the same principles apply in the string case:

#include <iostream>

static constexpr std::size_t LEN = 10;

void fill_arr(int a[LEN])
{
    /* *** */
    for (std::size_t i = 0; i < LEN; ++i) {
        const int t = 8;

        a[i] = t;
    }
    /* *** */
}

int main(void)
{
    int a[LEN];

    fill_arr(a);

    for (std::size_t i = 0; i < LEN; ++i) {
        std::cout << a[i] << " ";
    }

    std::cout << "\n";

    return 0;
}

We can compare this to a version with the following difference:

    /* *** */
    const int t = 8;

    for (std::size_t i = 0; i < LEN; ++i) {
        a[i] = t;
    }
    /* *** */

With optimization disabled, gcc 10.2 puts 8 on the stack on every pass of the loop for the declaration-in-loop version:

    mov QWORD PTR -8[rbp], 0
.L3:
    cmp QWORD PTR -8[rbp], 9
    ja  .L4
    mov DWORD PTR -12[rbp], 8 ;?

whereas it only does it once for the out-of-loop version:

    mov DWORD PTR -12[rbp], 8 ;?
    mov QWORD PTR -8[rbp], 0
.L3:
    cmp QWORD PTR -8[rbp], 9
    ja  .L4

Does this make a performance impact? I didn't see an appreciable difference in runtime between them with my CPU (Intel i7-7700K) until I pushed the number of iterations into the billions, and even then the average difference was less than 0.01s. It's only a single extra operation in the loop, after all. (For a string, the difference in in-loop operations is obviously a bit greater, but not dramatically so.)

What's more, the question is largely academic, because with an optimization level of -O1 or higher gcc outputs identical asm for both source files, as does clang. So, at least for simple cases like this, it's unlikely to make any performance impact either way. Of course, in a real-world program, you should always profile rather than make assumptions.

Question #1: Is declaring a variable inside a loop a good practice or bad practice?

As with practically every question like this, it depends. If the declaration is inside a very tight loop and you're compiling without optimizations, say for debugging purposes, it's theoretically possible that moving it outside the loop would improve performance enough to be handy during your debugging efforts. If so, it might be sensible, at least while you're debugging. And although I don't think it's likely to make any difference in an optimized build, if you do observe one, you/your pair/your team can make a judgement call as to whether it's worth it.

At the same time, you have to consider not only how the compiler reads your code, but also how it comes off to humans, yourself included. I think you'll agree that a variable declared in the smallest scope possible is easier to keep track of. If it's outside the loop, it implies that it's needed outside the loop, which is confusing if that's not actually the case. In a big codebase, little confusions like this add up over time and become fatiguing after hours of work, and can lead to silly bugs. That can be much more costly than what you reap from a slight performance improvement, depending on the use case.

How to create an Array, ArrayList, Stack and Queue in Java?

Without more details as to what the question is exactly asking, I am going to answer the title of the question,

Create an Array:

String[] myArray = new String[2];
int[] intArray = new int[2];

// or can be declared as follows
String[] myArray = {"this", "is", "my", "array"};
int[] intArray = {1,2,3,4};

Create an ArrayList:

ArrayList<String> myList = new ArrayList<String>();
myList.add("Hello");
myList.add("World");

ArrayList<Integer> myNum = new ArrayList<Integer>();
myNum.add(1);
myNum.add(2);

This means, create an ArrayList of String and Integer objects. You cannot use int because thats a primitive data types, see the link for a list of primitive data types.

Create a Stack:

Stack myStack = new Stack();
// add any type of elements (String, int, etc..)
myStack.push("Hello");
myStack.push(1);

Create an Queue: (using LinkedList)

Queue<String> myQueue = new LinkedList<String>();
Queue<Integer> myNumbers = new LinkedList<Integer>();
myQueue.add("Hello");
myQueue.add("World");
myNumbers.add(1);
myNumbers.add(2);

Same thing as an ArrayList, this declaration means create an Queue of String and Integer objects.


Update:

In response to your comment from the other given answer,

i am pretty confused now, why are using string. and what does <String> means

We are using String only as a pure example, but you can add any other object, but the main point is that you use an object not a primitive type. Each primitive data type has their own primitive wrapper class, see link for list of primitive data type's wrapper class.

I have posted some links to explain the difference between the two, but here are a list of primitive types

  • byte
  • short
  • char
  • int
  • long
  • boolean
  • double
  • float

Which means, you are not allowed to make an ArrayList of integer's like so:

ArrayList<int> numbers = new ArrayList<int>(); 
           ^ should be an object, int is not an object, but Integer is!
ArrayList<Integer> numbers = new ArrayList<Integer>();
            ^ perfectly valid

Also, you can use your own objects, here is my Monster object I created,

public class Monster {
   String name = null;
   String location = null;
   int age = 0;

public Monster(String name, String loc, int age) { 
   this.name = name;
   this.loc = location;
   this.age = age;
 }

public void printDetails() {
   System.out.println(name + " is from " + location +
                                     " and is " + age + " old.");
 }
} 

Here we have a Monster object, but now in our Main.java class we want to keep a record of all our Monster's that we create, so let's add them to an ArrayList

public class Main {
    ArrayList<Monster> myMonsters = new ArrayList<Monster>();

public Main() {
    Monster yetti = new Monster("Yetti", "The Mountains", 77);
    Monster lochness = new Monster("Lochness Monster", "Scotland", 20);

    myMonsters.add(yetti); // <-- added Yetti to our list
    myMonsters.add(lochness); // <--added Lochness to our list
  
    for (Monster m : myMonsters) {
        m.printDetails();
     }
   }

public static void main(String[] args) {
    new Main();
 }
}

(I helped my girlfriend's brother with a Java game, and he had to do something along those lines as well, but I hope the example was well demonstrated)

Putting GridView data in a DataTable

Copying Grid to datatable

        if (GridView.Rows.Count != 0)
        {
            //Forloop for header
            for (int i = 0; i < GridView.HeaderRow.Cells.Count; i++)
            {
                dt.Columns.Add(GridView.HeaderRow.Cells[i].Text);
            }
            //foreach for datarow
            foreach (GridViewRow row in GridView.Rows)
            {
                DataRow dr = dt.NewRow();
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    dr[GridView.HeaderRow.Cells[j].Text] = row.Cells[j].Text;
                }
                dt.Rows.Add(dr);
            }
            //Loop for footer
            if (GridView.FooterRow.Cells.Count != 0)
            {
                DataRow dr = dt.NewRow();
                for (int i = 0; i < GridView.FooterRow.Cells.Count; i++)
                {
                    //You have to re-do the work if you did anything in databound for footer.  
                }
                dt.Rows.Add(dr);
            }
            dt.TableName = "tb";
        }

How to 'restart' an android application programmatically

Checkout intent properties like no history , clear back stack etc ... Intent.setFlags

Intent mStartActivity = new Intent(HomeActivity.this, SplashScreen.class);
int mPendingIntentId = 123456;
PendingIntent mPendingIntent = PendingIntent.getActivity(HomeActivity.this, mPendingIntentId, mStartActivity,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) HomeActivity.this.getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
System.exit(0);

PostgreSQL unnest() with element number

Postgres 9.4 or later

Use WITH ORDINALITY for set-returning functions:

When a function in the FROM clause is suffixed by WITH ORDINALITY, a bigint column is appended to the output which starts from 1 and increments by 1 for each row of the function's output. This is most useful in the case of set returning functions such as unnest().

In combination with the LATERAL feature in pg 9.3+, and according to this thread on pgsql-hackers, the above query can now be written as:

SELECT t.id, a.elem, a.nr
FROM   tbl AS t
LEFT   JOIN LATERAL unnest(string_to_array(t.elements, ','))
                    WITH ORDINALITY AS a(elem, nr) ON TRUE;

LEFT JOIN ... ON TRUE preserves all rows in the left table, even if the table expression to the right returns no rows. If that's of no concern you can use this otherwise equivalent, less verbose form with an implicit CROSS JOIN LATERAL:

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(string_to_array(t.elements, ',')) WITH ORDINALITY a(elem, nr);

Or simpler if based off an actual array (arr being an array column):

SELECT t.id, a.elem, a.nr
FROM   tbl t, unnest(t.arr) WITH ORDINALITY a(elem, nr);

Or even, with minimal syntax:

SELECT id, a, ordinality
FROM   tbl, unnest(arr) WITH ORDINALITY a;

a is automatically table and column alias. The default name of the added ordinality column is ordinality. But it's better (safer, cleaner) to add explicit column aliases and table-qualify columns.

Postgres 8.4 - 9.3

With row_number() OVER (PARTITION BY id ORDER BY elem) you get numbers according to the sort order, not the ordinal number of the original ordinal position in the string.

You can simply omit ORDER BY:

SELECT *, row_number() OVER (PARTITION by id) AS nr
FROM  (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;

While this normally works and I have never seen it fail in simple queries, PostgreSQL asserts nothing concerning the order of rows without ORDER BY. It happens to work due to an implementation detail.

To guarantee ordinal numbers of elements in the blank-separated string:

SELECT id, arr[nr] AS elem, nr
FROM  (
   SELECT *, generate_subscripts(arr, 1) AS nr
   FROM  (SELECT id, string_to_array(elements, ' ') AS arr FROM tbl) t
   ) sub;

Or simpler if based off an actual array:

SELECT id, arr[nr] AS elem, nr
FROM  (SELECT *, generate_subscripts(arr, 1) AS nr FROM tbl) t;

Related answer on dba.SE:

Postgres 8.1 - 8.4

None of these features are available, yet: RETURNS TABLE, generate_subscripts(), unnest(), array_length(). But this works:

CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

Note in particular, that the array index can differ from ordinal positions of elements. Consider this demo with an extended function:

CREATE FUNCTION f_unnest_ord_idx(anyarray, OUT val anyelement, OUT ordinality int, OUT idx int)
  RETURNS SETOF record
  LANGUAGE sql IMMUTABLE AS
'SELECT $1[i], i - array_lower($1,1) + 1, i
 FROM   generate_series(array_lower($1,1), array_upper($1,1)) i';

SELECT id, arr, (rec).*
FROM  (
   SELECT *, f_unnest_ord_idx(arr) AS rec
   FROM  (VALUES (1, '{a,b,c}'::text[])  --  short for: '[1:3]={a,b,c}'
               , (2, '[5:7]={a,b,c}')
               , (3, '[-9:-7]={a,b,c}')
      ) t(id, arr)
   ) sub;

 id |       arr       | val | ordinality | idx
----+-----------------+-----+------------+-----
  1 | {a,b,c}         | a   |          1 |   1
  1 | {a,b,c}         | b   |          2 |   2
  1 | {a,b,c}         | c   |          3 |   3
  2 | [5:7]={a,b,c}   | a   |          1 |   5
  2 | [5:7]={a,b,c}   | b   |          2 |   6
  2 | [5:7]={a,b,c}   | c   |          3 |   7
  3 | [-9:-7]={a,b,c} | a   |          1 |  -9
  3 | [-9:-7]={a,b,c} | b   |          2 |  -8
  3 | [-9:-7]={a,b,c} | c   |          3 |  -7

Compare:

Merging two images with PHP

I got it working from one I made.

<?php
$dest = imagecreatefrompng('vinyl.png');
$src = imagecreatefromjpeg('cover2.jpg');

imagealphablending($dest, false);
imagesavealpha($dest, true);

imagecopymerge($dest, $src, 10, 9, 0, 0, 181, 180, 100); //have to play with these numbers for it to work for you, etc.

header('Content-Type: image/png');
imagepng($dest);

imagedestroy($dest);
imagedestroy($src);
?>

React Js: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

I had the same issue with fetch and decided to switch to axios. Fixed the issue right away, here's the code snippet.

var axios = require('axios');

  var config = {
    method: 'get',
    url: 'http://localhost:4000/'
  };
  
  axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data));
  })
  .catch(function (error) {
    console.log(error);
  });

ios simulator: how to close an app

I had a difficult time in finding a way in XCode 7.2, but finally I had found one. First press Shift+Command+ H twice. This will open up all the apps that are currently open.

Swipe left/right to the app you actually want to close. Just Swipe Up using the Touchpad while Holding the App would close the app.

Java method to sum any number of ints

public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 

How do I pass data to Angular routed components?

I looked at every solution (and tried a few) from this page but I was not convinced that we have to kind of implement a hack-ish way to achieve the data transfer between route.

Another problem with simple history.state is that if you are passing an instance of a particular class in the state object, it will not be the instance while receiving it. But it will be a plain simple JavaScript object.

So in my Angular v10 (Ionic v5) application, I did this-

this.router.navigateByUrl('/authenticate/username', {
    state: {user: new User(), foo: 'bar'}
});

enter image description here

And in the navigating component ('/authenticate/username'), in ngOnInit() method, I printed the data with this.router.getCurrentNavigation().extras.state-

ngOnInit() {
    console.log('>>authenticate-username:41:',
        this.router.getCurrentNavigation().extras.state);
}

enter image description here

And I got the desired data which was passed-

enter image description here

setting system property

You need the path of the plugins directory of your local GATE install. So if Gate is installed in "/home/user/GATE_Developer_8.1", the code looks like this:

System.setProperty("gate.home", "/home/user/GATE_Developer_8.1/plugins");

You don't have to set gate.home from the command line. You can set it in your application, as long as you set it BEFORE you call Gate.init().

What is the difference between String and StringBuffer in Java?

I found interest answer for compare performance String vs StringBuffer by Reggie Hutcherso Source: http://www.javaworld.com/javaworld/jw-03-2000/jw-0324-javaperf.html

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Using the String class, concatenations are typically performed as follows:

 String str = new String ("Stanford  ");
 str += "Lost!!";

If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:

 StringBuffer str = new StringBuffer ("Stanford ");
 str.append("Lost!!");

Developers usually assume that the first example above is more efficient because they think that the second example, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.

The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String. To discover why this is the case, we must examine the generated bytecode from our two examples. The bytecode for the example using String looks like this:

0 new #7 <Class java.lang.String>
3 dup 
4 ldc #2 <String "Stanford ">
6 invokespecial #12 <Method java.lang.String(java.lang.String)>
9 astore_1
10 new #8 <Class java.lang.StringBuffer>
13 dup
14 aload_1
15 invokestatic #23 <Method java.lang.String valueOf(java.lang.Object)>
18 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
21 ldc #1 <String "Lost!!">
23 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
26 invokevirtual #22 <Method java.lang.String toString()>
29 astore_1

The bytecode at locations 0 through 9 is executed for the first line of code, namely:

 String str = new String("Stanford ");

Then, the bytecode at location 10 through 29 is executed for the concatenation:

 str += "Lost!!";

Things get interesting here. The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.

After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done with the call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are very expensive.

In summary, the two lines of code above result in the creation of three objects:

  1. A String object at location 0
  2. A StringBuffer object at location 10
  3. A String object at location 26

Now, let's look at the bytecode generated for the example using StringBuffer:

0 new #8 <Class java.lang.StringBuffer>
3 dup
4 ldc #2 <String "Stanford ">
6 invokespecial #13 <Method java.lang.StringBuffer(java.lang.String)>
9 astore_1
10 aload_1 
11 ldc #1 <String "Lost!!">
13 invokevirtual #15 <Method java.lang.StringBuffer append(java.lang.String)>
16 pop

The bytecode at locations 0 to 9 is executed for the first line of code:

 StringBuffer str = new StringBuffer("Stanford ");

The bytecode at location 10 to 16 is then executed for the concatenation:

 str.append("Lost!!");

Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

The spatial functions in PostGIS are much more functional (i.e. not constrained to BBOX operations) than those in the MySQL spatial functions. Check it out: link text

How can I output leading zeros in Ruby?

Use the % operator with a string:

irb(main):001:0> "%03d" % 5
=> "005"

The left-hand-side is a printf format string, and the right-hand side can be a list of values, so you could do something like:

irb(main):002:0> filename = "%s/%s.%04d.txt" % ["dirname", "filename", 23]
=> "dirname/filename.0023.txt"

Here's a printf format cheat sheet you might find useful in forming your format string. The printf format is originally from the C function printf, but similar formating functions are available in perl, ruby, python, java, php, etc.

Multiple queries executed in java in single statement

Why dont you try and write a Stored Procedure for this?

You can get the Result Set out and in the same Stored Procedure you can Insert what you want.

The only thing is you might not get the newly inserted rows in the Result Set if you Insert after the Select.

getting the table row values with jquery

Give something like this a try:

$(document).ready(function(){
    $("#thisTable tr").click(function(){
        $(this).find("td").each(function(){
            alert($(this).html());
        });
    });
});?

Here is a fiddle of the code in action: http://jsfiddle.net/YhZsW/

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

React Hooks useState() with Object

function App() {

  const [todos, setTodos] = useState([
    { id: 1, title: "Selectus aut autem", completed: false },
    { id: 2, title: "Luis ut nam facilis et officia qui", completed: false },
    { id: 3, title: "Fugiat veniam minus", completed: false },
    { id: 4, title: "Aet porro tempora", completed: true },
    { id: 5, title: "Laboriosam mollitia et enim quasi", completed: false }
  ]);

  const changeInput = (e) => {todos.map(items => items.id === parseInt(e.target.value) && (items.completed = e.target.checked));
 setTodos([...todos], todos);}
  return (
    <div className="container">
      {todos.map(items => {
        return (
          <div key={items.id}>
            <label>
<input type="checkbox" 
onChange={changeInput} 
value={items.id} 
checked={items.completed} />&nbsp; {items.title}</label>
          </div>
        )
      })}
    </div>
  );
}

Identifier is undefined

Are you missing a function declaration?

void ac_search(uint num_patterns, uint pattern_length, const char *patterns, 
               uint num_records, uint record_length, const char *records, int *matches, Node* trie);

Add it just before your implementation of ac_benchmark_search.

Java - Find shortest path between 2 points in a distance weighted map

This maybe too late but No one provided a clear explanation of how the algorithm works

The idea of Dijkstra is simple, let me show this with the following pseudocode.

Dijkstra partitions all nodes into two distinct sets. Unsettled and settled. Initially all nodes are in the unsettled set, e.g. they must be still evaluated.

At first only the source node is put in the set of settledNodes. A specific node will be moved to the settled set if the shortest path from the source to a particular node has been found.

The algorithm runs until the unsettledNodes set is empty. In each iteration it selects the node with the lowest distance to the source node out of the unsettledNodes set. E.g. It reads all edges which are outgoing from the source and evaluates each destination node from these edges which are not yet settled.

If the known distance from the source to this node can be reduced when the selected edge is used, the distance is updated and the node is added to the nodes which need evaluation.

Please note that Dijkstra also determines the pre-successor of each node on its way to the source. I left that out of the pseudo code to simplify it.

Credits to Lars Vogel

Finding all possible combinations of numbers to reach a given sum

Here is a better version with better output formatting and C++ 11 features:

void subset_sum_rec(std::vector<int> & nums, const int & target, std::vector<int> & partialNums) 
{
    int currentSum = std::accumulate(partialNums.begin(), partialNums.end(), 0);
    if (currentSum > target)
        return;
    if (currentSum == target) 
    {
        std::cout << "sum([";
        for (auto it = partialNums.begin(); it != std::prev(partialNums.end()); ++it)
            cout << *it << ",";
        cout << *std::prev(partialNums.end());
        std::cout << "])=" << target << std::endl;
    }
    for (auto it = nums.begin(); it != nums.end(); ++it) 
    {
        std::vector<int> remaining;
        for (auto it2 = std::next(it); it2 != nums.end(); ++it2)
            remaining.push_back(*it2);

        std::vector<int> partial = partialNums;
        partial.push_back(*it);
        subset_sum_rec(remaining, target, partial);
    }
}

Finding the average of an array using JS

Writing the function for average yourself is crazy. That's why modules exist. I found math.js

In my HTML file:

  <script src="http://cdnjs.cloudflare.com/ajax/libs/mathjs/3.2.1/math.min.js"></script>

(or you can download it)

In my JS code:

math.mean([1,2,3]) // =2
math.mean(1,2,3) // the same
math.mean(grades)

SQL Server command line backup statement

Seba Illingworth's code, In case you need time in your file name (it gives 2014-02-21_1035)

echo off
cls
echo -- BACKUP DATABASE --
set /p DATABASENAME=Enter database name:
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-2 delims=/:" %%a in ("%TIME%") do (set mytime=%%a%%b)

:: filename format Name-Date (eg MyDatabase-2009.5.19.bak)
set DATESTAMP=%mydate%_%mytime%
set BACKUPFILENAME=%CD%\%DATABASENAME%-%DATESTAMP%.bak
set SERVERNAME=.
echo.

sqlcmd -E -S %SERVERNAME% -d master -Q "BACKUP DATABASE [%DATABASENAME%] TO DISK = N'%BACKUPFILENAME%' WITH INIT , NOUNLOAD , NAME = N'%DATABASENAME% backup', NOSKIP , STATS = 10, NOFORMAT"
echo.
pause

How to send a POST request using volley with string body?

Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();


JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();

StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.v("LOG_VOLLEY", response);

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("LOG_VOLLEY", error.toString());
    }
}) {
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
            return null;
        }
    }

};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);

What's the best way to get the last element of an array without deleting it?

The many answers in this thread present us with many different options. To be able to choose from them I needed to understand their behavior and performance. In this answer I will share my findings with you, benchmarked against PHP versions 5.6.38, 7.2.10 and 7.3.0RC1 (expected Dec 13 2018).

The options (<<option code>>s) I will test are:

(functions mentioned: array_key_last , array_keys , array_pop , array_slice , array_values , count , end , reset)

The test inputs (<<input code>>s) to combine with:

  • null = $array = null;
  • empty = $array = [];
  • last_null = $array = ["a","b","c",null];
  • auto_idx = $array = ["a","b","c","d"];
  • shuffle = $array = []; $array[1] = "a"; $array[2] = "b"; $array[0] = "c";
  • 100 = $array = []; for($i=0;$i<100;$i++) { $array[] = $i; }
  • 100000 = $array = []; for($i=0;$i<100000;$i++) { $array[] = $i; }

For testing I will use the 5.6.38, 7.2.10 and 7.3.0RC1 PHP docker containers like:

sudo docker run -it --rm php:5.6.38-cli-stretch php -r '<<<CODE HERE>>>'

Each combination of the above listed <<option code>>s and <<input code>>s will be run on all versions of PHP. For each test run the following code snippet is used:

<<input code>>  error_reporting(E_ALL);  <<option code>>  error_reporting(0); $before=microtime(TRUE); for($i=0;$i<100;$i++){echo ".";for($j=0;$j<100;$j++){  <<option code>>  }}; $after=microtime(TRUE); echo "\n"; var_dump($x); echo round(($after-$before)/(100*100)*1000*1000*1000);

For each run this will var_dump the last retrieved last value of the test input and print the average duration of one iteration in femtoseconds (0.000000000000001th of a second).

The results are as follows:

/==========================================================================================================================================================================================================================================================================================================================================================================================================================\
||                                                                      ||                            T  E  S  T     I  N  P  U  T     -     5  .  6  .  3  8                            ||                             T  E  S  T     I  N  P  U  T     -     7  .  2  .  1  0                           ||                             T  E  S  T     I  N  P  U  T     -     7  .  3  .  0  R  C  1                     ||
||                                                                      ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||          null |         empty |     last_null |      auto_idx |       shuffle |           100 |        100000 ||
||============================OPTIONS - ERRORS==========================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||       W1 + W2 |            N1 |             - |             - |             - |             - |             - ||
||  2.  $x = array_slice($array, -1)[0];                                ||            W1 |            N1 |             - |             - |             - |             - |             - ||            W1 |            N1 |             - |             - |             - |             - |             - ||            W1 |            N1 |             - |             - |             - |             - |             - ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||       W1 + W3 |             - |             - |             - |             - |             - |             - ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||       W1 + W3 |             - |             - |             - |             - |             - |             - ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||  W1 + N2 + W3 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  5.  $x = end($array); reset($array);                                ||       W4 + W5 |             - |             - |             - |             - |             - |             - ||       W4 + W5 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||       W4 + W5 |             - |             - |             - |             - |             - |             - ||
||  6.  $x = end((array_values($array)));                               ||       W2 + W4 |             - |             - |             - |             - |             - |             - ||  W2 + N2 + W4 |             - |             - |             - |             - |             - |             - ||  W2 + N2 + W4 |            N2 |            N2 |            N2 |            N2 |            N2 |            N2 ||
||  7.  $x = $array[count($array)-1];                                   ||             - |            N3 |             - |             - |             - |             - |             - ||            W7 |            N3 |             - |             - |             - |             - |             - ||            W7 |            N3 |             - |             - |             - |             - |             - ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||            W6 |       N3 + N4 |             - |             - |             - |             - |             - ||       W6 + W7 |       N3 + N4 |             - |             - |             - |             - |             - ||       W6 + W7 |       N3 + N4 |             - |             - |             - |             - |             - ||
||  9.  $x = $array[] = array_pop($array);                              ||            W3 |             - |             - |             - |             - |             - |             - ||            W3 |             - |             - |             - |             - |             - |             - ||            W3 |             - |             - |             - |             - |             - |             - ||
|| 10.  $x = $array[array_key_last($array)];                            ||            F1 |            F1 |            F1 |            F1 |            F1 |            F1 |            F1 ||            F2 |            F2 |            F2 |            F2 |            F2 |            F2 |            F2 ||            W8 |            N4 |            F2 |            F2 |            F2 |            F2 |            F2 ||
||========================OPTIONS - VALUE RETRIEVED=====================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  2.  $x = array_slice($array, -1)[0];                                ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  5.  $x = end($array); reset($array);                                ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  6.  $x = end((array_values($array)));                               ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |   bool(false) |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  7.  $x = $array[count($array)-1];                                   ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "b" |       int(99) |    int(99999) ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
||  9.  $x = $array[] = array_pop($array);                              ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||          NULL |          NULL |          NULL | string(1) "d" | string(1) "c" |       int(99) |    int(99999) ||
|| 10.  $x = $array[array_key_last($array)];                            ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||
||=================OPTIONS - FEMTOSECONDS PER ITERATION=================++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============++===============+===============+===============+===============+===============+===============+===============<|
||  1.  $x = array_values(array_slice($array, -1))[0];                  ||           803 |           466 |           390 |           384 |           373 |           764 |     1.046.642 ||           691 |           252 |           101 |           128 |            93 |           170 |        89.028 ||           695 |           235 |            90 |            97 |            95 |           188 |        87.991 ||
||  2.  $x = array_slice($array, -1)[0];                                ||           414 |           349 |           252 |           248 |           246 |           604 |     1.038.074 ||           373 |           249 |            85 |            91 |            90 |           164 |        90.750 ||           367 |           224 |            78 |            85 |            80 |           155 |        86.141 ||
||  3.  $x = array_pop((array_slice($array, -1)));                      ||           724 |           228 |           323 |           318 |           350 |           673 |     1.042.263 ||           988 |           285 |           309 |           317 |           331 |           401 |        88.363 ||           877 |           266 |           298 |           300 |           326 |           403 |        87.279 ||
||  4.  $x = array_pop((array_slice($array, -1, 1)));                   ||           734 |           266 |           358 |           356 |           349 |           699 |     1.050.101 ||           887 |           288 |           316 |           322 |           314 |           408 |        88.402 ||           935 |           268 |           335 |           315 |           313 |           403 |        86.445 ||
||  5.  $x = end($array); reset($array);                                ||           715 |           186 |           185 |           180 |           176 |           185 |           172 ||           674 |            73 |            69 |            70 |            66 |            65 |            70 ||           693 |            65 |            85 |            74 |            68 |            70 |            69 ||
||  6.  $x = end((array_values($array)));                               ||           877 |           205 |           320 |           337 |           304 |         2.901 |     7.921.860 ||           948 |           300 |           336 |           308 |           309 |           509 |    29.696.951 ||           946 |           262 |           301 |           309 |           302 |           499 |    29.234.928 ||
||  7.  $x = $array[count($array)-1];                                   ||           123 |           300 |           137 |           139 |           143 |           140 |           144 ||           312 |           218 |            48 |            53 |            45 |            47 |            51 ||           296 |           217 |            46 |            44 |            53 |            53 |            55 ||
||  8.  $keys = array_keys($array); $x = $array[$keys[count($keys)-1]]; ||           494 |           593 |           418 |           435 |           399 |         3.873 |    12.199.450 ||           665 |           407 |           103 |           109 |           114 |           431 |    30.053.730 ||           647 |           445 |            91 |            95 |            96 |           419 |    30.718.586 ||
||  9.  $x = $array[] = array_pop($array);                              ||           186 |           178 |           175 |           188 |           180 |           181 |           186 ||            83 |            78 |            75 |            71 |            74 |            69 |            83 ||            71 |            64 |            70 |            64 |            68 |            69 |            81 ||
|| 10.  $x = $array[array_key_last($array)];                            ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           N/A |           N/A |           N/A |           N/A |           N/A |           N/A |           N/A ||           370 |           223 |            49 |            52 |            61 |            57 |            52 ||
 \=========================================================================================================================================================================================================================================================================================================================================================================================================================/ 

The above mentioned Fatal, Warning and Notice codes translate as:

F1 = Fatal error: Call to undefined function array_key_last() in Command line code on line 1
F2 = Fatal error: Uncaught Error: Call to undefined function array_key_last() in Command line code:1
W1 = Warning: array_slice() expects parameter 1 to be array, null given in Command line code on line 1
W2 = Warning: array_values() expects parameter 1 to be array, null given in Command line code on line 1
W3 = Warning: array_pop() expects parameter 1 to be array, null given in Command line code on line 1
W4 = Warning: end() expects parameter 1 to be array, null given in Command line code on line 1
W5 = Warning: reset() expects parameter 1 to be array, null given in Command line code on line 1
W6 = Warning: array_keys() expects parameter 1 to be array, null given in Command line code on line 1
W7 = Warning: count(): Parameter must be an array or an object that implements Countable in Command line code on line 1
W8 = Warning: array_key_last() expects parameter 1 to be array, null given in Command line code on line 1
N1 = Notice: Undefined offset: 0 in Command line code on line 1
N2 = Notice: Only variables should be passed by reference in Command line code on line 1
N3 = Notice: Undefined offset: -1 in Command line code on line 1
N4 = Notice: Undefined index:  in Command line code on line 1

Based on this output I draw the following conclusions:

  • newer versions of PHP perform better with the exception of these options that became significantly slower:
    • option .6. $x = end((array_values($array)));
    • option .8. $keys = array_keys($array); $x = $array[$keys[count($keys)-1]];
  • these options scale best for very large arrays:
    • option .5. $x = end($array); reset($array);
    • option .7. $x = $array[count($array)-1];
    • option .9. $x = $array[] = array_pop($array);
    • option 10. $x = $array[array_key_last($array)]; (since PHP 7.3)
  • these options should only be used for auto-indexed arrays:
    • option .7. $x = $array[count($array)-1]; (due to use of count)
    • option .9. $x = $array[] = array_pop($array); (due to assigning value losing original key)
  • this option does not preserve the array's internal pointer
    • option .5. $x = end($array); reset($array);
  • this option is an attempt to modify option .5. to preserve the array's internal pointer (but sadly it does not scale well for very large arrays)
    • option .6. $x = end((array_values($array)));
  • the new array_key_last function seems to have none of the above mentioned limitations with the exception of still being an RC at the time of this writing (so use the RC or await it's release Dec 2018):
    • option 10. $x = $array[array_key_last($array)]; (since PHP 7.3)

A bit depending on whether using the array as stack or as queue you can make variations on option 9.

Prepend text to beginning of string

EcmaScript 2017 added special functions to string prototype for that. padStart and padEnd are two new methods available in JavaScript string prototype object. As their name implies, they allow for formatting a string by adding padding characters at the start or the end. (Not supported by IE11 and lower)

var mystr = "Doe";
mystr = mystr.padStart('John ');

How do you get a directory listing sorted by creation date in python?

This was my version:

import os

folder_path = r'D:\Movies\extra\new\dramas' # your path
os.chdir(folder_path) # make the path active
x = sorted(os.listdir(), key=os.path.getctime)  # sorted using creation time

folder = 0

for folder in range(len(x)):
    print(x[folder]) # print all the foldername inside the folder_path
    folder = +1

How to know a Pod's own IP address from inside a container in the Pod?

kubectl get pods -o wide

Give you a list of pods with name, status, ip, node...

Error Code: 2013. Lost connection to MySQL server during query

I had the same problem - but for me the solution was a DB user with too strict permissions. I had to allow the Execute ability on the mysql table. After allowing that I had no dropping connections anymore

Start service in Android

startService(new Intent(this, MyService.class));

Just writing this line was not sufficient for me. Service still did not work. Everything had worked only after registering service at manifest

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    ...

    <service
        android:name=".MyService"
        android:label="My Service" >
    </service>
</application>

Value Change Listener to JTextField

I am brand new to WindowBuilder, and, in fact, just getting back into Java after a few years, but I implemented "something", then thought I'd look it up and came across this thread.

I'm in the middle of testing this, so, based on being new to all this, I'm sure I must be missing something.

Here's what I did, where "runTxt" is a textbox and "runName" is a data member of the class:

public void focusGained(FocusEvent e) {
    if (e.getSource() == runTxt) {
        System.out.println("runTxt got focus");
        runTxt.selectAll();
    }
}

public void focusLost(FocusEvent e) {
    if (e.getSource() == runTxt) {
        System.out.println("runTxt lost focus");
        if(!runTxt.getText().equals(runName))runName= runTxt.getText();
        System.out.println("runText.getText()= " + runTxt.getText() + "; runName= " + runName);
    }
}

Seems a lot simpler than what's here so far, and seems to be working, but, since I'm in the middle of writing this, I'd appreciate hearing of any overlooked gotchas. Is it an issue that the user could enter & leave the textbox w/o making a change? I think all you've done is an unnecessary assignment.

How to run shell script on host from docker container?

My laziness led me to find the easiest solution that wasn't published as an answer here.

It is based on the great article by luc juggery.

All you need to do in order to gain a full shell to your linux host from within your docker container is:

docker run --privileged --pid=host -it alpine:3.8 \
nsenter -t 1 -m -u -n -i sh

Explanation:

--privileged : grants additional permissions to the container, it allows the container to gain access to the devices of the host (/dev)

--pid=host : allows the containers to use the processes tree of the Docker host (the VM in which the Docker daemon is running) nsenter utility: allows to run a process in existing namespaces (the building blocks that provide isolation to containers)

nsenter (-t 1 -m -u -n -i sh) allows to run the process sh in the same isolation context as the process with PID 1. The whole command will then provide an interactive sh shell in the VM

This setup has major security implications and should be used with cautions (if any).

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

I tried the solution below, it works on my machine.

<context:property-placeholder location="classpath*:connection.properties" ignore-unresolvable="true" order="1" />

<context:property-placeholder location="classpath*:general.properties" order="2"/>

In case multiple elements are present in the Spring context, there are a few best practices that should be followed:

the order attribute needs to be specified to fix the order in which these are processed by Spring all property placeholders minus the last one (highest order) should have ignore-unresolvable=”true” to allow the resolution mechanism to pass to others in the context without throwing an exception

source: http://www.baeldung.com/2012/02/06/properties-with-spring/

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

Can I change the headers of the HTTP request sent by the browser?

ModHeader extension for Google Chrome, is also a good option. You can just set the Headers you want and just enter the URL in the browser, it will automatically take the headers from the extension when you hit the url. Only thing is, it will send headers for each and every URL you will hit so you have to disable or delete it after use.

(change) vs (ngModelChange) in angular

In Angular 7, the (ngModelChange)="eventHandler()" will fire before the value bound to [(ngModel)]="value" is changed while the (change)="eventHandler()" will fire after the value bound to [(ngModel)]="value" is changed.

How to prevent scrollbar from repositioning web page?

Wrap the content of your scrollable element into a div and apply padding-left: calc(100vw - 100%);.

<body>
    <div style="padding-left: calc(100vw - 100%);">
        Some Content that is higher than the user's screen
    </div>
</body>

The trick is that 100vw represents 100% of the viewport including the scrollbar. If you subtract 100%, which is the available space without the scrollbar, you end up with the width of the scrollbar or 0 if it is not present. Creating a padding of that width on the left will simulate a second scrollbar, shifting centered content back to the right.

Please note that this will only work if the scrollable element uses the page's entire width, but this should be no problem most of the time because there are only few other cases where you have centered scrollable content.

Getting error "The package appears to be corrupt" while installing apk file

After searching a lot I found a solution:

Go to Build-> Build Apk(s).

After creating apk you will see a dialog as below.

enter image description here

Click on locate and install it in your phone

Enjoy

How can I open multiple files using "with open" in Python?

Just replace and with , and you're done:

try:
    with open('a', 'w') as a, open('b', 'w') as b:
        do_something()
except IOError as e:
    print 'Operation failed: %s' % e.strerror

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

How do I make an HTML button not reload the page

I can't comment yet, so I'm posting this as an answer. Best way to avoid reload is how @user2868288 said: using the onsubmit on the form tag.

From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page. For example:

<form id="frmData" onsubmit="return false">
 <input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
 <input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
 <input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
  $(document).ready(function(){
    $('#btnSubmit').click(function() {
        var tel = $("#txtTel").val();
        var email = $("#txtEmail").val();
        $.post("scripts/contact.php", {
            tel1: tel,
            email1: email
        })
        .done(function(data) {
            $('#lblEstatus').append(data); // Appends status
            if (data == "Received") {
                $("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
            }
        })
        .fail(function(xhr, textStatus, errorThrown) { 
            $('#lblEstatus').append("Error. Try later."); 
        });
     });
   }); 
</script>

How to gracefully handle the SIGKILL signal in Java

There are ways to handle your own signals in certain JVMs -- see this article about the HotSpot JVM for example.

By using the Sun internal sun.misc.Signal.handle(Signal, SignalHandler) method call you are also able to register a signal handler, but probably not for signals like INT or TERM as they are used by the JVM.

To be able to handle any signal you would have to jump out of the JVM and into Operating System territory.

What I generally do to (for instance) detect abnormal termination is to launch my JVM inside a Perl script, but have the script wait for the JVM using the waitpid system call.

I am then informed whenever the JVM exits, and why it exited, and can take the necessary action.

Check if table exists without using "select from"

Here is a table that is not a SELECT * FROM

SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = not exist

Got this from a database pro, here is what I was told:

select 1 from `tablename`; //avoids a function call
select * from INFORMATION_SCHEMA.tables where schema = 'db' and table = 'table' // slow. Field names not accurate
SHOW TABLES FROM `db` LIKE 'tablename'; //zero rows = does not exist

Unbound classpath container in Eclipse

Given the FAQ, sharing a project file seems have to have advantages and is even recommended practice for Java projects (personally, I would not do that).

Maybe some of the following work for you:

  1. Edit the project's properties (right-click project, Properties, Java Build Path, Libraries, Remove and Add Library.
  2. Import the project's files without the "project file"
  3. Install JDK1.5 from http://java.sun.com/javase/downloads/index_jdk5.jsp and see whether you can fix paths

How to upload images into MySQL database using PHP code

Just few more details:

  • Add mysql field

`image` blob

  • Get data from image

$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));

  • Insert image data into db

$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";

  • Show image to the web

<img src="data:image/png;base64,'.base64_encode($row['image']).'">

  • End

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

If you open /Users/{your name}/android sdks/tools/android (double click it), then click on "Android SDK Manager" menu and then "Preferences" and then you can change your proxy settings specifically for Android SDK Manager. These proxy settings also apply to "Android SDK Manager" if used within Eclipse.

How do I get extra data from intent on Android?

If used in a FragmentActivity, try this:

The first page extends FragmentActivity

Intent Tabdetail = new Intent(getApplicationContext(), ReceivePage.class);
Tabdetail.putExtra("Marker", marker.getTitle().toString());
startActivity(Tabdetail);

In the fragment, you just need to call getActivity() first,

The second page extends Fragment:

String receive = getActivity().getIntent().getExtras().getString("name");

Subset dataframe by multiple logical conditions of rows to remove

This answer is more meant to explain why, not how. The '==' operator in R is vectorized in a same way as the '+' operator. It matches the elements of whatever is on the left side to the elements of whatever is on the right side, per element. For example:

> 1:3 == 1:3
[1] TRUE TRUE TRUE

Here the first test is 1==1 which is TRUE, the second 2==2 and the third 3==3. Notice that this returns a FALSE in the first and second element because the order is wrong:

> 3:1 == 1:3
[1] FALSE  TRUE FALSE

Now if one object is smaller then the other object then the smaller object is repeated as much as it takes to match the larger object. If the size of the larger object is not a multiplication of the size of the smaller object you get a warning that not all elements are repeated. For example:

>  1:2 == 1:3
[1]  TRUE  TRUE FALSE
Warning message:
In 1:2 == 1:3 :
  longer object length is not a multiple of shorter object length

Here the first match is 1==1, then 2==2, and finally 1==3 (FALSE) because the left side is smaller. If one of the sides is only one element then that is repeated:

> 1:3 == 1
[1]  TRUE FALSE FALSE

The correct operator to test if an element is in a vector is indeed '%in%' which is vectorized only to the left element (for each element in the left vector it is tested if it is part of any object in the right element).

Alternatively, you can use '&' to combine two logical statements. '&' takes two elements and checks elementwise if both are TRUE:

> 1:3 == 1 & 1:3 != 2
[1]  TRUE FALSE FALSE

Default string initialization: NULL or Empty?

For most software that isn't actually string-processing software, program logic ought not to depend on the content of string variables. Whenever I see something like this in a program:

if (s == "value")

I get a bad feeling. Why is there a string literal in this method? What's setting s? Does it know that logic depends on the value of the string? Does it know that it has to be lower case to work? Should I be fixing this by changing it to use String.Compare? Should I be creating an Enum and parsing into it?

From this perspective, one gets to a philosophy of code that's pretty simple: you avoid examining a string's contents wherever possible. Comparing a string to String.Empty is really just a special case of comparing it to a literal: it's something to avoid doing unless you really have to.

Knowing this, I don't blink when I see something like this in our code base:

string msg = Validate(item);
if (msg != null)
{
   DisplayErrorMessage(msg);
   return;
}

I know that Validate would never return String.Empty, because we write better code than that.

Of course, the rest of the world doesn't work like this. When your program is dealing with user input, databases, files, and so on, you have to account for other philosophies. There, it's the job of your code to impose order on chaos. Part of that order is knowing when an empty string should mean String.Empty and when it should mean null.

(Just to make sure I wasn't talking out of my ass, I just searched our codebase for `String.IsNullOrEmpty'. All 54 occurrences of it are in methods that process user input, return values from Python scripts, examine values retrieved from external APIs, etc.)

notifyDataSetChanged not working on RecyclerView

Although it is a bit strange, but the notifyDataSetChanged does not really work without setting new values to adapter. So, you should do:

array = getNewItems();                    
((MyAdapter) mAdapter).setValues(array);  // pass the new list to adapter !!!
mAdapter.notifyDataSetChanged();       

This has worked for me.

How to insert spaces/tabs in text using HTML/CSS

In cases wherein the width/height of the space is beyond &nbsp; I usually use:

For horizontal spacer:

<span style="display:inline-block; width: YOURWIDTH;"></span>

For vertical spacer:

<span style="display:block; height: YOURHEIGHT;"></span>

How do I determine k when using k-means clustering?

If you don't know the numbers of the clusters k to provide as parameter to k-means so there are four ways to find it automaticaly:

  • G-means algortithm: it discovers the number of clusters automatically using a statistical test to decide whether to split a k-means center into two. This algorithm takes a hierarchical approach to detect the number of clusters, based on a statistical test for the hypothesis that a subset of data follows a Gaussian distribution (continuous function which approximates the exact binomial distribution of events), and if not it splits the cluster. It starts with a small number of centers, say one cluster only (k=1), then the algorithm splits it into two centers (k=2) and splits each of these two centers again (k=4), having four centers in total. If G-means does not accept these four centers then the answer is the previous step: two centers in this case (k=2). This is the number of clusters your dataset will be divided into. G-means is very useful when you do not have an estimation of the number of clusters you will get after grouping your instances. Notice that an inconvenient choice for the "k" parameter might give you wrong results. The parallel version of g-means is called p-means. G-means sources: source 1 source 2 source 3

  • x-means: a new algorithm that efficiently, searches the space of cluster locations and number of clusters to optimize the Bayesian Information Criterion (BIC) or the Akaike Information Criterion (AIC) measure. This version of k-means finds the number k and also accelerates k-means.

  • Online k-means or Streaming k-means: it permits to execute k-means by scanning the whole data once and it finds automaticaly the optimal number of k. Spark implements it.

  • MeanShift algorithm: it is a nonparametric clustering technique which does not require prior knowledge of the number of clusters, and does not constrain the shape of the clusters. Mean shift clustering aims to discover “blobs” in a smooth density of samples. It is a centroid-based algorithm, which works by updating candidates for centroids to be the mean of the points within a given region. These candidates are then filtered in a post-processing stage to eliminate near-duplicates to form the final set of centroids. Sources: source1, source2, source3

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

Invoke(Delegate)

It means that the delegate you pass is executed on the thread that created the Control object (which is the UI thread).

You need to call this method when your application is multi-threaded and you want do some UI operation from a thread other than the UI thread, because if you just try to call a method on a Control from a different thread you'll get a System.InvalidOperationException.

Why can't Python parse this JSON data?

Justin Peel's answer is really helpful, but if you are using Python 3 reading JSON should be done like this:

with open('data.json', encoding='utf-8') as data_file:
    data = json.loads(data_file.read())

Note: use json.loads instead of json.load. In Python 3, json.loads takes a string parameter. json.load takes a file-like object parameter. data_file.read() returns a string object.

To be honest, I don't think it's a problem to load all json data into memory in most cases. I see this in JS, Java, Kotlin, cpp, rust almost every language I use. Consider memory issue like a joke to me :)

On the other hand, I don't think you can parse json without reading all of it.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

did you add the shebang to the top of the file?

#!/usr/bin/python

How can I require at least one checkbox be checked before a form can be submitted?

You can either do this on a PHP level or on a Javascript level. If you use Javascript, and/or JQuery, you can check and validate if all the checkboxes are checked with a selector...

Jquery also offers several validation libraries. Check out: http://jqueryvalidation.org/

The problem with using Javascript to validate is that it may be bypassed so it is wise to check on the server too.

Example using PHP and assuming you are calling a PO

<?php
    if( $_GET["BoxSelect"] )
 {
     //Process your form here
     // Save to database, send email, redirect...
} else {

     // Return an error and do not anything
     echo "Checkbox is missing"; 


     exit();
 }
?>

jQuery Date Picker - disable past dates

You must create a new date object and set it as minDate when you initialize the datepickers

<label for="from">From</label> <input type="text" id="from" name="from"/> <label for="to">to</label> <input type="text" id="to" name="to"/>

var dateToday = new Date();
var dates = $("#from, #to").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    minDate: dateToday,
    onSelect: function(selectedDate) {
        var option = this.id == "from" ? "minDate" : "maxDate",
            instance = $(this).data("datepicker"),
            date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
        dates.not(this).datepicker("option", option, date);
    }
});

Edit - from your comment now it works as expected http://jsfiddle.net/nicolapeluchetti/dAyzq/1/

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

How to get autocomplete in jupyter notebook without using tab?

The auto-completion with Jupyter Notebook is so weak, even with hinterland extension. Thanks for the idea of deep-learning-based code auto-completion. I developed a Jupyter Notebook Extension based on TabNine which provides code auto-completion based on Deep Learning. Here's the Github link of my work: jupyter-tabnine.

It's available on pypi index now. Simply issue following commands, then enjoy it:)

pip3 install jupyter-tabnine
jupyter nbextension install --py jupyter_tabnine
jupyter nbextension enable --py jupyter_tabnine
jupyter serverextension enable --py jupyter_tabnine

demo

How to convert all tables in database to one collation?

@Namphibian's suggestion helped me a lot...
went a little further though and added columns and views to the script

just enter your schema's name below and it will do the rest

-- set your table name here
SET @MY_SCHEMA = "";

-- tables
SELECT DISTINCT
    CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA=@MY_SCHEMA
  AND TABLE_TYPE="BASE TABLE"

UNION

-- table columns
SELECT DISTINCT
    CONCAT("ALTER TABLE ", C.TABLE_NAME, " CHANGE ", C.COLUMN_NAME, " ", C.COLUMN_NAME, " ", C.COLUMN_TYPE, " CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;") as queries
FROM INFORMATION_SCHEMA.COLUMNS as C
    LEFT JOIN INFORMATION_SCHEMA.TABLES as T
        ON C.TABLE_NAME = T.TABLE_NAME
WHERE C.COLLATION_NAME is not null
    AND C.TABLE_SCHEMA=@MY_SCHEMA
    AND T.TABLE_TYPE="BASE TABLE"

UNION

-- views
SELECT DISTINCT
    CONCAT("CREATE OR REPLACE VIEW ", V.TABLE_NAME, " AS ", V.VIEW_DEFINITION, ";") as queries
FROM INFORMATION_SCHEMA.VIEWS as V
    LEFT JOIN INFORMATION_SCHEMA.TABLES as T
        ON V.TABLE_NAME = T.TABLE_NAME
WHERE V.TABLE_SCHEMA=@MY_SCHEMA
    AND T.TABLE_TYPE="VIEW";

Differences between fork and exec

The prime example to understand the fork() and exec() concept is the shell,the command interpreter program that users typically executes after logging into the system.The shell interprets the first word of command line as a command name

For many commands,the shell forks and the child process execs the command associated with the name treating the remaining words on the command line as parameters to the command.

The shell allows three types of commands. First, a command can be an executable file that contains object code produced by compilation of source code (a C program for example). Second, a command can be an executable file that contains a sequence of shell command lines. Finally, a command can be an internal shell command.(instead of an executable file ex->cd,ls etc.)

How to get the sign, mantissa and exponent of a floating point number

On Linux package glibc-headers provides header #include <ieee754.h> with floating point types definitions, e.g.:

union ieee754_double
  {
    double d;

    /* This is the IEEE 754 double-precision format.  */
    struct
      {
#if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int negative:1;
    unsigned int exponent:11;
    /* Together these comprise the mantissa.  */
    unsigned int mantissa0:20;
    unsigned int mantissa1:32;
#endif              /* Big endian.  */
#if __BYTE_ORDER == __LITTLE_ENDIAN
# if    __FLOAT_WORD_ORDER == __BIG_ENDIAN
    unsigned int mantissa0:20;
    unsigned int exponent:11;
    unsigned int negative:1;
    unsigned int mantissa1:32;
# else
    /* Together these comprise the mantissa.  */
    unsigned int mantissa1:32;
    unsigned int mantissa0:20;
    unsigned int exponent:11;
    unsigned int negative:1;
# endif
#endif              /* Little endian.  */
      } ieee;

    /* This format makes it easier to see if a NaN is a signalling NaN.  */
    struct
      {
#if __BYTE_ORDER == __BIG_ENDIAN
    unsigned int negative:1;
    unsigned int exponent:11;
    unsigned int quiet_nan:1;
    /* Together these comprise the mantissa.  */
    unsigned int mantissa0:19;
    unsigned int mantissa1:32;
#else
# if    __FLOAT_WORD_ORDER == __BIG_ENDIAN
    unsigned int mantissa0:19;
    unsigned int quiet_nan:1;
    unsigned int exponent:11;
    unsigned int negative:1;
    unsigned int mantissa1:32;
# else
    /* Together these comprise the mantissa.  */
    unsigned int mantissa1:32;
    unsigned int mantissa0:19;
    unsigned int quiet_nan:1;
    unsigned int exponent:11;
    unsigned int negative:1;
# endif
#endif
      } ieee_nan;
  };

#define IEEE754_DOUBLE_BIAS 0x3ff /* Added to exponent.  */

Two Divs on the same row and center align both of them

Please take a look on flex it will help you make things right,

on the main div set css display :flex

the div's that inside set css: flex:1 1 auto;

attached jsfiddle link as example enjoy :)

https://jsfiddle.net/hodca/v1uLsxbg/

eval command in Bash and its typical uses

Simply think of eval as "evaluating your expression one additional time before execution"

eval echo \${$n} becomes echo $1 after the first round of evaluation. Three changes to notice:

  • The \$ became $ (The backslash is needed, otherwise it tries to evaluate ${$n}, which means a variable named {$n}, which is not allowed)
  • $n was evaluated to 1
  • The eval disappeared

In the second round, it is basically echo $1 which can be directly executed.

So eval <some command> will first evaluate <some command> (by evaluate here I mean substitute variables, replace escaped characters with the correct ones etc.), and then run the resultant expression once again.

eval is used when you want to dynamically create variables, or to read outputs from programs specifically designed to be read like this. See http://mywiki.wooledge.org/BashFAQ/048 for examples. The link also contains some typical ways in which eval is used, and the risks associated with it.

How to convert an enum type variable to a string?

Personally, I would go for something simple and use an operator to do so.

Considering the following enum:

enum WeekDay { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

We can create an operator to output the result in an std::ostream.

std::ostream &operator<<(std::ostream &stream, const WeekDay day) {
  switch (day) {
    case MONDAY:
      stream << "Monday";
      break;
    case TUESDAY:
      stream << "Tuesday";
      break;
    case WEDNESDAY:
      stream << "Wednesday";
      break;
    case THURSDAY:
      stream << "Thursday";
      break;
    case FRIDAY:
      stream << "Friday";
      break;
    case SATURDAY:
      stream << "Saturday";
      break;
    case SUNDAY:
      stream << "Sunday";
      break;
  }

  return stream;
}

The boilerplate code is indeed pretty big compared to some other methods presented in this thread. Still, it has the avantage of being pretty straightforward and easy to use.

std::cout << "First day of the week is " << WeekDay::Monday << std::endl;

How to create unit tests easily in eclipse

You can use my plug-in to create tests easily:

  1. highlight the method
  2. press Ctrl+Alt+Shift+U
  3. it will create the unit test for it.

The plug-in is available here. Hope this helps.