Programs & Examples On #Swf decompiler

How to Convert the value in DataTable into a string array in c#

Perhaps something like this, assuming that there are many of these rows inside of the datatable and that each row is row:

List<string[]> MyStringArrays = new List<string[]>();
foreach( var row in datatable.rows )//or similar
 MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );

You could then access one:


If you use linqpad, here is a very simple scenario of your example:

class Datatable
 public List<data> rows { get; set; }
 public Datatable(){
  rows = new List<data>();

class data
 public string Name { get; set; }
 public string Address { get; set; }
 public int Age { get; set; }

void Main()
 var datatable = new Datatable();
 var r = new data();
 r.Name = "Jim";
 r.Address = "USA";
 r.Age = 23;
 List<string[]> MyStringArrays = new List<string[]>();
 foreach( var row in datatable.rows )//or similar
  MyStringArrays.Add( new string[]{row.Name,row.Address,row.Age.ToString()} );
 var s = MyStringArrays.ElementAt(0)[1];

Adding elements to a C# array

You can use this snippet:

static void Main(string[] args)

        Console.WriteLine("Enter number:");
        int fnum = 0;
        bool chek = Int32.TryParse(Console.ReadLine(),out fnum);            

        Console.WriteLine("Enter number:");
        int snum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out snum);

        Console.WriteLine("Enter number:");
        int thnum = 0;
        chek = Int32.TryParse(Console.ReadLine(),out thnum);

        int[] arr = AddToArr(fnum,snum,thnum);

        IOrderedEnumerable<int> oarr = arr.OrderBy(delegate(int s)
            return s;

        Console.WriteLine("Here your result:");

        oarr.ToList().FindAll(delegate(int num) {


            return num > 0;



public static int[] AddToArr(params int[] arr) {

    return arr;

I hope this will help to you, just change the type

Using wget to recursively fetch a directory with arbitrary files in it

You should be able to do it simply by adding a -r

wget -r

Process escape sequences in a string in Python

Below code should work for \n is required to be displayed on the string.

import string

our_str = 'The String is \\n, \\n and \\n!'
new_str = string.replace(our_str, '/\\n', '/\n', 1)

Good way of getting the user's location in Android

I scoured the internet for an updated (past year) answer using the latest location pulling methods suggested by google (to use FusedLocationProviderClient). I finally landed on this:

I created a new project and copied in most of this code. Boom. It works. And I think without any deprecated lines.

Also, the simulator doesn't seem to get a GPS location, that I know of. It did get as far as reporting this in the log: "All location settings are satisfied."

And finally, in case you wanted to know (I did), you DO NOT need a google maps api key from the google developer console, if all you want is the GPS location.

Also useful is their tutorial. But I wanted a full one page tutorial/code example, and that. Their tutorial stacks but is confusing when you're new to this because you don't know what pieces you need from earlier pages.

And finally, remember things like this:

I not only had to modify the mainActivity.Java. I also had to modify Strings.xml, androidmanifest.xml, AND the correct build.gradle. And also your activity_Main.xml (but that part was easy for me).

I needed to add dependencies like this one: implementation '', and update the settings of my android studio SDK to include google play services. (file settings appearance system settings android SDK SDK Tools check google play services).

update: the android simulator did seem to get a location and location change events (when I changed the value in the settings of the sim). But my best and first results were on an actual device. So it's probably easiest to test on actual devices.

FFmpeg on Android

First, add the dependency of FFmpeg library

implementation 'com.writingminds:FFmpegAndroid:0.3.2'

Then load in activity

FFmpeg ffmpeg;
    private void trimVideo(ProgressDialog progressDialog) {

    outputAudioMux = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getAbsolutePath()
            + "/VidEffectsFilter" + "/" + new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date())
            + "filter_apply.mp4";

    if (startTrim.equals("")) {
        startTrim = "00:00:00";

    if (endTrim.equals("")) {
        endTrim = timeTrim(player.getDuration());

    String[] cmd = new String[]{"-ss", startTrim + ".00", "-t", endTrim + ".00", "-noaccurate_seek", "-i", videoPath, "-codec", "copy", "-avoid_negative_ts", "1", outputAudioMux};

    execFFmpegBinary1(cmd, progressDialog);

    private void execFFmpegBinary1(final String[] command, ProgressDialog prpg) {

    ProgressDialog progressDialog = prpg;

    try {
        ffmpeg.execute(command, new ExecuteBinaryResponseHandler() {
            public void onFailure(String s) {
                Toast.makeText(PlayerTestActivity.this, "Fail to generate video", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "FAILED with output : " + s);

            public void onSuccess(String s) {
                Log.d(TAG, "SUCCESS wgith output : " + s);

//                    pathVideo = outputAudioMux;
                String finalPath = outputAudioMux;
                videoPath = outputAudioMux;
                Toast.makeText(PlayerTestActivity.this, "Storage Path =" + finalPath, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(PlayerTestActivity.this, ShareVideoActivity.class);
                intent.putExtra("pathGPU", finalPath);
                MediaScannerConnection.scanFile(PlayerTestActivity.this, new String[]{finalPath}, new String[]{"mp4"}, null);


            public void onProgress(String s) {
                Log.d(TAG, "Started gcommand : ffmpeg " + command);
                progressDialog.setMessage("Please Wait video triming...");

            public void onStart() {
                Log.d(TAG, "Startedf command : ffmpeg " + command);


            public void onFinish() {
                Log.d(TAG, "Finished f command : ffmpeg " + command);
    } catch (FFmpegCommandAlreadyRunningException e) {
        // do nothing for now

  private void loadFFMpegBinary() {
    try {
        if (ffmpeg == null) {
            ffmpeg = FFmpeg.getInstance(this);
        ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
            public void onFailure() {

            public void onSuccess() {
                Log.d("dd", "ffmpeg : correct Loaded");
    } catch (FFmpegNotSupportedException e) {
    } catch (Exception e) {
        Log.d("dd", "EXception no controlada : " + e);

private void showUnsupportedExceptionDialog() {
    new AlertDialog.Builder(this)
            .setTitle("Not Supported")
            .setMessage("Device Not Supported")
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

    public String timeTrim(long milliseconds) {
        String finalTimerString = "";
        String minutString = "";
        String secondsString = "";

        // Convert total duration into time
        int hours = (int) (milliseconds / (1000 * 60 * 60));
        int minutes = (int) (milliseconds % (1000 * 60 * 60)) / (1000 * 60);
        int seconds = (int) ((milliseconds % (1000 * 60 * 60)) % (1000 * 60) / 1000);
        // Add hours if there

        if (hours < 10) {
            finalTimerString = "0" + hours + ":";
        } else {
            finalTimerString = hours + ":";

        if (minutes < 10) {
            minutString = "0" + minutes;
        } else {
            minutString = "" + minutes;

        // Prepending 0 to seconds if it is one digit
        if (seconds < 10) {
            secondsString = "0" + seconds;
        } else {
            secondsString = "" + seconds;

        finalTimerString = finalTimerString + minutString + ":" + secondsString;

        // return timer string
        return finalTimerString;

Also use another feature by FFmpeg

===> merge audio to video
String[] cmd = new String[]{"-i", yourRealPath, "-i", arrayList.get(posmusic).getPath(), "-map", "1:a", "-map", "0:v", "-codec", "copy", "-shortest", outputcrop};

===> Flip vertical :
String[] cm = new String[]{"-i", yourRealPath, "-vf", "vflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};

===> Flip horizontally :  
String[] cm = new String[]{"-i", yourRealPath, "-vf", "hflip", "-codec:v", "libx264", "-preset", "ultrafast", "-codec:a", "copy", outputcrop1};

===> Rotate 90 degrees clockwise:
String[] cm=new String[]{"-i", yourRealPath, "-c", "copy", "-metadata:s:v:0", "rotate=90", outputcrop1};

===> Compress Video
String[] complexCommand = {"-y", "-i", yourRealPath, "-strict", "experimental", "-vcodec", "libx264", "-preset", "ultrafast", "-crf", "24", "-acodec", "aac", "-ar", "22050", "-ac", "2", "-b", "360k", "-s", "1280x720", outputcrop1};

===> Speed up down video
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=2.0*PTS[v];[0:a]atempo=0.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=1.0*PTS[v];[0:a]atempo=1.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.75*PTS[v];[0:a]atempo=1.5[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};
String[] complexCommand = {"-y", "-i", yourRealPath, "-filter_complex", "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]", "-map", "[v]", "-map", "[a]", "-b:v", "2097k", "-r", "60", "-vcodec", "mpeg4", outputcrop1};

===> Add two mp3 files 

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(" -i ");
sb.append(" -filter_complex [0:0][1:0]concat=n=2:v=0:a=1[out] -map [out] ");
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()

===> Add three mp3 files

StringBuilder sb = new StringBuilder();
sb.append("-i ");
sb.append(" -i ");
sb.append(" -i ");
sb.append(" -filter_complex [0:0][1:0][2:0]concat=n=3:v=0:a=1[out] -map [out] ");
---> ffmpeg.execute(sb.toString().split(" "), new ExecuteBinaryResponseHandler()

Unable to start MySQL server

You should start by checking the error log and/or the startup message log when managing the instance using MySQL Workbench. There could be clues as to what is going wrong, which may be different than this scenario.

When I had this issue, it was because I used a space in the service name during installation. While it is technically valid, you should not do that. It seems that the MySQL Installer (and MySQL Notifier) does not put the name in quotes which causes it to use an incorrect service name later on. There are two ways to fix the problem (all commands should be run from an elevated command prompt).

Reinstall the server

The first is to simply reinstall MySQL Server 5.6 using the default, no-space service name MySQL56.

The installer uses the same value for the service name and service display name. The name that I had originally specified was for a display name, when it should have been a simple service name. After installation, if you so choose, the display name can safely be changed to use spaces and other characters by using:

sc config MySQL56 DisplayName= "MySQL 5.6"

Recreate the service

If you don't want to reinstall the server however, you will have to recreate the service. Start by removing the old service:

mysqld --remove "service_name"

Now install the replacement. You can use --install to create a service that starts with the system automatically, or --install-manual to create a service that requires you to start it.

mysqld --install-manual "service_name" --local-service --defaults-file="C:\path\to\mysql\my.ini"

This creates a service that runs as the LocalService account which presents anonymous credentials on the network however. Under most circumstances this is fine, but if you want to use the NetworkService account (which is what the installer creates the service as) you can change it using the Services administrative tool.

Onclick javascript to make browser go back to previous page?

You just need to call the following:


Serializing a list to JSON

If using .Net Core 3.0 or later;

Default to using the built in System.Text.Json parser implementation.


using System.Text.Json;

var json = JsonSerializer.Serialize(aList);

alternatively, other, less mainstream options are available like Utf8Json parser and Jil: These may offer superior performance, if you really need it but, you will need to install their respective packages.

If stuck using .Net Core 2.2 or earlier;

Default to using Newtonsoft JSON.Net as your first choice JSON Parser.


using Newtonsoft.Json;

var json = JsonConvert.SerializeObject(aList);

you may need to install the package first.

PM> Install-Package Newtonsoft.Json

For more details see and upvote the answer that is the source of this information.

For reference only, this was the original answer, many years ago;

// you need to reference System.Web.Extensions

using System.Web.Script.Serialization;

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

Examples of good gotos in C or C++

I've seen goto used correctly but the situations are normaly ugly. It is only when the use of goto itself is so much less worse than the original. @Johnathon Holland the poblem is you're version is less clear. people seem to be scared of local variables:

void foo()
    bool doAsuccess = doA();
    bool doBsuccess = doAsuccess && doB();
    bool doCsuccess = doBsuccess && doC();

    if (!doCsuccess)
        if (doBsuccess)
        if (doAsuccess)

And I prefer loops like this but some people prefer while(true).

for (;;)
    //code goes here

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Inside of VBS you can access parameters with


and so on. The number of parameter:


How to create two columns on a web page?

The simple and best solution is to use tables for layouts. You're doing it right. There are a number of reasons tables are better.

  • They perform better than CSS
  • They work on all browsers without any fuss
  • You can debug them easily with the border=1 attribute

How do I use a Boolean in Python?

Yes, there is a bool data type (which inherits from int and has only two values: True and False).

But also Python has the boolean-able concept for every object, which is used when function bool([x]) is called.

See more: object.nonzero and boolean-value-of-objects-in-python.

How to do Select All(*) in linq to sql

using (MyDataContext dc = new MyDataContext())
    var rows = from myRow in dc.MyTable
               select myRow;


using (MyDataContext dc = new MyDataContext())
    var rows = dc.MyTable.Select(row => row);

Property 'catch' does not exist on type 'Observable<any>'

With RxJS 5.5+, the catch operator is now deprecated. You should now use the catchError operator in conjunction with pipe.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including catchError you should now import from 'rxjs/operators' and use the pipe operator.

Example of catching error for an Http request Observable

import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.request(method, url, options).pipe(
      catchError((err: HttpErrorResponse) => {

Notice here that catch is replaced with catchError and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.

See the rxjs documentation on pipable (previously known as lettable) operators for more info.

jQuery UI Sortable, then write order into a database

I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.

How to download source in ZIP format from GitHub?

I've been stumped by this too. The "Download" button is to the far right, but you also need to be in the top folder in order to download what you're seeing. Go up as high as you can to the parent/root folder and then look for the download button.

How to resize an image to fit in the browser window?

For the future generations, if you want a solution that answers 1-6 and does 7 in a way that allows resize beyond to original size, I have developed a complete solution for this problem:

<!DOCTYPE html>
  <body style="overflow:hidden; margin:0; text-align:center;">
    <img src="" style="height:100vh; max-width:100%; object-fit: contain;">

How to check if a float value is a whole number

Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.

for i in range(20, 30):
    print("Trying {0}".format(i))
    if i ** 3 > 12000:
        print("Maximum integral cube root less than 12000: {0}".format(i - 1))

Cannot read property 'style' of undefined -- Uncaught Type Error

Add your <script> to the bottom of your <body>, or add an event listener for DOMContentLoaded following this StackOverflow question.

If that script executes in the <head> section of the code, document.getElementsByClassName(...) will return an empty array because the DOM is not loaded yet.

You're getting the Type Error because you're referencing search_span[0], but search_span[0] is undefined.

This works when you execute it in Dev Tools because the DOM is already loaded.

When is std::weak_ptr useful?

std::weak_ptr is a very good way to solve the dangling pointer problem. By just using raw pointers it is impossible to know if the referenced data has been deallocated or not. Instead, by letting a std::shared_ptr manage the data, and supplying std::weak_ptr to users of the data, the users can check validity of the data by calling expired() or lock().

You could not do this with std::shared_ptr alone, because all std::shared_ptr instances share the ownership of the data which is not removed before all instances of std::shared_ptr are removed. Here is an example of how to check for dangling pointer using lock():

#include <iostream>
#include <memory>

int main()
    // OLD, problem with dangling pointer
    // PROBLEM: ref will point to undefined data!

    int* ptr = new int(10);
    int* ref = ptr;
    delete ptr;

    // NEW
    // SOLUTION: check expired() or lock() to determine if pointer is valid

    // empty definition
    std::shared_ptr<int> sptr;

    // takes ownership of pointer
    sptr.reset(new int);
    *sptr = 10;

    // get pointer to data without taking ownership
    std::weak_ptr<int> weak1 = sptr;

    // deletes managed object, acquires new pointer
    sptr.reset(new int);
    *sptr = 5;

    // get pointer to new data without taking ownership
    std::weak_ptr<int> weak2 = sptr;

    // weak1 is expired!
    if(auto tmp = weak1.lock())
        std::cout << *tmp << '\n';
        std::cout << "weak1 is expired\n";

    // weak2 points to new data (5)
    if(auto tmp = weak2.lock())
        std::cout << *tmp << '\n';
        std::cout << "weak2 is expired\n";

PHP to search within txt file and echo the whole line

one way...

$needle = "blah";
$content = file_get_contents('file.txt');
echo $line[1];

though it would probably be better to read it line by line with fopen() and fread() and use strpos()

SQL conditional SELECT

This is a psuedo way of doing it

IF (selectField1 = true) 
SELECT Field1 FROM Table
SELECT Field2 FROM Table

How to get file name from file path in android

I think you can use substring method to get name of the file from the path string.

String path=":/storage/sdcard0/DCIM/Camera/1414240995236.jpg"; 
// it contains your image path...I'm using a temp string...
String filename=path.substring(path.lastIndexOf("/")+1);

SelectSingleNode returning null for known good xml node path using XPath

Roisgoen's answer worked for me, but to make it more general, you can use a RegEx:

//Substitute "My_RootNode" for whatever your root node is
string strRegex = @"<My_RootNode(?<xmlns>\s+xmlns([\s]|[^>])*)>";
var myMatch = new Regex(strRegex, RegexOptions.None).Match(myXmlDoc.InnerXml);
if (myMatch.Success)
    var grp = myMatch.Groups["xmlns"];
    if (grp.Success)
        myXmlDoc.InnerXml = myXmlDoc.InnerXml.Replace(grp.Value, "");

I fully admit that this is not a best-practice answer, but but it's an easy fix and sometimes that's all we need.

Error in MySQL when setting default value for DATE or DATETIME

First select current session sql_mode:

SELECT @@SESSION.sql_mode;

Then you will get something like that default value:


and then set sql_mode without 'NO_ZERO_DATE':


If you have grants, you can do it also for GLOBAL:

SELECT @@GLOBAL.sql_mode;
SET GLOBAL sql_mode = '...';

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

How can I create a product key for my C# application?

Whether it's trivial or hard to crack, I'm not sure that it really makes much of a difference.

The likelihood of your app being cracked is far more proportional to its usefulness rather than the strength of the product key handling.

Personally, I think there are two classes of user. Those who pay. Those who don't. The ones that do will likely do so with even the most trivial protection. Those who don't will wait for a crack or look elsewhere. Either way, it won't get you any more money.

Query comparing dates in SQL

Date format is yyyy-mm-dd. So the above query is looking for records older than 12Apr2013

Suggest you do a quick check by setting the date string to '2013-04-30', if no sql error, date format is confirmed to yyyy-mm-dd.

Calculate percentage saved between two numbers?

This is function with inverted option

It will return:

  • 'change' - string that you can use for css class in your template
  • 'result' - plain result
  • 'formatted' - formatted result

function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){

    $value      = $newNumber - $oldNumber;

    $change     = '';
    $sign       = '';

    $result     = 0.00;

    if ( $invert ) {
         if ( $value > 0 ) {
        //  going UP
            $change             = 'up';
            $sign               = '+';
            if ( $oldNumber > 0 ) {
                $result         = ($newNumber / $oldNumber) * 100;
            } else {
                $result     = 100.00;

        }elseif ( $value < 0 ) {        
        //  going DOWN
            $change             = 'down';
            //$value                = abs($value);
            $result             = ($oldNumber / $newNumber) * 100;
            $result             = abs($result);
            $sign               = '-';

        }else {
        //  no changes


        if ( $newNumber > $oldNumber ) {

            //  increase
            $change             = 'up';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

                $result = 100.00;

            $sign               = '+';

        }elseif ( $oldNumber > $newNumber ) {

            //  decrease
            $change             = 'down';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            } else {
                $result = 100.00;

            $sign               = '-';


            //  no change


        $result = abs($result);


    $result_formatted       = number_format($result, 2);

    if ( $invert ) {
        if ( $change == 'up' ) {
            $change = 'down';
        }elseif ( $change == 'down' ) {
            $change = 'up';

        if ( $sign == '+' ) {
            $sign = '-';
        }elseif ( $sign == '-' ) {
            $sign = '+';
    if ( $format ) {
        $formatted          = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
    } else{
        $formatted          = $result_formatted;

    return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );

How do you get a timestamp in JavaScript?

console.log(new Date().valueOf()); // returns the number of milliseconds since the epoch

SQL Server Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >=

The error implies that this subquery is returning more than 1 row:

(Select Supplier_Item.Price from Supplier_Item,orderdetails,Supplier where Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID )

You probably don't want to include the orderdetails and supplier tables in the subquery, because you want to reference the values selected from those tables in the outer query. So I think you want the subquery to be simply:

(Select Supplier_Item.Price from Supplier_Item where Supplier_Item.SKU=OrderDetails.Sku and Supplier_Item.SupplierId=Supplier.SupplierID )

I suggest you read up on correlated vs. non-correlated subqueries.

Android Studio doesn't start, fails saying components not installed

In OS X run as admin the first time by opening a new Terminal and run the commands:

cd /Applications/Android\

sudo ./studio

Convert seconds to Hour:Minute:Second

Just in case anyone else is looking for a simple function to return this nicely formatted (I know it is not the format the OP asked for), this is what I've just come up with. Thanks to @mughal for the code this was based on.

function format_timer_result($time_in_seconds){
    $time_in_seconds = ceil($time_in_seconds);

    // Check for 0
    if ($time_in_seconds == 0){
        return 'Less than a second';

    // Days
    $days = floor($time_in_seconds / (60 * 60 * 24));
    $time_in_seconds -= $days * (60 * 60 * 24);

    // Hours
    $hours = floor($time_in_seconds / (60 * 60));
    $time_in_seconds -= $hours * (60 * 60);

    // Minutes
    $minutes = floor($time_in_seconds / 60);
    $time_in_seconds -= $minutes * 60;

    // Seconds
    $seconds = floor($time_in_seconds);

    // Format for return
    $return = '';
    if ($days > 0){
        $return .= $days . ' day' . ($days == 1 ? '' : 's'). ' ';
    if ($hours > 0){
        $return .= $hours . ' hour' . ($hours == 1 ? '' : 's') . ' ';
    if ($minutes > 0){
        $return .= $minutes . ' minute' . ($minutes == 1 ? '' : 's') . ' ';
    if ($seconds > 0){
        $return .= $seconds . ' second' . ($seconds == 1 ? '' : 's') . ' ';
    $return = trim($return);

    return $return;

Purge Kafka Topic

Sometimes, if you've a saturated cluster (too many partitions, or using encrypted topic data, or using SSL, or the controller is on a bad node, or the connection is flaky, it'll take a long time to purge said topic.

I follow these steps, particularly if you're using Avro.

1: Run with kafka tools :

bash --alter --entity-type topics --zookeeper --add-config --entity-name <topic-name>

2: Run on Schema registry node:

kafka-avro-console-consumer --consumer-property security.protocol=SSL --consumer-property ssl.truststore.location=/etc/schema-registry/secrets/trust.jks --consumer-property ssl.truststore.password=password --consumer-property ssl.keystore.location=/etc/schema-registry/secrets/identity.jks --consumer-property ssl.keystore.password=password --consumer-property ssl.key.password=password --bootstrap-server --topic <topic-name> --new-consumer --from-beginning

3: Set topic retention back to the original setting, once topic is empty.

bash --alter --entity-type topics --zookeeper --add-config --entity-name <topic-name>

Hope this helps someone, as it isn't easily advertised.

How to select between brackets (or quotes or ...) in Vim?

Use arrows or hjkl to get to one of the bracketing expressions, then v to select visual (i.e. selecting) mode, then % to jump to the other bracket.

What is a non-capturing group in regular expressions?

You can use capturing groups to organize and parse an expression. A non-capturing group has the first benefit, but doesn't have the overhead of the second. You can still say a non-capturing group is optional, for example.

Say you want to match numeric text, but some numbers could be written as 1st, 2nd, 3rd, 4th,... If you want to capture the numeric part, but not the (optional) suffix you can use a non-capturing group.


That will match numbers in the form 1, 2, 3... or in the form 1st, 2nd, 3rd,... but it will only capture the numeric part.

How to move the cursor word by word in the OS X Terminal

I have Alt+/ working: open Preferences » Settings » Keyboard, set the entry for option cursor left to send string to shell: \033b, and set option cursor right to send string to shell: \033f. You can also use this for other Control key combinations.

How to declare a global variable in php?

$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:

function capital() {
    return my_var() . ' is the capital of Italy';

function my_var() {
    return 'Rome';

Date Format in Swift

You have to declare 2 different NSDateFormatters, the first to convert the string to a NSDate and the second to print the date in your format.
Try this code:

let dateFormatterGet = NSDateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = NSDateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

let date: NSDate? = dateFormatterGet.dateFromString("2016-02-29 12:24:26")

Swift 3 and higher:

From Swift 3 NSDate class has been changed to Date and NSDateFormatter to DateFormatter.

let dateFormatterGet = DateFormatter()
dateFormatterGet.dateFormat = "yyyy-MM-dd HH:mm:ss"

let dateFormatterPrint = DateFormatter()
dateFormatterPrint.dateFormat = "MMM dd,yyyy"

if let date = "2016-02-29 12:24:26") {
    print(dateFormatterPrint.string(from: date))
} else {
   print("There was an error decoding the string")

Node.js check if path is file or directory

The following should tell you. From the docs:


Objects returned from fs.stat() and fs.lstat() are of this type.

stats.isSymbolicLink() (only valid with fs.lstat())


The above solution will throw an Error if; for ex, the file or directory doesn't exist.

If you want a true or false approach, try fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory(); as mentioned by Joseph in the comments below.

LOAD DATA INFILE Error Code : 13

load data infile '/root/source/in.txt' into table employee; ==> Error Code:13

load data infile '/tmp/in.txt' into table employee; ==> works

CentOS release 6.6 (Final) - 5.5.32 MySQL Community Server (GPL)

something related to Linux file permissions

python: [Errno 10054] An existing connection was forcibly closed by the remote host

there are many causes such as

  • The network link between server and client may be temporarily going down.
  • running out of system resources.
  • sending malformed data.

To examine the problem in detail, you can use Wireshark.

or you can just re-request or re-connect again.

Open text file and program shortcut in a Windows batch file

Don't put quotes around the name of the file that you are trying to open; start "myfile.txt" opens a new command prompt with the title myfile.txt, while start myfile.txt opens myfile.txt in Notepad. There's no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start "" "my file.txt" works.

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

this post was made a while ago, but it provides an answer that did not solve the problem regarding reaching the limit of requests in an iteration for me, so I publish this, to help who else has not served.

My environment happened in Ionic 3.

Instead of making a "pause" in the iteration, I ocurred the idea of ??iterating with a timer, this timer has the particularity of executing the code that would go in the iteration, but will run every so often until it is reached the maximum count of the "Array" in which we want to iterate.

In other words, we will consult the Google API in a certain time so that it does not exceed the limit allowed in milliseconds.

// Code to start the timer
    this.count= 0;
    let loading = this.loadingCtrl.create({
      content: 'Buscando los mejores servicios...'
    this.interval = setInterval(() => this.getDistancias(loading), 40);
// Function that runs the timer, that is, query Google API
    if(this.count>= this.datos.length){
    } else {
      var sucursal = this.datos[this.count];
      this.calcularDistancia(this.posicion, new LatLng(parseFloat(sucursal.position.latitude),parseFloat(sucursal.position.longitude)),sucursal.codigo).then(distancia => {
    }).catch(error => {
    this.count += 1;
  calcularDistancia(miPosicion, markerPosicion, codigo){
    return new Promise(async (resolve,reject) => {
      var service = new google.maps.DistanceMatrixService;
      var distance;
      var duration;
        origins: [miPosicion, 'salida'],
        destinations: [markerPosicion, 'llegada'],
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
      }, function(response, status){
        if (status == 'OK') {
          var originList = response.originAddresses;
          var destinationList = response.destinationAddresses;
            if(response != null && response != undefined){
              distance = response.rows[0].elements[0].distance.value;
              duration = response.rows[0].elements[0].duration.text;
            console.log("ERROR GOOGLE");

I hope this helps!

I'm sorry for my English, I hope it's not an inconvenience, I had to use the Google translator.

Regards, Leandro.

Get UserDetails object from Security Context in Spring MVC controller

You can use below code to find out principal (user email who logged in)

  org.opensaml.saml2.core.impl.NameIDImpl principal =  
  (NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

  String email = principal.getValue();

This code is written on top of SAML.

Should I use Vagrant or Docker for creating an isolated environment?

Using both is an important part of application delivery testing. I am only beginning to get involved with Docker and thinking very hard about an application team that has terrible complexity in building and delivering its software. Think of a classic Phoenix Project / Continuous Delivery situation.

The thinking goes something like this:

  • Take a Java/Go application component and build it as a container (note, not sure if the app should be built in the container or built then installed to the container)
  • Deliver the container to a Vagrant VM.
  • Repeat this for all application components.
  • Iterate on the component(s) to code against.
  • Continuously test the delivery mechanism to the VM(s) managed by Vagrant
  • Sleep well knowing when it is time to deploy the container, that integration testing was occurring on a much more continuous basis than it was before Docker.

This seems to be the logical extension of Mitchell's statement that Vagrant is for development combined with Farley/Humbles thinking in Continuous Delivery. If I, as a developer, can shrink the feedback loop on integration testing and application delivery, higher quality and better work environments will follow.

The fact that as a developer I am constantly and consistently delivering containers to the VM and testing the application more holistically means that production releases will be further simplified.

So I see Vagrant evolving as a way of leveraging some of the awesome consequences Docker will have for app deployment.

ToggleClass animate jQuery?

.toggleClass() will not animate, you should go for slideToggle() or .animate() method.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:

This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.

In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.

You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.

Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)

Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:

public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
    if (uiElement == null)
        throw new ArgumentNullException("uiElement");

    if (uiElement.InvokeRequired)
        if (forceSynchronous)
            uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
            uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        if (uiElement.IsDisposed)
            throw new ObjectDisposedException("Control is already disposed.");


Consider the case where we're calling SafeInvoke from the non-gui thread for a control whose handle has not been created.

uiElement is not null, so we check uiElement.InvokeRequired. Per the MSDN docs (bolded) InvokeRequired will return false because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else condition where we check IsDisposed or immediately proceed to call the submitted action... from the background thread!

At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?

How to import data from text file to mysql database

If your table is separated by others than tabs, you should specify it like...

    INFILE '/tmp/mydata.txt' INTO TABLE PerformanceReport 
    COLUMNS TERMINATED BY '\t'  ## This should be your delimiter
    OPTIONALLY ENCLOSED BY '"'; ## ...and if text is enclosed, specify here

Should __init__() call the parent class's __init__()?

In Anon's answer:
"If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__ , you must call it yourself, since that will not happen automatically"

It's incredible: he is wording exactly the contrary of the principle of inheritance.

It is not that "something from super's __init__ (...) will not happen automatically" , it is that it WOULD happen automatically, but it doesn't happen because the base-class' __init__ is overriden by the definition of the derived-clas __init__

So then, WHY defining a derived_class' __init__ , since it overrides what is aimed at when someone resorts to inheritance ??

It's because one needs to define something that is NOT done in the base-class' __init__ , and the only possibility to obtain that is to put its execution in a derived-class' __init__ function.
In other words, one needs something in base-class' __init__ in addition to what would be automatically done in the base-classe' __init__ if this latter wasn't overriden.
NOT the contrary.

Then, the problem is that the desired instructions present in the base-class' __init__ are no more activated at the moment of instantiation. In order to offset this inactivation, something special is required: calling explicitly the base-class' __init__ , in order to KEEP , NOT TO ADD, the initialization performed by the base-class' __init__ . That's exactly what is said in the official doc:

An overriding method in a derived class may in fact want to extend rather than simply replace the base class method of the same name. There is a simple way to call the base class method directly: just call BaseClassName.methodname(self, arguments).

That's all the story:

  • when the aim is to KEEP the initialization performed by the base-class, that is pure inheritance, nothing special is needed, one must just avoid to define an __init__ function in the derived class

  • when the aim is to REPLACE the initialization performed by the base-class, __init__ must be defined in the derived-class

  • when the aim is to ADD processes to the initialization performed by the base-class, a derived-class' __init__ must be defined , comprising an explicit call to the base-class __init__

What I feel astonishing in the post of Anon is not only that he expresses the contrary of the inheritance theory, but that there have been 5 guys passing by that upvoted without turning a hair, and moreover there have been nobody to react in 2 years in a thread whose interesting subject must be read relatively often.

Is it possible to dynamically compile and execute C# code fragments?

To compile you could just initiate a shell call to the csc compiler. You may have a headache trying to keep your paths and switches straight but it certainly can be done.

C# Corner Shell Examples

EDIT: Or better yet, use the CodeDOM as Noldorin suggested...

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

I followed all of those instructions including the instructions from Android. What finally fixed it for me was changing Project Build Target from API level to API level 21 in my project.

I am using API 22 (Android 5.1.1), which is newer than when these other answers were written. So you cannot set target=21 in the support library as you could 6 months ago.

Difference between File.separator and slash in paths

"Java SE8 for Programmers" claims that the Java will cope with either. (pp. 480, last paragraph). The example claims that:

c:\Program Files\Java\jdk1.6.0_11\demo/jfc

will parse just fine. Take note of the last (Unix-style) separator.

It's tacky, and probably error-prone, but it is what they (Deitel and Deitel) claim.

I think the confusion for people, rather than Java, is reason enough not to use this (mis?)feature.

How can I get the actual video URL of a YouTube live stream?

This URL return to player actual video_id

Where UCkA21M22vGK9GtAvq3DvSlA is your channel id. You can find it inside YouTube account on "My Channel" link.

is there any way to force copy? copy without overwrite prompt, using windows?

MOVE /-Y Source Destination

Note:/-y will make the announcement of yes/no for overwrite

How to Change Margin of TextView

setMargins() sets the INNER margins of the TextView, not the layout-margins. Is that what you want to do? This two different margins can be quite complicated.

If you want to set the layout margins, change the LayoutParams of the TextView (textview.getLayoutParams(), then change the parameters on the returned LayoutParams object).

You don't need to change anything on your LinearLayout.

Regards, Oliver

Centering a background image, using CSS

I think this is what is wanted:

} get file names in directory?

You will need to use the IO.Directory.GetFiles function.

Dim files() As String = IO.Directory.GetFiles("c:\")

For Each file As String In files
  ' Do work, example
  Dim text As String = IO.File.ReadAllText(file)

Javascript - removing undefined fields from an object

Because it doesn't seem to have been mentioned, here's my preferred method, sans side effects or external dependencies:

const obj = {_x000D_
  a: 1,_x000D_
  b: undefined_x000D_
const newObject = Object.keys(obj).reduce((acc, key) => {_x000D_
  const _acc = acc;_x000D_
  if (obj[key] !== undefined) _acc[key] = obj[key];_x000D_
  return _acc;_x000D_
}, {})_x000D_
// Object {a: 1}

Javascript Equivalent to PHP Explode()

If you like php, take a look at php.JS - JavaScript explode

Or in normal JavaScript functionality: `

var vInputString = "0000000020C90037:TEMP:data";
var vArray = vInputString.split(":");
var vRes = vArray[1] + ":" + vArray[2]; `

Add a month to a Date

Here's a function that doesn't require any packages to be installed. You give it a Date object (or a character that it can convert into a Date), and it adds n months to that date without changing the day of the month (unless the month you land on doesn't have enough days in it, in which case it defaults to the last day of the returned month). Just in case it doesn't make sense reading it, there are some examples below.

Function definition

addMonth <- function(date, n = 1){
  if (n == 0){return(date)}
  if (n %% 1 != 0){stop("Input Error: argument 'n' must be an integer.")}

  # Check to make sure we have a standard Date format
  if (class(date) == "character"){date = as.Date(date)}

  # Turn the year, month, and day into numbers so we can play with them
  y = as.numeric(substr(as.character(date),1,4))
  m = as.numeric(substr(as.character(date),6,7))
  d = as.numeric(substr(as.character(date),9,10))

  # Run through the computation
  i = 0
  # Adding months
  if (n > 0){
    while (i < n){
      m = m + 1
      if (m == 13){
        m = 1
        y = y + 1
      i = i + 1
  # Subtracting months
  else if (n < 0){
    while (i > n){
      m = m - 1
      if (m == 0){
        m = 12
        y = y - 1
      i = i - 1

  # If past 28th day in base month, make adjustments for February
  if (d > 28 & m == 2){
      # If it's a leap year, return the 29th day
      if ((y %% 4 == 0 & y %% 100 != 0) | y %% 400 == 0){d = 29}
      # Otherwise, return the 28th day
      else{d = 28}
  # If 31st day in base month but only 30 days in end month, return 30th day
  else if (d == 31){if (m %in% c(1, 3, 5, 7, 8, 10, 12) == FALSE){d = 30}}

  # Turn year, month, and day into strings and put them together to make a Date
  y = as.character(y)

  # If month is single digit, add a leading 0, otherwise leave it alone
  if (m < 10){m = paste('0', as.character(m), sep = '')}
  else{m = as.character(m)}

  # If day is single digit, add a leading 0, otherwise leave it alone
  if (d < 10){d = paste('0', as.character(d), sep = '')}
  else{d = as.character(d)}

  # Put them together and convert return the result as a Date
  return(as.Date(paste(y,'-',m,'-',d, sep = '')))

Some examples

Adding months

> addMonth('2014-01-31', n = 1)
[1] "2014-02-28"  # February, non-leap year
> addMonth('2014-01-31', n = 5)
[1] "2014-06-30"  # June only has 30 days, so day of month dropped to 30
> addMonth('2014-01-31', n = 24)
[1] "2016-01-31"  # Increments years when n is a multiple of 12 
> addMonth('2014-01-31', n = 25)
[1] "2016-02-29"  # February, leap year

Subtracting months

> addMonth('2014-01-31', n = -1)
[1] "2013-12-31"
> addMonth('2014-01-31', n = -7)
[1] "2013-06-30"
> addMonth('2014-01-31', n = -12)
[1] "2013-01-31"
> addMonth('2014-01-31', n = -23)
[1] "2012-02-29"

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:




As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true


System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset


equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

Entity Framework - Include Multiple Levels of Properties

If I understand you correctly you are asking about including nested properties. If so :

.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)





Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

Take a look at it basically gives you a kick starter with either maven or gradle build.

Note: This is a Spring Boot based archetype.

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

I faced this problem when I tried to pass a serializable model object. Inside that model, another model was a variable but that wasn't serializable. That's why I face this problem. Make sure all the model inside of an model is serializable.

CSS disable hover effect

To disable the hover effect, I've got two suggestions:

  • if your hover effect is triggered by JavaScript, just use $.unbind('hover');
  • if your hover style is triggered by class, then just use $.removeClass('hoverCssClass');

Using CSS !important to override CSS will make your CSS very unclean thus that method is not recommended. You can always duplicate a CSS style with different class name to keep the same styling.

What's the difference between 'git merge' and 'git rebase'?

Git rebase is closer to a merge. The difference in rebase is:

  • the local commits are removed temporally from the branch.
  • run the git pull
  • insert again all your local commits.

So that means that all your local commits are moved to the end, after all the remote commits. If you have a merge conflict, you have to solve it too.

Angular2, what is the correct way to disable an anchor element?

Specifying pointer-events: none in CSS disables mouse input but doesn't disable keyboard input. For example, the user can still tab to the link and "click" it by pressing the Enter key or (in Windows) the ? Menu key. You could disable specific keystrokes by intercepting the keydown event, but this would likely confuse users relying on assistive technologies.

Probably the best way to disable a link is to remove its href attribute, making it a non-link. You can do this dynamically with a conditional href attribute binding:

<a *ngFor="let link of links"
   [attr.href]="isDisabled(link) ? null : '#'"
   (click)="!isDisabled(link) && onClick(link)">
   {{ }}

Or, as in Günter Zöchbauer's answer, you can create two links, one normal and one disabled, and use *ngIf to show one or the other:

<ng-template ngFor #link [ngForOf]="links">
    <a *ngIf="!isDisabled(link)" href="#" (click)="onClick(link)">{{ }}</a>
    <a *ngIf="isDisabled(link)" class="disabled">{{ }}</a>

Here's some CSS to make the link look disabled:

a.disabled {
    color: gray;
    cursor: not-allowed;
    text-decoration: underline;

What is the best way to paginate results in SQL Server

These are my solutions for paging the result of query in SQL server side. these approaches are different between SQL Server 2008 and 2012. Also, I have added the concept of filtering and order by with one column. It is very efficient when you are paging and filtering and ordering in your Gridview.

Before testing, you have to create one sample table and insert some row in this table : (In real world you have to change Where clause considering your table fields and maybe you have some join and subquery in main part of select)

Create Table VLT
    ID int IDentity(1,1),
    Name nvarchar(50),
    Tel Varchar(20)

    ('NAME' + Convert(varchar(10),@@identity),'FAMIL' + Convert(varchar(10),@@identity))
GO 500000

In all of these sample, I want to query 200 rows per page and I am fetching the row for page number 1200.

In SQL server 2008, you can use the CTE concept. Because of that, I have written two type of query for SQL server 2008+

-- SQL Server 2008+

DECLARE @PageNumber Int = 1200
DECLARE @PageSize INT = 200
DECLARE @SortByField int = 1 --The field used for sort by
DECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC
DECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)
DECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter
DECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.

        OVER( ORDER BY 
                CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'
                      THEN VLT.ID END ASC,
                CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'
                      THEN VLT.ID END DESC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'
                      THEN VLT.Tel END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'
                      THEN VLT.Tel END ASC
         ) AS RowNum
      ( -- We apply the filter logic here
          WHEN @FilterType = 'None' THEN 1

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 1
            AND VLT.ID = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1
            AND VLT.ID <> @FilterValue THEN 1               

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 2
            AND VLT.Name = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2
            AND VLT.Name <> @FilterValue THEN 1         

         -- Tel column filter   
         WHEN @FilterType = 'Contain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 3
            AND VLT.Tel = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3
            AND VLT.Tel <> @FilterValue THEN 1    

      ) = 1   
  ) AS Data
WHERE Data.RowNum > @PageSize * (@PageNumber - 1)
  AND Data.RowNum <= @PageSize * @PageNumber
ORDER BY Data.RowNum


And second solution with CTE in SQL server 2008+

DECLARE @PageNumber Int = 1200
DECLARE @PageSize INT = 200
DECLARE @SortByField int = 1 --The field used for sort by
DECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC
DECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)
DECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter
DECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.

        OVER( ORDER BY 
                CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'
                      THEN VLT.ID END ASC,
                CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'
                      THEN VLT.ID END DESC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'
                      THEN VLT.Name END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'
                      THEN VLT.Tel END ASC,
                CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'
                      THEN VLT.Tel END ASC
         ) AS RowNum
      ( -- We apply the filter logic here
          WHEN @FilterType = 'None' THEN 1

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 1
            AND VLT.ID = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1
            AND VLT.ID <> @FilterValue THEN 1               

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 2
            AND VLT.Name = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2
            AND VLT.Name <> @FilterValue THEN 1         

         -- Tel column filter   
         WHEN @FilterType = 'Contain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 3
            AND VLT.Tel = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3
            AND VLT.Tel <> @FilterValue THEN 1    

      ) = 1     

WHERE Data.RowNum > @PageSize * (@PageNumber - 1)
  AND Data.RowNum <= @PageSize * @PageNumber
ORDER BY Data.RowNum

-- SQL Server 2012+

DECLARE @PageNumber Int = 1200
DECLARE @PageSize INT = 200
DECLARE @SortByField int = 1 --The field used for sort by
DECLARE @SortOrder nvarchar(255) = 'ASC' --ASC or DESC
DECLARE @FilterType nvarchar(255) = 'None' --The filter type, as defined on the client side (None/Contain/NotContain/Match/NotMatch/True/False/)
DECLARE @FilterValue nvarchar(255) = '' --The value the user gave for the filter
DECLARE @FilterColumn int = 1 --The column to wich the filter is applied, represents the column number like when we send the information.

      ( -- We apply the filter logic here
          WHEN @FilterType = 'None' THEN 1

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 1
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.ID NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 1
            AND VLT.ID = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 1
            AND VLT.ID <> @FilterValue THEN 1               

          -- Name column filter
          WHEN @FilterType = 'Contain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 2
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Name NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 2
            AND VLT.Name = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 2
            AND VLT.Name <> @FilterValue THEN 1         

         -- Tel column filter   
         WHEN @FilterType = 'Contain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'NotContain' AND @FilterColumn = 3
            AND ( -- In this case, when the filter value is empty, we want to show everything.
                VLT.Tel NOT LIKE '%' + @FilterValue + '%'
                @FilterValue = ''
               ) THEN 1
          WHEN @FilterType = 'Match' AND @FilterColumn = 3
            AND VLT.Tel = @FilterValue THEN 1
          WHEN @FilterType = 'NotMatch' AND @FilterColumn = 3
            AND VLT.Tel <> @FilterValue THEN 1    

      ) = 1         

    CASE WHEN @SortByField = 1 AND @SortOrder = 'ASC'
        THEN Data.ID END ASC,
    CASE WHEN @SortByField = 1 AND @SortOrder = 'DESC'
        THEN Data.ID END DESC,
    CASE WHEN @SortByField = 2 AND @SortOrder = 'ASC'
        THEN Data.Name END ASC,
    CASE WHEN @SortByField = 2 AND @SortOrder = 'DESC'
        THEN Data.Name END ASC,
    CASE WHEN @SortByField = 3 AND @SortOrder = 'ASC'
        THEN Data.Tel END ASC,
    CASE WHEN @SortByField = 3 AND @SortOrder = 'DESC'
        THEN Data.Tel END ASC
OFFSET @PageSize * (@PageNumber - 1) ROWS FETCH NEXT @PageSize ROWS ONLY;

How to get the last element of an array in Ruby?

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

or Array#last method:

a.last # => 5
b.last # => 6

How to close a thread from within?

How about sys.exit() from the module sys.

If sys.exit() is executed from within a thread it will close that thread only.

This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

Reload an iframe with jQuery

SOLVED! I register to stockoverflow just to share to you the only solution (at least in ASP.NET/IE/FF/Chrome) that works! The idea is to replace innerHTML value of a div by its current innerHTML value.

Here is the HTML snippet:

<div class="content-2" id="divGranite">
<h2>Granite Purchase</h2>
<IFRAME  runat="server" id="frameGranite" src="Jobs-granite.aspx" width="820px" height="300px" frameborder="0" seamless  ></IFRAME>

And my Javascript code:

function refreshGranite() {           
   var iframe = document.getElementById('divGranite')
   iframe.innerHTML = iframe.innerHTML;

Hope this helps.

How to make two plots side-by-side using Python?

Check this page out:

plt.subplots is similar. I think it's better since it's easier to set parameters of the figure. The first two arguments define the layout (in your case 1 row, 2 columns), and other parameters change features such as figure size:

import numpy as np
import matplotlib.pyplot as plt

x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 2.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(5, 3))
axes[0].plot(x1, y1)
axes[1].plot(x2, y2)

enter image description here

How to subtract date/time in JavaScript?

Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:

subtractDates: function(date1, date2) {
    return moment.subtract(date1, date2).milliseconds();
millisecondsSince: function(dateSince) {
    return moment().subtract(dateSince).milliseconds();

Date constructor returns NaN in IE, but works in Firefox and Chrome

I always store my date in UTC time.

This is my own function made from the different functions I found in this page.

It takes a STRING as a mysql DATETIME format (example : 2013-06-15 15:21:41). The checking with the regex is optional. You can delete this part to improve performance.

This function return a timestamp.

The DATETIME is considered as a UTC date. Be carefull : If you expect a local datetime, this function is not for you.

    function datetimeToTimestamp(datetime)
        var regDatetime = /^[0-9]{4}-(?:[0]?[0-9]{1}|10|11|12)-(?:[012]?[0-9]{1}|30|31)(?: (?:[01]?[0-9]{1}|20|21|22|23)(?::[0-5]?[0-9]{1})?(?::[0-5]?[0-9]{1})?)?$/;
        if(regDatetime.test(datetime) === false)
            throw("Wrong format for the param. `Y-m-d H:i:s` expected.");

        var a=datetime.split(" ");
        var d=a[0].split("-");
        var t=a[1].split(":");

        var date = new Date();
        date.setUTCHours(t[0],t[1],t[2], 0);

        return date.getTime();

Get max and min value from array in JavaScript

use this and it works on both the static arrays and dynamically generated arrays.

var array = [12,2,23,324,23,123,4,23,132,23];
var getMaxValue = Math.max.apply(Math, array );

I had the issue when I use trying to find max value from code below

$('#myTabs').find('').prevAll().andSelf().each(function () {

        for (var i = 0; i < newGetWidthOfEachTab.length; i++) {
            newWidthOfEachTabTotal += newGetWidthOfEachTab[i];

        getMaxValue = Math.max.apply(Math, array);

I was getting 'NAN' when I use

    var max_value = Math.max(12, 21, 23, 2323, 23);

with my code

SonarQube not picking up Unit Test Coverage

Based on, the following POM works for me:

  • Setting the destination file to the report path ensures that Sonar reads exactly the file JaCoCo generates.
  • The report path should be outside the projects' directories to take cross-project coverage into account (e.g. in case of Tycho where the convention is to have separate projects for tests).
  • The reuseReports setting prevents the deletion of the JaCoCo report file before it is read! (Since 4.3, this is the default and is deprecated.)

Then I just run

mvn clean install
mvn sonar:sonar

Allow docker container to connect to a local/host postgres database

Docker for Mac solution

17.06 onwards

Thanks to @Birchlabs' comment, now it is tons easier with this special Mac-only DNS name available:

docker run -e DB_PORT=5432 -e

From 17.12.0-cd-mac46, should be used instead of docker.for.mac.localhost. See release note for details.

Older version

@helmbert's answer well explains the issue. But Docker for Mac does not expose the bridge network, so I had to do this trick to workaround the limitation:

$ sudo ifconfig lo0 alias

Open /usr/local/var/postgres/pg_hba.conf and add this line:

host    all             all               trust

Open /usr/local/var/postgres/postgresql.conf and edit change listen_addresses:

listen_addresses = '*'

Reload service and launch your container:

$ PGDATA=/usr/local/var/postgres pg_ctl reload
$ docker run -e DB_PORT=5432 -e DB_HOST= my_app 

What this workaround does is basically same with @helmbert's answer, but uses an IP address that is attached to lo0 instead of docker0 network interface.

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

How can I get input radio elements to horizontally align?

This also works like a charm

    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
} else {
    System.out.println("Login canceled");

CSS Background image not loading

I found the problem was you can't use short URL for image "img/image.jpg"

you should use the full URL "", yet I don't know why !!

Use YAML with variables

This is how I was able to configure yaml files to refer to variable.

I have values.yaml where we have root level fields which are used as template variables inside values.yaml


databaseUserPropName: spring.datasource.username  
databaseUserName: sa  
    type: Opaque  
    name: dbservice-secrets  
      - name: "{{ .Values.databaseUserPropName }}"  
        value: "{{ .Values.databaseUserName }}"  

When referencing these values in secret.yaml, we would use tpl function using syntax {{ tpl TEMPLATE_STRING VALUES }}


when using inside range i:e iteration

  {{ range }}
    {{ tpl .name $ }}: "{{ tpl .value $ }}"
  {{ end }}

when directly referring as variable

  {{ tpl . }}
  {{ tpl . }}

$ - this is global variable and will always point to the root context . - this variable will point to the root context based on where it used.

High-precision clock in Python

On the same win10 OS system using "two distinct method approaches" there appears to be an approximate "500 ns" time difference. If you care about nanosecond precision check my code below.

The modifications of the code is based on code from user cod3monk3y and Kevin S.

OS: python 3.7.3 (default, date, time) [MSC v.1915 64 bit (AMD64)]

def measure1(mean):
    for i in range(1, my_range+1):
        x = time.time()
        td = x- samples1[i-1][2]
        if i-1 == 0:
            td = 0
        td = f'{td:.6f}'
        samples1.append((i, td, x))
        mean += float(td)
        print (mean)
    mean = mean/my_range
    return mean

def measure2(nr):
    t0 = time.time()
    t1 = t0
    while t1 == t0:
        t1 = time.time()
    td = t1-t0
    td = f'{td:.6f}'
    return (nr, td, t1, t0)

samples1 = [(0, 0, 0)]
my_range = 10
mean1    = 0.0
mean2    = 0.0

mean1 = measure1(mean1)

for i in samples1: print (i)

print ('...\n\n')

samples2 = [measure2(i) for i in range(11)]

for s in samples2:
    #print(f'time delta: {s:.4f} seconds')
    mean2 += float(s[1])
    print (s)
mean2 = mean2/my_range

print ('\nMean1 : ' f'{mean1:.6f}')
print ('Mean2 : ' f'{mean2:.6f}')

The measure1 results:

nr, td, t0
(0, 0, 0)
(1, '0.000000', 1562929696.617988)
(2, '0.002000', 1562929696.6199884)
(3, '0.001001', 1562929696.620989)
(4, '0.001001', 1562929696.62199)
(5, '0.001001', 1562929696.6229906)
(6, '0.001001', 1562929696.6239917)
(7, '0.001001', 1562929696.6249924)
(8, '0.001000', 1562929696.6259928)
(9, '0.001001', 1562929696.6269937)
(10, '0.001001', 1562929696.6279945)

The measure2 results:

nr, td , t1, t0
(0, '0.000500', 1562929696.6294951, 1562929696.6289947)
(1, '0.000501', 1562929696.6299958, 1562929696.6294951)
(2, '0.000500', 1562929696.6304958, 1562929696.6299958)
(3, '0.000500', 1562929696.6309962, 1562929696.6304958)
(4, '0.000500', 1562929696.6314962, 1562929696.6309962)
(5, '0.000500', 1562929696.6319966, 1562929696.6314962)
(6, '0.000500', 1562929696.632497, 1562929696.6319966)
(7, '0.000500', 1562929696.6329975, 1562929696.632497)
(8, '0.000500', 1562929696.633498, 1562929696.6329975)
(9, '0.000500', 1562929696.6339984, 1562929696.633498)
(10, '0.000500', 1562929696.6344984, 1562929696.6339984)

End result:

Mean1 : 0.001001 # (measure1 function)

Mean2 : 0.000550 # (measure2 function)

Handling exceptions from Java ExecutorService tasks

If your ExecutorService comes from an external source (i. e. it's not possible to subclass ThreadPoolExecutor and override afterExecute()), you can use a dynamic proxy to achieve the desired behavior:

public static ExecutorService errorAware(final ExecutorService executor) {
    return (ExecutorService) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
            new Class[] {ExecutorService.class},
            (proxy, method, args) -> {
                if (method.getName().equals("submit")) {
                    final Object arg0 = args[0];
                    if (arg0 instanceof Runnable) {
                        args[0] = new Runnable() {
                            public void run() {
                                final Runnable task = (Runnable) arg0;
                                try {
                                    if (task instanceof Future<?>) {
                                        final Future<?> future = (Future<?>) task;

                                        if (future.isDone()) {
                                            try {
                                            } catch (final CancellationException ce) {
                                                // Your error-handling code here
                                            } catch (final ExecutionException ee) {
                                                // Your error-handling code here
                                            } catch (final InterruptedException ie) {
                                } catch (final RuntimeException re) {
                                    // Your error-handling code here
                                    throw re;
                                } catch (final Error e) {
                                    // Your error-handling code here
                                    throw e;
                    } else if (arg0 instanceof Callable<?>) {
                        args[0] = new Callable<Object>() {
                            public Object call() throws Exception {
                                final Callable<?> task = (Callable<?>) arg0;
                                try {
                                } catch (final Exception e) {
                                    // Your error-handling code here
                                    throw e;
                                } catch (final Error e) {
                                    // Your error-handling code here
                                    throw e;
                return method.invoke(executor, args);

Get hostname of current request in node.js Express

First of all, before providing an answer I would like to be upfront about the fact that by trusting headers you are opening the door to security vulnerabilities such as phishing. So for redirection purposes, don't use values from headers without first validating the URL is authorized.

Then, your operating system hostname might not necessarily match the DNS one. In fact, one IP might have more than one DNS name. So for HTTP purposes there is no guarantee that the hostname assigned to your machine in your operating system configuration is useable.

The best choice I can think of is to obtain your HTTP listener public IP and resolve its name via DNS. See the dns.reverse method for more info. But then, again, note that an IP might have multiple names associated with it.

How to delete node from XML file using C#

It may be easier to use XPath to locate the nodes that you wish to delete. This stackoverflow thread might give you some ideas.

In your case you will find the four nodes that you want using this expression:

XmlDocument doc = new XmlDocument();
XmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Have the certificate and bundle copied in one .crt file and make sure that there is a blank line between the certificates in the file.

This worked for me on a GitLab server after trying everything on the Internet.

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
        <c:forEach items="${map}" var="entry">



passing argument to DialogFragment

I used to send some values from my listview

How to send

mListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            Favorite clickedObj = (Favorite) parent.getItemAtPosition(position);

            Bundle args = new Bundle();
            args.putString("tar_name", clickedObj.getNameTarife());
            args.putString("fav_name", clickedObj.getName());

            FragmentManager fragmentManager = getSupportFragmentManager();
            TarifeDetayPopup userPopUp = new TarifeDetayPopup();
  , "sam");

            return false;

How to receive inside onCreate() method of DialogFragment

    Bundle mArgs = getArguments();
    String nameTrife = mArgs.getString("tar_name");
    String nameFav = mArgs.getString("fav_name");
    String name = "";

// Kotlin upload

 val fm = supportFragmentManager
        val dialogFragment = AddProgFargmentDialog() // my custom FargmentDialog
        var args: Bundle? = null
        args?.putString("title", model.title);
        dialogFragment.setArguments(args), "Sample Fragment")

// receive

 override fun onCreate(savedInstanceState: Bundle?) {
        if (getArguments() != null) {
            val mArgs = arguments
            var myDay= mArgs.getString("title")

Globally catch exceptions in a WPF application?

Like "VB's On Error Resume Next?" That sounds kind of scary. First recommendation is don't do it. Second recommendation is don't do it and don't think about it. You need to isolate your faults better. As to how to approach this problem, it depends on how you're code is structured. If you are using a pattern like MVC or the like then this shouldn't be too difficult and would definitely not require a global exception swallower. Secondly, look for a good logging library like log4net or use tracing. We'd need to know more details like what kinds of exceptions you're talking about and what parts of your application may result in exceptions being thrown.

Simulate a button click in Jest

You may use something like this to call the handler written on click:

import { shallow } from 'enzyme'; // Mount is not required

page = <MyCoolPage />;
pageMounted = shallow(page);

// The below line will execute your click function

Override and reset CSS style: auto or none don't work

Set min-width: inherit /* Reset the min-width */

Try this. It will work.

Laravel Rule Validation for Numbers


Try this it will be work

What is the most efficient way to store tags in a database?

Items should have an "ID" field, and Tags should have an "ID" field (Primary Key, Clustered).

Then make an intermediate table of ItemID/TagID and put the "Perfect Index" on there.

How do I access refs of a child component in the parent component

Recommended for React versions prior to 16.3

If it cannot be avoided the suggested pattern extracted from the React docs would be:

import React, { Component } from 'react';

const Child = ({ setRef }) => <input type="text" ref={setRef} />;

class Parent extends Component {
    constructor(props) {
        this.setRef = this.setRef.bind(this);

    componentDidMount() {
        // Calling a function on the Child DOM element

    setRef(input) {
        this.childRef = input;

    render() {
        return <Child setRef={this.setRef} />

The Parent forwards a function as prop bound to Parent's this. When React calls the Child's ref prop setRef it will assign the Child's ref to the Parent's childRef property.

Recommended for React >= 16.3

Ref forwarding is an opt-in feature that lets some components take a ref they receive, and pass it further down (in other words, “forward” it) to a child.

We create Components that forward their ref with React.forwardRef. The returned Component ref prop must be of the same type as the return type of React.createRef. Whenever React mounts the DOM node then property current of the ref created with React.createRef will point to the underlying DOM node.

import React from "react";

const LibraryButton = React.forwardRef((props, ref) => (
  <button ref={ref} {...props}>

class AutoFocus extends React.Component {
  constructor(props) {
    this.childRef = React.createRef();
    this.onClick = this.onClick.bind(this);

  componentDidMount() {

  onClick() {

  render() {
    return <LibraryButton onClick={this.onClick} ref={this.childRef} />;

Forwarding refs HOC example

Created Components are forwarding their ref to a child node.

function logProps(Component) {
  class LogProps extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('old props:', prevProps);
      console.log('new props:', this.props);

    render() {
      const {forwardedRef,} = this.props;

      // Assign the custom prop "forwardedRef" as a ref
      return <Component ref={forwardedRef} {} />;

  // Note the second param "ref" provided by React.forwardRef.
  // We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
  // And it can then be attached to the Component.
  return React.forwardRef((props, ref) => {
    return <LogProps {...props} forwardedRef={ref} />;

See Forwarding Refs in React docs.

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

None of these answers worked for me. I had to create my own function called alphanum which stripped the chars for me:

  DECLARE ret CHAR(255) DEFAULT ''; 
    SET len = CHAR_LENGTH( str ); 
        SET c = MID( str, i, 1 ); 
        IF c REGEXP '[[:alnum:]]' THEN 
          SET ret=CONCAT(ret,c); 
        END IF; 
        SET i = i + 1; 
    UNTIL i > len END REPEAT; 
    SET ret='';
  RETURN ret; 
END | 

Now I can do:

select 'This works finally!', alphanum('This works finally!');

and I get:

| This works finally! | alphanum('This works finally!') |
| This works finally! | Thisworksfinally                |
1 row in set (0.00 sec)


Python Pandas User Warning: Sorting because non-concatenation axis is not aligned


concat and append currently sort the non-concatenation index (e.g. columns if you're adding rows) if the columns don't match. In pandas 0.23 this started generating a warning; pass the parameter sort=True to silence it. In the future the default will change to not sort, so it's best to specify either sort=True or False now, or better yet ensure that your non-concatenation indices match.

The warning is new in pandas 0.23.0:

In a future version of pandas pandas.concat() and DataFrame.append() will no longer sort the non-concatenation axis when it is not already aligned. The current behavior is the same as the previous (sorting), but now a warning is issued when sort is not specified and the non-concatenation axis is not aligned, link.

More information from linked very old github issue, comment by smcinerney :

When concat'ing DataFrames, the column names get alphanumerically sorted if there are any differences between them. If they're identical across DataFrames, they don't get sorted.

This sort is undocumented and unwanted. Certainly the default behavior should be no-sort.

After some time the parameter sort was implemented in pandas.concat and DataFrame.append:

sort : boolean, default None

Sort non-concatenation axis if it is not already aligned when join is 'outer'. The current default of sorting is deprecated and will change to not-sorting in a future version of pandas.

Explicitly pass sort=True to silence the warning and sort. Explicitly pass sort=False to silence the warning and not sort.

This has no effect when join='inner', which already preserves the order of the non-concatenation axis.

So if both DataFrames have the same columns in the same order, there is no warning and no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['a', 'b'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['b', 'a'])

print (pd.concat([df1, df2]))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

But if the DataFrames have different columns, or the same columns in a different order, pandas returns a warning if no parameter sort is explicitly set (sort=None is the default value):

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8]}, columns=['b', 'a'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3]}, columns=['a', 'b'])

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=True))
   a  b
0  1  0
1  2  8
0  4  7
1  5  3

print (pd.concat([df1, df2], sort=False))
   b  a
0  0  1
1  8  2
0  7  4
1  3  5

If the DataFrames have different columns, but the first columns are aligned - they will be correctly assigned to each other (columns a and b from df1 with a and b from df2 in the example below) because they exist in both. For other columns that exist in one but not both DataFrames, missing values are created.

Lastly, if you pass sort=True, columns are sorted alphanumerically. If sort=False and the second DafaFrame has columns that are not in the first, they are appended to the end with no sorting:

df1 = pd.DataFrame({"a": [1, 2], "b": [0, 8], 'e':[5, 0]}, 
                    columns=['b', 'a','e'])
df2 = pd.DataFrame({"a": [4, 5], "b": [7, 3], 'c':[2, 8], 'd':[7, 0]}, 

print (pd.concat([df1, df2]))

FutureWarning: Sorting because non-concatenation axis is not aligned.

   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=True))
   a  b    c    d    e
0  1  0  NaN  NaN  5.0
1  2  8  NaN  NaN  0.0
0  4  7  2.0  7.0  NaN
1  5  3  8.0  0.0  NaN

print (pd.concat([df1, df2], sort=False))

   b  a    e    c    d
0  0  1  5.0  NaN  NaN
1  8  2  0.0  NaN  NaN
0  7  4  NaN  2.0  7.0
1  3  5  NaN  8.0  0.0

In your code:

placement_by_video_summary = placement_by_video_summary.drop(placement_by_video_summary_new.index)
                                                       .append(placement_by_video_summary_new, sort=True)

In CSS what is the difference between "." and "#" when declaring a set of styles?

A couple of quick extensions on what has already been said...

An id must be unique, but you can use the same id to make different styles more specific.

For example, given this HTML extract:

<div id="sidebar">
    <ul class="menu">
<div id="content">
<div id="footer">
    <ul class="menu">

You could apply different styles with these:

#sidebar h2
{ ... }

#sidebar .menu
{ ... }

#content h2
{ ... }

#footer .menu
{ ... }

Another useful thing to know: you can have multiple classes on an element, by space-delimiting them...

<ul class="main menu">...</ul>
<ul class="other menu">...</ul>

Which allows you to have common styling in .menu with specific styles using and

{ ... }
{ ... }
{ ... }

Force youtube embed to start in 720p

(This answer was updated, as the previous method using vq isn't recognized anymore.)

Specifying the height of the video will change the quality accordingly. example for html 5;

<iframe style='width:100%; height:800px;' src=''></iframe>

If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.

Tested on a working server + passes the nuhtml validator.

Git will not init/sync/update new submodules

I had the same problem but none of the solutions above helped. The entries in the .gitmodules and in .git/config were right but the command git submodules update --init --recursive was doing nothing. I also removed the submodule directory and did run git submodules update --init --recursive and got the submodule directory back but with exactly the same commit as before.

I found the answer on this page. The command is:git submodule update --remote

How to affect other elements when one element is hovered

If the cube is directly inside the container:

#container:hover > #cube { background-color: yellow; }

If cube is next to (after containers closing tag) the container:

#container:hover + #cube { background-color: yellow; }

If the cube is somewhere inside the container:

#container:hover #cube { background-color: yellow; }

If the cube is a sibling of the container:

#container:hover ~ #cube { background-color: yellow; }

JavaScript: Is there a way to get Chrome to break on all errors?

I got trouble to get it so I post pictures showing different options:

Chrome 75.0.3770.142 [29 July 2018]

Very very similar UI since at least Chrome 38.0.2125.111 [11 December 2014]

In tab Sources :

enter image description here

When button is activated, you can Pause On Caught Exceptions with the checkbox below: enter image description here

Previous versions

Chrome 32.0.1700.102 [03 feb 2014]

enter image description here

enter image description here enter image description here enter image description here

Chrome 27.0.1453.93 Stable

Debug options

Save byte array to file

You can use:

File.WriteAllBytes("Foo.txt", arrBytes); // Requires System.IO

If you have an enumerable and not an array, you can use:

File.WriteAllBytes("Foo.txt", arrBytes.ToArray()); // Requires System.Linq

Getting the docstring from a function

You can also use inspect.getdoc. It cleans up the __doc__ by normalizing tabs to spaces and left shifting the doc body to remove common leading spaces.

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can create table variable instead of tamp table in procedure A and execute procedure B and insert into temp table by below query.


and you continue operation.

Secondary axis with twinx(): how to add to legend?

You can easily add a second legend by adding the line:


You'll get this:

enter image description here

But if you want all labels on one legend then you should do something like this:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10

fig = plt.figure()
ax = fig.add_subplot(111)

lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')

# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)

ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)

Which will give you this:

enter image description here

How to round an average to 2 decimal places in PostgreSQL?

Try casting your column to a numeric like:

SELECT ROUND(cast(some_column as numeric),2) FROM table

'Invalid update: invalid number of rows in section 0

Here is some code from above added with actual action code (point 1 and 2);

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let deleteAction = UIContextualAction(style: .destructive, title: "Delete") { _, _, completionHandler in

        // 1. remove object from your array
        scannedItems.remove(at: indexPath.row)
        // 2. reload the table, otherwise you get an index out of bounds crash

    deleteAction.backgroundColor = .systemOrange
    let configuration = UISwipeActionsConfiguration(actions: [deleteAction])
    configuration.performsFirstActionWithFullSwipe = true
    return configuration

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

The count method of NSArray returns an NSUInteger, and on the 64-bit OS X platform

  • NSUInteger is defined as unsigned long, and
  • unsigned long is a 64-bit unsigned integer.
  • int is a 32-bit integer.

So int is a "smaller" datatype than NSUInteger, therefore the compiler warning.

See also NSUInteger in the "Foundation Data Types Reference":

When building 32-bit applications, NSUInteger is a 32-bit unsigned integer. A 64-bit application treats NSUInteger as a 64-bit unsigned integer.

To fix that compiler warning, you can either declare the local count variable as

NSUInteger count;

or (if you are sure that your array will never contain more than 2^31-1 elements!), add an explicit cast:

int count = (int)[myColors count];

How do I set the colour of a label (coloured text) in Java?

One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)

title.text=<html>Text color: <font color='red'>red</font></html>

title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>

title.text=<html>???? ??????: <font color='red'>???????</font></html>

What's the difference between SHA and AES encryption?

SHA isn't encryption, it's a one-way hash function. AES (Advanced_Encryption_Standard) is a symmetric encryption standard.

AES Reference

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources

CodeIgniter 500 Internal Server Error

This works fine for me

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >

combining two string variables

IMO, froadie's simple concatenation is fine for a simple case like you presented. If you want to put together several strings, the string join method seems to be preferred:

the_text = ''.join(['the ', 'quick ', 'brown ', 'fox ', 'jumped ', 'over ', 'the ', 'lazy ', 'dog.'])

Edit: Note that join wants an iterable (e.g. a list) as its single argument.

jQuery getTime function

It's plain javascript:

new Date()

Using comma as list separator with AngularJS

.list-comma::before {_x000D_
  content: ',';_x000D_
.list-comma:first-child::before {_x000D_
  content: '';_x000D_
<span class="list-comma" ng-repeat="destination in destinations">_x000D_

Why Would I Ever Need to Use C# Nested Classes

Maybe this is a good example of when to use nested classes?

class ImageCacheSettings { }
class ImageCacheEntry { }
class ImageCache
    ImageCacheSettings mSettings;
    List<ImageCacheEntry> mEntries;


class ImageCache
    Settings mSettings;
    List<Entry> mEntries;

    class Settings {}
    class Entry {}

PS: I've not taken into account which access modifiers should be applied (private, protected, public, internal)

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

Can a Byte[] Array be written to a file in C#?

You can use a BinaryWriter object.

protected bool SaveData(string FileName, byte[] Data)
    BinaryWriter Writer = null;
    string Name = @"C:\temp\";

        // Create a new stream to write to the file
        Writer = new BinaryWriter(File.OpenWrite(Name));

        // Writer raw data                
        return false;

    return true;

Edit: Oops, forgot the finally part... lets say it is left as an exercise for the reader ;-)

Difference between string and StringBuilder in C#

System.String is a mutable object, meaning it cannot be modified after it’s been created. Please refer to Difference between string and StringBuilder in C#? for better understanding.

How to enable authentication on MongoDB through Docker?

I want to comment but don't have enough reputation.

The user-adding executable script shown above has to be modified with --authenticationDatabase admin and NEWDATABASENAME.

mongo --authenticationDatabase admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED NEWDATABASENAME --eval "db.createUser({user: 'NEWUSERNAME', pwd: 'PASSWORD', roles: [{role: 'readWrite', db: 'NEWDATABASENAME'}]});"

popup form using html/javascript/css

But the problem with this code is that, I cannot change the content popup content from "Please enter your name" to my html form.

Umm. Just change the string passed to the prompt() function.

While searching, I found that there we CANNOT change the content of popup Prompt Box

You can't change the title. You can change the content, it is the first argument passed to the prompt() function.

Pandas/Python: Set value of one column based on value in another column

Note the tilda that reverses the selection. It uses pandas methods (i.e. is faster than if/else).

df.loc[(df['c1'] == 'Value'), 'c2'] = 10
df.loc[~(df['c1'] == 'Value'), 'c2'] = df['c3']

Factorial using Recursion in Java

Using Java 8 and above, using recursion itself

  UnaryOperator<Long> fact = num -> num<1 ? 1 : num * this.fact.apply(num-1);

And use it like

  fact.apply(5); // prints 120

Internally it calculate like


How to use a SQL SELECT statement with Access VBA

Access 2007 can lose the CurrentDb: see, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

How to list files in a directory in a C program?

An example, available for POSIX compliant systems :

 * This program displays the names of all files in the current directory.

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);

Beware that such an operation is platform dependant in C.

Source :

html select scroll bar

One options will be to show the selected option above (or below) the select list like following:


<div id="selText"><span>&nbsp;</span></div><br/>
<select size="4" id="mySelect" style="width:65px;color:#f98ad3;">
    <option value="1" selected>option 1 The Long Option</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
    <option value="5">option 5 Another Longer than the Long Option ;)</option>
    <option value="6">option 6</option>


<script src=""   
<script type="text/javascript">
       var txt = $($(this).children("option:selected")[0]).text();
       $("<span>" + txt + "<br/></span>").appendTo($("#selText span:last"));

PS:- Set height of div#selText otherwise it will keep shifting select list downward.

Getting all request parameters in Symfony 2

You can do $this->getRequest()->query->all(); to get all GET params and $this->getRequest()->request->all(); to get all POST params.

So in your case:

$params = $this->getRequest()->request->all();

For more info about the Request class, see

How to check permissions of a specific directory?

In GNU/Linux, try to use ls, namei, getfacl, stat.

For Dir

[flying@lempstacker ~]$ ls -ldh /tmp
drwxrwxrwt. 23 root root 4.0K Nov  8 15:41 /tmp
[flying@lempstacker ~]$ namei -l /tmp
f: /tmp
dr-xr-xr-x root root /
drwxrwxrwt root root tmp
[flying@lempstacker ~]$ getfacl /tmp
getfacl: Removing leading '/' from absolute path names
# file: tmp
# owner: root
# group: root
# flags: --t

[flying@lempstacker ~]$ 


[flying@lempstacker ~]$ stat -c "%a" /tmp
[flying@lempstacker ~]$ stat -c "%n %a" /tmp
/tmp 1777
[flying@lempstacker ~]$ stat -c "%A" /tmp
[flying@lempstacker ~]$ stat -c "%n %A" /tmp
/tmp drwxrwxrwt
[flying@lempstacker ~]$

For file

[flying@lempstacker ~]$ ls -lh /tmp/anaconda.log
-rw-r--r-- 1 root root 0 Nov  8 08:31 /tmp/anaconda.log
[flying@lempstacker ~]$ namei -l /tmp/anaconda.log
f: /tmp/anaconda.log
dr-xr-xr-x root root /
drwxrwxrwt root root tmp
-rw-r--r-- root root anaconda.log
[flying@lempstacker ~]$ getfacl /tmp/anaconda.log
getfacl: Removing leading '/' from absolute path names
# file: tmp/anaconda.log
# owner: root
# group: root

[flying@lempstacker ~]$


[flying@lempstacker ~]$ stat -c "%a" /tmp/anaconda.log
[flying@lempstacker ~]$ stat -c "%n %a" /tmp/anaconda.log
/tmp/anaconda.log 644
[flying@lempstacker ~]$ stat -c "%A" /tmp/anaconda.log
[flying@lempstacker ~]$ stat -c "%n %A" /tmp/anaconda.log
/tmp/anaconda.log -rw-r--r--
[flying@lempstacker ~]$

Importing packages in Java

For the second class file, add "package Dan;" like the first one, so as to make sure they are in the same package; modify "import Dan.Vik.disp;" to be "import Dan.Vik;"

How to convert an Instant to a date format?

Instant i = Instant.ofEpochSecond(cal.getTime);

Read more here and here

How many bytes does one Unicode character take?

Unicode is a standard which provides a unique number for every character. These unique numbers are called code points (which is just unique code) to all characters existing in the world (some's are still to be added).

For different purposes, you might need to represent this code points in bytes (most programming languages do so), and here's where Character Encoding kicks in.

UTF-8, UTF-16, UTF-32 and so on are all Character Encodings, and Unicode's code points are represented in these encodings, in different ways.

UTF-8 encoding has a variable-width length, and characters, encoded in it, can occupy 1 to 4 bytes inclusive;

UTF-16 has a variable length and characters, encoded in it, can take either 1 or 2 bytes (which is 8 or 16 bits). This represents only part of all Unicode characters called BMP (Basic Multilingual Plane) and it's enough for almost all the cases. Java uses UTF-16 encoding for its strings and characters;

UTF-32 has fixed length and each character takes exactly 4 bytes (32 bits).

Black transparent overlay on image hover with only CSS?

Here's a good way using :after on the image div, instead of the extra overlay div:

<div class="image">
    <img src="" alt="" />

.image {position:relative; border:1px solid black; width:200px; height:200px;}
.image img {max-width:100%; max-height:100%;}
.image:hover:after {content:""; position:absolute; top:0; left:0; bottom:0; right:0; background-color: rgba(0,0,0,0.3);}

"Could not find a version that satisfies the requirement opencv-python"

Use this and it will work:

pip install --upgrade pip
pip install opencv-python

Add Foreign Key relationship between two Databases

The short answer is that SQL Server (as of SQL 2008) does not support cross database foreign keys--as the error message states.

While you cannot have declarative referential integrity (the FK), you can reach the same goal using triggers. It's a bit less reliable, because the logic you write may have bugs, but it will get you there just the same.

See the SQL docs @ Which state:

Triggers are often used for enforcing business rules and data integrity. SQL Server provides declarative referential integrity (DRI) through the table creation statements (ALTER TABLE and CREATE TABLE); however, DRI does not provide cross-database referential integrity. To enforce referential integrity (rules about the relationships between the primary and foreign keys of tables), use primary and foreign key constraints (the PRIMARY KEY and FOREIGN KEY keywords of ALTER TABLE and CREATE TABLE). If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution and prior to the AFTER trigger execution. If the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not executed (fired).

There is also an OK discussion over at SQLTeam -

Check if value exists in enum in TypeScript

TypeScript v3.7.3

export enum YourEnum {
   enum1 = 'enum1',
   enum2 = 'enum2',
   enum3 = 'enum3',

const status = 'enumnumnum';

if (!(status in YourEnum)) {
     throw new UnprocessableEntityResponse('Invalid enum val');

Sorting an array of objects by property values

This could have been achieved through a simple one line valueof() sort function. Run code snippet below to see demo.

var homes = [_x000D_
        "h_id": "3",_x000D_
        "city": "Dallas",_x000D_
        "state": "TX",_x000D_
        "zip": "75201",_x000D_
        "price": "162500"_x000D_
    }, {_x000D_
        "h_id": "4",_x000D_
        "city": "Bevery Hills",_x000D_
        "state": "CA",_x000D_
        "zip": "90210",_x000D_
        "price": "319250"_x000D_
    }, {_x000D_
        "h_id": "5",_x000D_
        "city": "New York",_x000D_
        "state": "NY",_x000D_
        "zip": "00010",_x000D_
        "price": "962500"_x000D_
console.log("To sort descending/highest first, use operator '<'");_x000D_
homes.sort(function(a,b) { return a.price.valueOf() < b.price.valueOf();});_x000D_
console.log("To sort ascending/lowest first, use operator '>'");_x000D_
homes.sort(function(a,b) { return a.price.valueOf() > b.price.valueOf();});_x000D_

What is hashCode used for? Is it unique?

This is from the msdn article here:

"While you will hear people state that hash codes generate a unique value for a given input, the fact is that, while difficult to accomplish, it is technically feasible to find two different data inputs that hash to the same value. However, the true determining factors regarding the effectiveness of a hash algorithm lie in the length of the generated hash code and the complexity of the data being hashed."

So just use a hash algorithm suitable to your data size and it will have unique hashcodes.

Clearing state es6 React

I will add to the above answer that the reset function should also assign state like so:

reset() {
  this.state = initialState;

The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState({}) after the assignment.

How to find length of dictionary values

Let dictionary be :

If you know the key :

else :
val=[len(i) for i in dict.values()]
# for printing length of 1st key value or length of values in keys if all keys have same amount of values.

horizontal line and right way to code it in html, css

it is depends on requirement , but many developers suggestions is to make your code as simple as possible . so, go with simple "hr" tag and CSS code for that.

How to get a list of installed android applications and pick one to run

You can Find the List of installed apps in Android Device by using below code, "packageInfo" Contains Installed Application Information in Device. we can retrive Intent for the application installed from the packageinfo object and by using startactivity(intent), can start application. it is up to you how you organize the UI either Listview or Gridview. so on click event based on position, you can retrive intent object and start activity intent.

final PackageManager pm = getPackageManager();

List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

for (ApplicationInfo packageInfo : packages) 

 if(pm.getLaunchIntentForPackage(packageInfo.packageName)!= null &&   



    System.out.println("Package Name :" + packageInfo.packageName);

    System.out.println("Launch Intent For Package :"   +  

    System.out.println("Application Label :"   + pm.getApplicationLabel(packageInfo));

    System.out.println("Application Label :"   + 

    System.out.println("i : "+i);







Convert xlsx to csv in Linux with command line

As others said, libreoffice can convert xls files to csv. The problem for me was the sheet selection.

This libreoffice Python script does a fine job at converting a single sheet to CSV.

Usage is:

./ File.xls:"Sheet Name" output.csv

The only downside (on my end) is that --headless doesn't seem to work. I have a LO window that shows up for a second and then quits.
That's OK with me, it's the only tool that does the job rapidly.

jquery simple image slideshow tutorial

This is by far the easiest example I have found on the net.

Summaring the example, this is what you need to do a slideshow:


<div id="slideshow">
    <img src="img1.jpg" style="position:absolute;" class="active" />
    <img src="img2.jpg" style="position:absolute;" />
    <img src="img3.jpg" style="position:absolute;" />

Position absolute is used to put an each image over the other.


<style type="text/css">

The image that has the class="active" will appear over the others, the class=active property will change with the following Jquery code.

    function slideSwitch() {
        var $active = $('div#slideshow');
        var $next = $;    



    $(function() {
        setInterval( "slideSwitch()", 5000 );

If you want to go further with slideshows I suggest you to have a look at the link above (to see animated oppacity changes - 2n example) or at other more complex slideshows tutorials.

Easy way to pull latest of all git submodules

If it's the first time you check-out a repo you need to use --init first:

git submodule update --init --recursive

For git 1.8.2 or above, the option --remote was added to support updating to latest tips of remote branches:

git submodule update --recursive --remote

This has the added benefit of respecting any "non default" branches specified in the .gitmodules or .git/config files (if you happen to have any, default is origin/master, in which case some of the other answers here would work as well).

For git 1.7.3 or above you can use (but the below gotchas around what update does still apply):

git submodule update --recursive


git pull --recurse-submodules

if you want to pull your submodules to latest commits instead of the current commit the repo points to.

See git-submodule(1) for details

How to get just the parent directory name of a specific file

In Groovy:

There is no need to create a File instance to parse the string in groovy. It can be done as follows:

String path = "C:/aaa/bbb/ccc/ddd/"
path.split('/')[-2]  // this will return ddd

The split will create the array [C:, aaa, bbb, ccc, ddd,] and index -2 will point to entry before the last one, which in this case is ddd

Java - get the current class name?

Try using this this.getClass().getCanonicalName() or this.getClass().getSimpleName(). If it's an anonymous class, use this.getClass().getSuperclass().getName()

Setting default values for columns in JPA

You can do the following:

private double price = 0.0;

There! You've just used zero as the default value.

Note this will serve you if you're only accessing the database from this application. If other applications also use the database, then you should make this check from the database using Cameron's columnDefinition annotation attribute, or some other way.

iFrame src change event detection?

The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:

Html code:

<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src=""></iframe>


    function resizeIframe(obj) {

plain count up timer in javascript

Check this:

var minutesLabel = document.getElementById("minutes");_x000D_
var secondsLabel = document.getElementById("seconds");_x000D_
var totalSeconds = 0;_x000D_
setInterval(setTime, 1000);_x000D_
function setTime() {_x000D_
  secondsLabel.innerHTML = pad(totalSeconds % 60);_x000D_
  minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));_x000D_
function pad(val) {_x000D_
  var valString = val + "";_x000D_
  if (valString.length < 2) {_x000D_
    return "0" + valString;_x000D_
  } else {_x000D_
    return valString;_x000D_
<label id="minutes">00</label>:<label id="seconds">00</label>

How to pass multiple checkboxes using jQuery ajax post

Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.

var data = { 'venue[]' : []};

$("input:checked").each(function() {

In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)

Check date between two other dates spring data jpa

Maybe you could try

List<Article> findAllByPublicationDate(Date publicationDate);

The detail could be checked in this article:

Adding JPanel to JFrame

Your Test2 class is not a Component, it has a Component which is a difference.

Either you do something like

frame.add(test.getPanel() );

after you introduced a getter for the panel in your class, or you make sure your Test2 class becomes a Component (e.g. by extending a JPanel)

Html.Raw() in ASP.NET MVC Razor view

Html.Raw() returns IHtmlString, not the ordinary string. So, you cannot write them in opposite sides of : operator. Remove that .ToString() calling

@{int count = 0;}
@foreach (var item in Model.Resources)
    @(count <= 3 ? Html.Raw("<div class=\"resource-row\">"): Html.Raw("")) 
    // some code
    @(count <= 3 ? Html.Raw("</div>") : Html.Raw("")) 


By the way, returning IHtmlString is the way MVC recognizes html content and does not encode it. Even if it hasn't caused compiler errors, calling ToString() would destroy meaning of Html.Raw()

Intellij JAVA_HOME variable

In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"

  • Platform Settings > SDKs ( +; )
  • Click the + button to add a new SDK (or rename and load an existing one)
  • Choose the /Contents/Home directory from the appropriate SDK
    (i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)

What does 'wb' mean in this code, using Python?

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

How can I show a combobox in Android?

In android it is called a Spinner you can take a look at the tutorial here.

Hello, Spinner

And this is a very vague question, you should try to be more descriptive of your problem.

Xampp Access Forbidden php

Did you change any thing on the virtual-host before it stop working ?

Add this line to xampp/apache/conf/extra/httpd-vhosts.conf

<VirtualHost localhost:80>
    DocumentRoot "C:/xampp/htdocs"
    ServerAdmin localhost
    <Directory "C:/xampp/htdocs">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted

How to get hostname from IP (Linux)?

Another simple way I found for using in LAN is

ssh [username@ip] uname -n

If you need to login command line will be

sshpass -p "[password]" ssh [username@ip] uname -n

Call asynchronous method in constructor?

Brian Lagunas has shown a solution that I really like. More info his youtube video


Add a TaskExtensions method

  public static class TaskExtensions
    public static async void Await(this Task task, Action completedCallback = null ,Action<Exception> errorCallBack = null )
            await task;
        catch (Exception e)


  public class MyClass

    public MyClass()
       // DoSomething().Await(Completed, HandleError);

    async Task DoSomething()
        await Task.Delay(3000);
        //Some works here
        //throw new Exception("Thrown in task");

    private void Completed()
        //some thing;

    private void HandleError(Exception ex)
        //handle error


Getter and Setter declaration in .NET


string _myProperty { get; set; }

This is called an Auto Property in the .NET world. It's just syntactic sugar for #2.


string _myProperty;

public string myProperty
    get { return _myProperty; }
    set { _myProperty = value; }

This is the usual way to do it, which is required if you need to do any validation or extra code in your property. For example, in WPF if you need to fire a Property Changed Event. If you don't, just use the auto property, it's pretty much standard.


string _myProperty;

public string getMyProperty()
    return this._myProperty;

public string setMyProperty(string value)
    this._myProperty = value;

The this keyword here is redundant. Not needed at all. These are just Methods that get and set as opposed to properties, like the Java way of doing things.

Get the row(s) which have the max value in groups using groupby

You can sort the dataFrame by count and then remove duplicates. I think it's easier:

df.sort_values('count', ascending=False).drop_duplicates(['Sp','Mt'])

Is it possible to set a number to NaN or infinity?

Yes, you can use numpy for that.

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True

How to change content on hover

The CSS content property along with ::after and ::before pseudo-elements have been introduced for this.

.item:hover a{
    content: 'ADD';

JSFiddle Demo

How do I clear only a few specific objects from the workspace?

To clear all data:

click on Misc>Remove all objects.

Your good to go.

To clear the console:

click on edit>Clear console.

No need for any code.

Extract month and year from a zoo::yearmon object

I know the OP is using zoo here, but I found this thread googling for a standard ts solution for the same problem. So I thought I'd add a zoo-free answer for ts as well.

# create an example Date 
date_1 <- as.Date("1990-01-01")
# extract year
as.numeric(format(date_1, "%Y"))
# extract month
as.numeric(format(date_1, "%m"))

mysql count group by having

One way would be to use a nested query:

SELECT count(*)
   SELECT COUNT(Genre) AS count
   FROM movies
   HAVING (count = 4)
) AS x

The inner query gets all the movies that have exactly 4 genres, then outer query counts how many rows the inner query returned.

Getting an odd error, SQL Server query using `WITH` clause

always use with statement like ;WITH then you'll never get this error. The WITH command required a ; between it and any previous command, by always using ;WITH you'll never have to remember to do this.

see WITH common_table_expression (Transact-SQL), from the section Guidelines for Creating and Using Common Table Expressions:

When a CTE is used in a statement that is part of a batch, the statement before it must be followed by a semicolon.

Notice: Undefined variable: _SESSION in "" on line 9



at the beginning of your page before any HTML

You will have something like :

<?php session_start();
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Worth mentioning: you should download the x64 version!

From the main download page ( click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)

how to "execute" make file

As paxdiablo said make -f would execute the makefile, if you directly execute it by typing ./, then you would get syntax error.

Also you can just type make if your file name is makefile/Makefile.

Suppose you have two files named makefile and Makefile in the same directory then makefile is executed if make alone is given. You can even pass arguments to makefile.

Check out more about makefile at this Tutorial : Basic understanding of Makefile

Calculating a 2D Vector's Cross Product

In short: It's a shorthand notation for a mathematical hack.

Long explanation:

You can't do a cross product with vectors in 2D space. The operation is not defined there.

However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.

If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.

That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.

From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

Open the command palette (ctrl+shift+p), type flutter: get packages (should autocomplete); after it resolves open the command palette again and type reload window and execute the command. This should resolve the issue as quickly as possible.

Can't bind to 'routerLink' since it isn't a known property

You need to add RouterMoudle into imports sections of the module containing the Header component

How do I escape special characters in MySQL?

The information provided in this answer can lead to insecure programming practices.

The information provided here depends highly on MySQL configuration, including (but not limited to) the program version, the database client and character-encoding used.


MySQL recognizes the following escape sequences.
\0     An ASCII NUL (0x00) character.
\'     A single quote (“'”) character.
\"     A double quote (“"”) character.
\b     A backspace character.
\n     A newline (linefeed) character.
\r     A carriage return character.
\t     A tab character.
\Z     ASCII 26 (Control-Z). See note following the table.
\\     A backslash (“\”) character.
\%     A “%” character. See note following the table.
\_     A “_” character. See note following the table.

So you need

select * from tablename where fields like "%string \"hi\" %";

Although as Bill Karwin notes below, using double quotes for string delimiters isn't standard SQL, so it's good practice to use single quotes. This simplifies things:

select * from tablename where fields like '%string "hi" %';

What is the relative performance difference of if/else versus switch statement in Java?

A good explanation at the link below:

1 - If grouped
2 - If sequential
3 - Goto Array
4 - Switch Case - Jump Table

Best way to get identity of inserted row?

I'm saying the same thing as the other guys, so everyone's correct, I'm just trying to make it more clear.

@@IDENTITY returns the id of the last thing that was inserted by your client's connection to the database.
Most of the time this works fine, but sometimes a trigger will go and insert a new row that you don't know about, and you'll get the ID from this new row, instead of the one you want

SCOPE_IDENTITY() solves this problem. It returns the id of the last thing that you inserted in the SQL code you sent to the database. If triggers go and create extra rows, they won't cause the wrong value to get returned. Hooray

IDENT_CURRENT returns the last ID that was inserted by anyone. If some other app happens to insert another row at an unforunate time, you'll get the ID of that row instead of your one.

If you want to play it safe, always use SCOPE_IDENTITY(). If you stick with @@IDENTITY and someone decides to add a trigger later on, all your code will break.

PHP Change Array Keys

If you have an array of keys that you want to use then use array_combine

Given $keys = array('a', 'b', 'c', ...) and your array, $list, then do this:

$list = array_combine($keys, array_values($list));

List will now be array('a' => 'blabla 1', ...) etc.

You have to use array_values to extract just the values from the array and not the old, numeric, keys.

That's nice and simple looking but array_values makes an entire copy of the array so you could have space issues. All we're doing here is letting php do the looping for us, not eliminate the loop. I'd be tempted to do something more like:

foreach ($list as $k => $v) {
   unset ($list[$k]);

   $new_key =  *some logic here*

   $list[$new_key] = $v;

I don't think it's all that more efficient than the first code but it provides more control and won't have issues with the length of the arrays.

Download image from the site in .NET/C#

You can use this code

using (WebClient client = new WebClient()) {
                    Stream stream = client.OpenRead(imgUrl);
                    if (stream != null) {
                        Bitmap bitmap = new Bitmap(stream);
                        ImageFormat imageFormat = ImageFormat.Jpeg;
                        if (bitmap.RawFormat.Equals(ImageFormat.Png)) {
                            imageFormat = ImageFormat.Png;
                        else if (bitmap.RawFormat.Equals(ImageFormat.Bmp)) {
                            imageFormat = ImageFormat.Bmp;
                        else if (bitmap.RawFormat.Equals(ImageFormat.Gif)) {
                            imageFormat = ImageFormat.Gif;
                        else if (bitmap.RawFormat.Equals(ImageFormat.Tiff)) {
                            imageFormat = ImageFormat.Tiff;

                        bitmap.Save(fileName, imageFormat);

Project available at: github

How is AngularJS different from jQuery

AngularJS : AngularJS is for developing heavy web applications. AngularJS can use jQuery if it’s present in the web-app when the application is being bootstrapped. If it's not present in the script path, then AngularJS falls back to its own implementation of the subset of jQuery.

JQuery : jQuery is a small, fast, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler. jQuery simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

Read more details here: angularjs-vs-jquery


WHERE clockDate = '08/10/2012') AND userName = 'test')

Has an extra parenthesis. I think it's fine if you remove it:

clockDate = '08/10/2012' AND userName = 'test')

Also, GETDATE() will put the current date in the column, though if you don't want the time you'll have to play a little. I think CONVERT(varchar(8), GETDATE(), 112) would give you just the date (not time) portion.

clockDate = CONVERT(varchar(8), GETDATE(), 112)
AND userName = 'test')

should probably do it.

PS: use a merge statement :)

MVC ajax post to controller action method

try this:

/////// Controller post and get simple text value 
    public string Contact(string message)
        return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";

//// in the view add reference to the Javascript (jQuery) files

@section Scripts{

<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>  

/// then add the Post method as following:

<script type="text/javascript"> 

/// post and get text value
$("#send").on("click", function () {    
$.post('', { message: $('#msg').val() })  

//// empty post('') means post to the default controller, 
///we are not pacifying different action or controller
/// however we can define a url as following:
/// var url = "@(Url.Action("GetDataAction", "GetDataController"))"

         .done(function (response) {
        .error(function () { alert('Error') })
        .success(function () { alert('OK') })
        return false;

Now let's say you want to do it using $.Ajax and JSON:

// Post JSON data  add using System.Net;
    public JsonResult JsonFullName(string fname, string lastname)
        var data = "{ \"fname\" : \"" + fname  + " \" , \"lastname\" : \"" + lastname + "\" }";
//// you have to add the JsonRequestBehavior.AllowGet 
 //// otherwise it will throw an exception on run-time.
        return Json(data, JsonRequestBehavior.AllowGet);  

Then, inside your view: add the event click on a an input of type button, or even a from submit: Just make sure your JSON data is well formatted.

  $("#jsonGetfullname").on("click", function () { 
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "@(Url.Action("JsonFullName", "Home"))",
            data: "{ \"fname\" : \"Mahmoud\" , \"lastname\" : \"Sayed\" }",
            dataType: "json",
            success: function (data) {
                var res = $.parseJSON(data);
                $("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
            error: function (xhr, err) {
                alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
                alert("responseText: " + xhr.responseText);

How do I set the default page of my application in IIS7?

Just go to web.config file and add following

        <clear />
        <add value="Path of your Page" />

calculating the difference in months between two dates

The method returns a list that contains 3 element first is year, second is month and end element is day:

public static List<int> GetDurationInEnglish(DateTime from, DateTime to)
            if (from > to)
                return null;

            var fY = from.Year;
            var fM = from.Month;
            var fD = DateTime.DaysInMonth(fY, fM);

            var tY = to.Year;
            var tM = to.Month;
            var tD = DateTime.DaysInMonth(tY, tM);

            int dY = 0;
            int dM = 0;
            int dD = 0;

            if (fD > tD)

                if (tM <= 0)
                    tM = 12;
                    tD += DateTime.DaysInMonth(tY, tM);
                    tD += DateTime.DaysInMonth(tY, tM);
            dD = tD - fD;

            if (fM > tM)

                tM += 12;
            dM = tM - fM;

            dY = tY - fY;

            return new List<int>() { dY, dM, dD };
        catch (Exception exception)
            //todo: log exception with parameters in db

            return null;

Java 8 lambdas, Function.identity() or t->t

From the JDK source:

static <T> Function<T, T> identity() {
    return t -> t;

So, no, as long as it is syntactically correct.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=

Dont know if this is good to anyone, but search all these dlls:

  • Microsoft.ReportViewer.Common.dll
  • Microsoft.ReportViewer.ProcessingObjectModel.dll
  • Microsoft.ReportViewer.WebForms.dll
  • Microsoft.ReportViewer.WinForms.dll
  • Microsoft.ReportViewer.DataVisualization.dll

You find them in C:\Windows\assembly\GAC_MSIL\..., and then put them in the references of your project.

For each of them say: local copy, and check for 32 or 64 bit solution.

Does List<T> guarantee insertion order?

If you will change the order of operations, you will avoid the strange behavior: First insert the value to the right place in the list, and then delete it from his first position. Make sure you delete it by his index, because if you will delete it by reference, you might delete them both...

Updating address bar with new URL without hash or reloading the page

var newurl = window.location.protocol + "//" + + window.location.pathname + '?foo=bar';

Switch between python 2.7 and python 3.5 on Mac OS X

OSX's Python binary (version 2) is located at /usr/bin/python

if you use which python it will tell you where the python command is being resolved to. Typically, what happens is third parties redefine things in /usr/local/bin (which takes precedence, by default over /usr/bin). To fix, you can either run /usr/bin/python directly to use 2.x or find the errant redefinition (probably in /usr/local/bin or somewhere else in your PATH)

Why does an image captured using camera intent gets rotated on some devices on Android?

Got an answer for this problem without using ExifInterface. We can get the rotation of the camera either front camera or back camera whichever you are using then while creating the Bitmap we can rotate the bitmap using Matrix.postRotate(degree)

public int getRotationDegree() {
    int degree = 0;

    for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(i, info);
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
            degree = info.orientation;

            return degree;

    return degree;

After calculating the rotation you can rotate you bitmap like below:

 Matrix matrix = new Matrix();


 Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

Herare bm should be your bitmap.

If you want to know the rotation of your front camera just change Camera.CameraInfo.CAMERA_FACING_BACK to Camera.CameraInfo.CAMERA_FACING_FRONT above.

I hope this helps.

How to use split?

Look in JavaScript split() Method


"something -- something_else".split(" -- ") 

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

If error comes for ".settings/language.settings.xml" or any such file you don't need to git.

  1. Team -> Commit -> Staged filelist, check if unwanted file exists, -> Right click on each-> remove from index.
  2. From UnStaged filelist, check if unwanted file exists, -> Right click on each-> Ignore.

Now if Staged file list empty, and Unstaged file list all files are marked as Ignored. You can pull. Otherwise, follow other answers.

open link in iframe

<a href="YOUR_URL" target="_YOUR_IFRAME_NAME">LINK NAME</a>