Programs & Examples On #Dbghelp

dbghelp is the short name of the Microsoft Debug Help library.

How to set default values in Rails?

Based on SFEley's answer, here is an updated/fixed one for newer Rails versions:

class SetDefault < ActiveRecord::Migration
  def change
    change_column :table_name, :column_name, :type, default: "Your value"
  end
end

How to save public key from a certificate in .pem format

There are a couple ways to do this.

First, instead of going into openssl command prompt mode, just enter everything on one command line from the Windows prompt:

E:\> openssl x509 -pubkey -noout -in cert.pem  > pubkey.pem

If for some reason, you have to use the openssl command prompt, just enter everything up to the ">". Then OpenSSL will print out the public key info to the screen. You can then copy this and paste it into a file called pubkey.pem.

openssl> x509 -pubkey -noout -in cert.pem

Output will look something like this:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAryQICCl6NZ5gDKrnSztO
3Hy8PEUcuyvg/ikC+VcIo2SFFSf18a3IMYldIugqqqZCs4/4uVW3sbdLs/6PfgdX
7O9D22ZiFWHPYA2k2N744MNiCD1UE+tJyllUhSblK48bn+v1oZHCM0nYQ2NqUkvS
j+hwUU3RiWl7x3D2s9wSdNt7XUtW05a/FXehsPSiJfKvHJJnGOX0BgTvkLnkAOTd
OrUZ/wK69Dzu4IvrN4vs9Nes8vbwPa/ddZEzGR0cQMt0JBkhk9kU/qwqUseP1QRJ
5I1jR4g8aYPL/ke9K35PxZWuDp3U0UPAZ3PjFAh+5T+fc7gzCs9dPzSHloruU+gl
FQIDAQAB
-----END PUBLIC KEY-----

Retrieving the COM class factory for component failed

For IIS 8 I did basically the same thing as Monic. Im running my application as its own app pool on an x64 machine 1.In DCOMCNFG, right click on the My Computer and select properties.

2.Choose the COM Securities tab.

3.In Access Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Allow local access permission. Do the same for iis apppool\myapp

4.In launch and Activation Permissions, click Edit Defaults and add iis apppool\myapp to it and give it Local launch and Local Activation permission. Do the same for iis apppool\myapp.

additionally I had to make the folders outlined under C:\Windows\SysWOW64\config\systemprofile\Desktop and give read \ write permissions to iis apppool\myapp also

How do I check if a list is empty?

You can even try using bool() like this. Although it is less readable surely it's a concise way to perform this.

    a = [1,2,3];
    print bool(a); # it will return True
    a = [];
    print bool(a); # it will return False

I love this way for the checking list is empty or not.

Very handy and useful.

ArrayBuffer to base64 encoded string

For those who like it short, here's an other one using Array.reduce which will not cause stack overflow:

var base64 = btoa(
  new Uint8Array(arrayBuffer)
    .reduce((data, byte) => data + String.fromCharCode(byte), '')
);

Difference between two lists

        List<int> list1 = new List<int>();
        List<int> list2 = new List<int>();
        List<int> listDifference = new List<int>();

        foreach (var item1 in list1)
        {
            foreach (var item2 in list2)
            {
                if (item1 != item2)
                    listDifference.Add(item1);
            }
        }

How can you undo the last git add?

You can use

git reset

to undo the recently added local files

 git reset file_name

to undo the changes for a specific file

SoapUI "failed to load url" error when loading WSDL

In my case the server were the service was installed was configured only for TLS. SSL was not allowed. So you have to update SoapUI vmoptions file by adding

-Dsoapui.https.protocols=TLSv1.2

You can find vmoptions file under SoapUI installation folder:

C:\Program Files (x86)\SmartBear\SoapUI-5.0.0\bin\soapUI-5.0.0.vmoptions

OR change your server setting to allow SSL

Open files in 'rt' and 'wt' modes

The t indicates text mode, meaning that \n characters will be translated to the host OS line endings when writing to a file, and back again when reading. The flag is basically just noise, since text mode is the default.

Other than U, those mode flags come directly from the standard C library's fopen() function, a fact that is documented in the sixth paragraph of the python2 documentation for open().

As far as I know, t is not and has never been part of the C standard, so although many implementations of the C library accept it anyway, there's no guarantee that they all will, and therefore no guarantee that it will work on every build of python. That explains why the python2 docs didn't list it, and why it generally worked anyway. The python3 docs make it official.

Auto insert date and time in form input field?

Another option is:

<script language="JavaScript" type="text/javascript"> 
document.getElementById("my_date:box").value = ( Stamp.getDate()+"/"+(Stamp.getMonth() + 1)+"/"+(Stamp.getYear()) );
</script>

Parse JSON response using jQuery

Try bellow code. This is help your code.

  $("#btnUpdate").on("click", function () {
            //alert("Alert Test");
            var url = 'http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json';
            $.ajax({
                type: "GET",
                url: url,
                data: "{}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (result) {
                    debugger;

                    $.each(result.callback, function (index, value) {
                        alert(index + ': ' + value.Name);
                    });
                },
                failure: function (result) { alert('Fail'); }
            });
        });

I could not access your url. Bellow error is shows

XMLHttpRequest cannot load http://cooktv.sndimg.com/webcook/sandbox/perf/topics.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:19829' is therefore not allowed access. The response had HTTP status code 501.

How can foreign key constraints be temporarily disabled using T-SQL?

Answer marked '905' looks good but does not work.

Following worked for me. Any Primary Key, Unique Key, or Default constraints CAN NOT be disabled. In fact, if 'sp_helpconstraint '' shows 'n/a' in status_enabled - Means it can NOT be enabled/disabled.

-- To generate script to DISABLE

select 'ALTER TABLE ' + object_name(id) + ' NOCHECK CONSTRAINT [' + object_name(constid) + ']'
from sys.sysconstraints 
where status & 0x4813 = 0x813 order by object_name(id)

-- To generate script to ENABLE

select 'ALTER TABLE ' + object_name(id) + ' CHECK CONSTRAINT [' + object_name(constid) + ']'
from sys.sysconstraints 
where status & 0x4813 = 0x813 order by object_name(id)

What does "zend_mm_heap corrupted" mean

I just had this issue as well on a server I own, and the root cause was APC. I commented out the "apc.so" extension in the php.ini file, reloaded Apache, and the sites came right back up.

How to make PyCharm always show line numbers

For version 2.6 and up, the dialog is in the "Preferences" dialog, access using Cmd ',':

PyCharm (far left menu) -> Preferences... -> Editor (bottom left section) -> Appearance -> Show line numbers checkbox

Regular expression to return text between parenthesis

If you want to find all occurences:

>>> re.findall('\(.*?\)',s)
[u"(date='2/xc2/xb2',time='/case/test.png')", u'(eee)']

>>> re.findall('\((.*?)\)',s)
[u"date='2/xc2/xb2',time='/case/test.png'", u'eee']

See last changes in svn

Open you working copy folder in console (terminal) and choose commands below. To see last changes: If you have commited last changes use:

svn diff -rPREV

If you left changes in working copy (that's bad practice) than use:

svn diff

To see log of commits: If you're working in branch:

svn log --stop-on-copy 

If you're working with trunk:

svn log | head

or just

svn log

Create Carriage Return in PHP String?

There is also the PHP 5.0.2 PHP_EOL constant that is cross-platform !

Stackoverflow reference

Errno 13 Permission denied Python

Your user don't have the right permissions to read the file, since you used open() without specifying a mode.

Since you're using Windows, you should read a little more about File and Folder Permissions.

Also, if you want to play with your file permissions, you should right-click it, choose Properties and select Security tab.

Or if you want to be a little more hardcore, you can run your script as admin.

SO Related Questions:

Correct way of using log4net (logger naming)

Disadvantage of second approach is big repository with created loggers. This loggers do the same if root is defined and class loggers are not defined. Standard scenario on production system is using few loggers dedicated to group of class. Sorry for my English.

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

C++, copy set to vector

Just use the constructor for the vector that takes iterators:

std::set<T> s;

//...

std::vector v( s.begin(), s.end() );

Assumes you just want the content of s in v, and there's nothing in v prior to copying the data to it.

Disable dragging an image from an HTML page

You may consider my solution the best. Most of answers are not compatible with old browsers like IE8 since e.preventDefault() wont be supported as well as ondragstart event. To do it cross browser compatible you have to block mousemove event for this image. See example below:

jQuery

$("#my_image").mousemove( function(e) { return false } ); // fix for IE
$("#my_image").attr("draggable", false); // disable dragging from attribute

without jQuery

var my_image = document.getElementById("my_image");
my_image.setAttribute("draggable", false);

if (my_image.addEventListener) {
   my_image.addEventListener("mousemove", function(e) { return false });
} else if (my_image.attachEvent) {
   my_image.attachEvent("onmousemove", function(e) { return false });
}

tested and worked even for IE8

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

I was using old version 1.0.beta.6 of handlebars, i think somewhere during 1.1 - 1.3 this functionality was added, so updating to 1.3.0 solved the issue, here is the usage:

Usage:

{{#each object}}
  Key {{@key}} : Value {{this}}
{{/people}}

Using prepared statements with JDBCTemplate

I'd factor out the prepared statement handling to at least a method. In this case, because there are no results it is fairly simple (and assuming that the connection is an instance variable that doesn't change):

private PreparedStatement updateSales;
public void updateSales(int sales, String cof_name) throws SQLException {
    if (updateSales == null) {
        updateSales = con.prepareStatement(
            "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    }
    updateSales.setInt(1, sales);
    updateSales.setString(2, cof_name);
    updateSales.executeUpdate();
}

At that point, it is then just a matter of calling:

updateSales(75, "Colombian");

Which is pretty simple to integrate with other things, yes? And if you call the method many times, the update will only be constructed once and that will make things much faster. Well, assuming you don't do crazy things like doing each update in its own transaction...

Note that the types are fixed. This is because for any particular query/update, they should be fixed so as to allow the database to do its job efficiently. If you're just pulling arbitrary strings from a CSV file, pass them in as strings. There's also no locking; far better to keep individual connections to being used from a single thread instead.

What is the difference between a definition and a declaration?

There are some very clear definitions sprinkled throughout K&R (2nd edition); it helps to put them in one place and read them as one:

"Definition" refers to the place where the variable is created or assigned storage; "declaration" refers to the places where the nature of the variable is stated but no storage is allocated. [p. 33]

...

It is important to distinguish between the declaration of an external variable and its definition. A declaration announces the properties of a variable (primarily its type); a definition also causes storage to be set aside. If the lines

int sp;
double val[MAXVAL]

appear outside of any function, they define the external variables sp and val, cause storage to be set aside, and also serve as the declaration for the rest of that source file.

On the other hand, the lines

extern int sp;
extern double val[];

declare for the rest of the source file that sp is an int and that val is a double array (whose size is determined elsewhere), but they do not create the variables or reserve storage for them.

There must be only one definition of an external variable among all the files that make up the source program. ... Array sizes must be specified with the definition, but are optional with an extern declaration. [pp. 80-81]

...

Declarations specify the interpretation given to each identifier; they do not necessarily reserve storage associated with the identifier. Declarations that reserve storage are called definitions. [p. 210]

Reloading a ViewController

Update the data ... change button titles..whatever stuff you have to update..

then just call

[self.view setNeedsDisplay];

Get distance between two points in canvas

You can do it with pythagoras theorem

If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.

enter image description here

var a = x1 - x2;
var b = y1 - y2;

var c = Math.sqrt( a*a + b*b );

// c is the distance

Javascript/DOM: How to remove all events of a DOM object?

I am not sure what you mean with remove all events. Remove all handlers for a specific type of event or all event handlers for one type?

Remove all event handlers

If you want to remove all event handlers (of any type), you could clone the element and replace it with its clone:

var clone = element.cloneNode(true);

Note: This will preserve attributes and children, but it will not preserve any changes to DOM properties.


Remove "anonymous" event handlers of specific type

The other way is to use removeEventListener() but I guess you already tried this and it didn't work. Here is the catch:

Calling addEventListener to an anonymous function creates a new listener each time. Calling removeEventListener to an anonymous function has no effect. An anonymous function creates a unique object each time it is called, it is not a reference to an existing object though it may call one. When adding an event listener in this manner be sure it is added only once, it is permanent (cannot be removed) until the object it was added to, is destroyed.

You are essentially passing an anonymous function to addEventListener as eventReturner returns a function.

You have two possibilities to solve this:

  1. Don't use a function that returns a function. Use the function directly:

     function handler() {
         dosomething();
     }
    
     div.addEventListener('click',handler,false);
    
  2. Create a wrapper for addEventListener that stores a reference to the returned function and create some weird removeAllEvents function:

     var _eventHandlers = {}; // somewhere global
    
     const addListener = (node, event, handler, capture = false) => {
       if (!(event in _eventHandlers)) {
         _eventHandlers[event] = []
       }
       // here we track the events and their nodes (note that we cannot
       // use node as Object keys, as they'd get coerced into a string
       _eventHandlers[event].push({ node: node, handler: handler, capture: capture })
       node.addEventListener(event, handler, capture)
     }
    
     const removeAllListeners = (targetNode, event) => {
       // remove listeners from the matching nodes
       _eventHandlers[event]
         .filter(({ node }) => node === targetNode)
         .forEach(({ node, handler, capture }) => node.removeEventListener(event, handler, capture))
    
       // update _eventHandlers global
       _eventHandlers[event] = _eventHandlers[event].filter(
         ({ node }) => node !== targetNode,
       )
     }
    

And then you could use it with:

    addListener(div, 'click', eventReturner(), false)
    // and later
    removeAllListeners(div, 'click')

DEMO

Note: If your code runs for a long time and you are creating and removing a lot of elements, you would have to make sure to remove the elements contained in _eventHandlers when you destroy them.

Authentication versus Authorization

The confusion is understandable, since the two words sound similar, and since the concepts are often closely related and used together. Also, as mentioned, the commonly used abbreviation Auth doesn't help.

Others have already described well what authentication and authorization mean. Here's a simple rule to help keep the two clearly apart:

  • Authentication validates your Identity (or authenticity, if you prefer that)
  • Authorization validates your authority, i.e. your right to access and possibly change something.

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

check if directory exists and delete in one command unix

Try:

bash -c '[ -d my_mystery_dirname ] && run_this_command'

This will work if you can run bash on the remote machine....

In bash, [ -d something ] checks if there is directory called 'something', returning a success code if it exists and is a directory. Chaining commands with && runs the second command only if the first one succeeded. So [ -d somedir ] && command runs the command only if the directory exists.

Java count occurrence of each item in an array

Count String occurence using hashmap, streams & collections

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class StringOccurence {

public static void main(String args[]) {

    String[] stringArray = { "name1", "name1", "name2", "name2", "name2" };
    countStringOccurence(stringArray);
    countStringOccurenceUsingStream(stringArray);
    countStringOccurenceUsingCollections(stringArray);
}

private static void countStringOccurenceUsingCollections(String[] stringArray) {
    // TODO Auto-generated method stub
    List<String> asList = Arrays.asList(stringArray);
    Set<String> set = new HashSet<String>(asList);
    for (String string : set) {
        System.out.println(string + "   -->   " + Collections.frequency(asList, string));
    }

}

private static void countStringOccurenceUsingStream(String[] stringArray) {
    // TODO Auto-generated method stub
    Arrays.stream(stringArray).collect(Collectors.groupingBy(s -> s))
            .forEach((k, v) -> System.out.println(k + "   -->   " + v.size()));
}

private static void countStringOccurence(String[] stringArray) {
    // TODO Auto-generated method stub
    Map<String, Integer> map = new HashMap<String, Integer>();
    for (String s : stringArray) {
        if (map.containsKey(s)) {
            map.put(s, map.get(s) + 1);
        } else {
            map.put(s, 1);
        }
    }

    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "   -->   " + entry.getValue());
    }

}

}

Why is there no String.Empty in Java?

If you really want a String.EMPTY constant, you can create an utility static final class named "Constants" (for example) in your project. This class will maintain your constants, including the empty String...

In the same idea, you can create ZERO, ONE int constants... that don't exist in the Integer class, but like I commented, it would be a pain to write and to read :

for(int i=Constants.ZERO; ...) {
    if(myArray.length > Constants.ONE) {
        System.out.println("More than one element");
    }
}

Etc.

How to change progress bar's progress color in Android

For a horizontal style ProgressBar I use:

import android.widget.ProgressBar;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.ClipDrawable;
import android.view.Gravity;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;

public void setColours(ProgressBar progressBar,
                        int bgCol1, int bgCol2, 
                        int fg1Col1, int fg1Col2, int value1,
                        int fg2Col1, int fg2Col2, int value2)
  {
    //If solid colours are required for an element, then set
    //that elements Col1 param s the same as its Col2 param
    //(eg fg1Col1 == fg1Col2).

    //fgGradDirection and/or bgGradDirection could be parameters
    //if you require other gradient directions eg LEFT_RIGHT.

    GradientDrawable.Orientation fgGradDirection
        = GradientDrawable.Orientation.TOP_BOTTOM;
    GradientDrawable.Orientation bgGradDirection
        = GradientDrawable.Orientation.TOP_BOTTOM;

    //Background
    GradientDrawable bgGradDrawable = new GradientDrawable(
            bgGradDirection, new int[]{bgCol1, bgCol2});
    bgGradDrawable.setShape(GradientDrawable.RECTANGLE);
    bgGradDrawable.setCornerRadius(5);
    ClipDrawable bgclip = new ClipDrawable(
            bgGradDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);     
    bgclip.setLevel(10000);

    //SecondaryProgress
    GradientDrawable fg2GradDrawable = new GradientDrawable(
            fgGradDirection, new int[]{fg2Col1, fg2Col2});
    fg2GradDrawable.setShape(GradientDrawable.RECTANGLE);
    fg2GradDrawable.setCornerRadius(5);
    ClipDrawable fg2clip = new ClipDrawable(
            fg2GradDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);        

    //Progress
    GradientDrawable fg1GradDrawable = new GradientDrawable(
            fgGradDirection, new int[]{fg1Col1, fg1Col2});
    fg1GradDrawable.setShape(GradientDrawable.RECTANGLE);
    fg1GradDrawable.setCornerRadius(5);
    ClipDrawable fg1clip = new ClipDrawable(
            fg1GradDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL);        

    //Setup LayerDrawable and assign to progressBar
    Drawable[] progressDrawables = {bgclip, fg2clip, fg1clip};
    LayerDrawable progressLayerDrawable = new LayerDrawable(progressDrawables);     
    progressLayerDrawable.setId(0, android.R.id.background);
    progressLayerDrawable.setId(1, android.R.id.secondaryProgress);
    progressLayerDrawable.setId(2, android.R.id.progress);

    //Copy the existing ProgressDrawable bounds to the new one.
    Rect bounds = progressBar.getProgressDrawable().getBounds();
    progressBar.setProgressDrawable(progressLayerDrawable);     
    progressBar.getProgressDrawable().setBounds(bounds);

    // setProgress() ignores a change to the same value, so:
    if (value1 == 0)
        progressBar.setProgress(1);
    else
        progressBar.setProgress(0);
    progressBar.setProgress(value1);

    // setSecondaryProgress() ignores a change to the same value, so:
    if (value2 == 0)
        progressBar.setSecondaryProgress(1);
    else
        progressBar.setSecondaryProgress(0);
    progressBar.setSecondaryProgress(value2);

    //now force a redraw
    progressBar.invalidate();
  }

An example call would be:

  setColours(myProgressBar, 
          0xff303030,   //bgCol1  grey 
          0xff909090,   //bgCol2  lighter grey 
          0xff0000FF,   //fg1Col1 blue 
          0xffFFFFFF,   //fg1Col2 white
          50,           //value1
          0xffFF0000,   //fg2Col1 red 
          0xffFFFFFF,   //fg2Col2 white
          75);          //value2

If you don't need the 'secondary progress' simply set value2 to value1.

How to write a full path in a batch file having a folder name with space?

I made a **

automatic-network-drive connector

** using a batch file.

Suddenly there was a networkdrive called "Data for Analysation", and yeah with the double quotes it works proper!

looks a little bit different but works:

net use y: "\\share.blabla.com\Folder\Subfolder\Data for Analysation" /USER:domain\username PW /PERSISTENT:YES

Thx for the Hint :)

Twitter Bootstrap 3: how to use media queries?

Based on the other users' answers, I wrote these custom mixins for easier usage:

Less input

.when-xs(@rules) { @media (max-width: @screen-xs-max) { @rules(); } }
.when-sm(@rules) { @media (min-width: @screen-sm-min) { @rules(); } }
.when-md(@rules) { @media (min-width: @screen-md-min) { @rules(); } }
.when-lg(@rules) { @media (min-width: @screen-lg-min) { @rules(); } }

Example usage

body {
  .when-lg({
    background-color: red;
  });
}

SCSS input

@mixin when-xs() { @media (max-width: $screen-xs-max) { @content; } }
@mixin when-sm() { @media (min-width: $screen-sm-min) { @content; } }
@mixin when-md() { @media (min-width: $screen-md-min) { @content; } }
@mixin when-lg() { @media (min-width: $screen-lg-min) { @content; } }

Example usage:

body {
  @include when-md {
    background-color: red;
  }
}

Output

@media (min-width:1200px) {
  body {
    background-color: red;
  }
}

Generate fixed length Strings filled with whitespaces

Utilize String.format's padding with spaces and replace them with the desired char.

String toPad = "Apple";
String padded = String.format("%8s", toPad).replace(' ', '0');
System.out.println(padded);

Prints 000Apple.


Update more performant version (since it does not rely on String.format), that has no problem with spaces (thx to Rafael Borja for the hint).

int width = 10;
char fill = '0';

String toPad = "New York";
String padded = new String(new char[width - toPad.length()]).replace('\0', fill) + toPad;
System.out.println(padded);

Prints 00New York.

But a check needs to be added to prevent the attempt of creating a char array with negative length.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

How to create a HashMap with two keys (Key-Pair, Value)?

You can download it from the below link: https://github.com/VVS279/DoubleKeyHashMap/blob/master/src/com/virtualMark/doubleKeyHashMap/DoubleKeyHashMap.java

https://github.com/VVS279/DoubleKeyHashMap

You can use double key: value hashmap,

   DoubleKeyHashMap<Integer, Integer, String> doubleKeyHashMap1 = new 
   DoubleKeyHashMap<Integer, Integer, String>();

   DoubleKeyHashMap<String, String, String> doubleKeyHashMap2 = new 
   DoubleKeyHashMap<String, String, String>();

Android: Cancel Async Task

You can just ask for cancellation but not really terminate it. See this answer.

Matlab: Running an m-file from command-line

Here are the steps:

  1. Start the command line.
  2. Enter the folder containing the .m file with cd C:\M1\M2\M3
  3. Run the following: C:\E1\E2\E3\matlab.exe -r mfile

Windows systems will use your current folder as the location for MATLAB to search for .m files, and the -r option tries to start the given .m file as soon as startup occurs.

Check if a PHP cookie exists and if not set its value

Answer

You can't according to the PHP manual:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

This is because cookies are sent in response headers to the browser and the browser must then send them back with the next request. This is why they are only available on the second page load.

Work around

But you can work around it by also setting $_COOKIE when you call setcookie():

if(!isset($_COOKIE['lg'])) {
    setcookie('lg', 'ro');
    $_COOKIE['lg'] = 'ro';
}
echo $_COOKIE['lg'];

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

I was getting the same type of error, and I found that the console is not capable of displaying the string in another language. Hence I made the below code changes to set default_charset as UTF-8.

data_head = [('\x81\xa1\x8fo\x89\xef\x82\xa2\x95\xdb\x8f\xd8\x90\xa7\x93x\x81\xcb3\x8c\x8e\x8cp\x91\xb1\x92\x86(\x81\x86\x81\xde\x81\x85)\x81\xa1\x8f\x89\x89\xf1\x88\xc8\x8aO\x81A\x82\xa8\x8b\xe0\x82\xcc\x90S\x94z\x82\xcd\x88\xea\x90\xd8\x95s\x97v\x81\xa1\x83}\x83b\x83v\x82\xcc\x82\xa8\x8e\x8e\x82\xb5\x95\xdb\x8c\xaf\x82\xc5\x8fo\x89\xef\x82\xa2\x8am\x92\xe8\x81\xa1', 'shift_jis')]
default_charset = 'UTF-8' #can also try 'ascii' or other unicode type
print ''.join([ unicode(lin[0], lin[1] or default_charset) for lin in data_head ])

How do I run a Python program?

if you dont want call filename.py you can add .PY to the PATHEXT, that way you will just call filename

If table exists drop table then create it, if it does not exist just create it

I needed to drop a table and re-create with a data from a view. I was creating a table out of a view and this is what I did:

DROP TABLE <table_name>;
CREATE TABLE <table_name> AS SELECT * FROM <view>;

The above worked for me using MySQL MariaDb.

Time stamp in the C programming language

If you want to find elapsed time, this method will work as long as you don't reboot the computer between the start and end.

In Windows, use GetTickCount(). Here's how:

DWORD dwStart = GetTickCount();
...
... process you want to measure elapsed time for
...
DWORD dwElapsed = GetTickCount() - dwStart;

dwElapsed is now the number of elapsed milliseconds.

In Linux, use clock() and CLOCKS_PER_SEC to do about the same thing.

If you need timestamps that last through reboots or across PCs (which would need quite good syncronization indeed), then use the other methods (gettimeofday()).

Also, in Windows at least you can get much better than standard time resolution. Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed. That's because of the time quantum used by the Windows thread scheduler. This is more or less the amount of time it gives each thread to run before switching to something else. If you do a:

timeBeginPeriod(1);

at the beginning of your program or process and a:

timeEndPeriod(1);

at the end, then the quantum will change to 1 ms, and you will get much better time resolution on the GetTickCount() call. However, this does make a subtle change to how your entire computer runs processes, so keep that in mind. However, Windows Media Player and many other things do this routinely anyway, so I don't worry too much about it.

I'm sure there's probably some way to do the same in Linux (probably with much better control, or maybe with sub-millisecond quantums) but I haven't needed to do that yet in Linux.

Exception is never thrown in body of corresponding try statement

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

Closing Application with Exit button

Below used main.xml file

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/txt1" android:text="txt1" />
<TextView android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/txt2"   android:text="txt2"/>
<Button android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:id="@+id/btn1"
    android:text="Close App" />
  </LinearLayout>

and text.java file is below


import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

public class testprj extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    Button btn1 = (Button) findViewById(R.id.btn1);
    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
            System.exit(0);
        }
    });
    }
 }

Create Excel files from C# without office

Use OleDB, you can create, read, and edit excel files pretty easily. Read the MSDN docs for more info:

http://msdn.microsoft.com/en-us/library/aa288452(VS.71).aspx

I've used OleDB to read from excel files and I know you can create them, but I haven't done it firsthand.

what do <form action="#"> and <form method="post" action="#"> do?

Apparently, action was required prior to HTML5 (and # was just a stand in), but you no longer have to use it.

See The Action Attribute:

When specified with no attributes, as below, the data is sent to the same page that the form is present on:

<form>

How to check task status in Celery?

You can also create custom states and update it's value duting task execution. This example is from docs:

@app.task(bind=True)
def upload_files(self, filenames):
    for i, file in enumerate(filenames):
        if not self.request.called_directly:
            self.update_state(state='PROGRESS',
                meta={'current': i, 'total': len(filenames)})

http://celery.readthedocs.org/en/latest/userguide/tasks.html#custom-states

Where is Java Installed on Mac OS X?

I tried serkan's solution, it found java 7's location on OS X Mavericks. it is resided in "/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/" but to make it the default JDK I had to set JAVA_HOME system variable in .bash_profile in home directory to "/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home/" so its up and running now thanks to serkan's idea

Easy way to make a confirmation dialog in Angular?

I'm pretty late to the party, but here is another implementation using : https://stackblitz.com/edit/angular-confirmation-dialog

confirmation-dialog.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

import { ConfirmationDialogComponent } from './confirmation-dialog.component';

@Injectable()
export class ConfirmationDialogService {

  constructor(private modalService: NgbModal) { }

  public confirm(
    title: string,
    message: string,
    btnOkText: string = 'OK',
    btnCancelText: string = 'Cancel',
    dialogSize: 'sm'|'lg' = 'sm'): Promise<boolean> {
    const modalRef = this.modalService.open(ConfirmationDialogComponent, { size: dialogSize });
    modalRef.componentInstance.title = title;
    modalRef.componentInstance.message = message;
    modalRef.componentInstance.btnOkText = btnOkText;
    modalRef.componentInstance.btnCancelText = btnCancelText;

    return modalRef.result;
  }

}

confirmation-dialog.component.ts

import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-confirmation-dialog',
  templateUrl: './confirmation-dialog.component.html',
  styleUrls: ['./confirmation-dialog.component.scss'],
})
export class ConfirmationDialogComponent implements OnInit {

  @Input() title: string;
  @Input() message: string;
  @Input() btnOkText: string;
  @Input() btnCancelText: string;

  constructor(private activeModal: NgbActiveModal) { }

  ngOnInit() {
  }

  public decline() {
    this.activeModal.close(false);
  }

  public accept() {
    this.activeModal.close(true);
  }

  public dismiss() {
    this.activeModal.dismiss();
  }

}

confirmation-dialog.component.html

<div class="modal-header">
  <h4 class="modal-title">{{ title }}</h4>
    <button type="button" class="close" aria-label="Close" (click)="dismiss()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    {{ message }}
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-danger" (click)="decline()">{{ btnCancelText }}</button>
    <button type="button" class="btn btn-primary" (click)="accept()">{{ btnOkText }}</button>
  </div>

Use the dialog like this:

public openConfirmationDialog() {
    this.confirmationDialogService.confirm('Please confirm..', 'Do you really want to ... ?')
    .then((confirmed) => console.log('User confirmed:', confirmed))
    .catch(() => console.log('User dismissed the dialog (e.g., by using ESC, clicking the cross icon, or clicking outside the dialog)'));
  }

How can I pass a member function where a free function is expected?

@Pete Becker's answer is fine but you can also do it without passing the class instance as an explicit parameter to function1 in C++ 11:

#include <functional>
using namespace std::placeholders;

void function1(std::function<void(int, int)> fun)
{
    fun(1, 1);
}

int main (int argc, const char * argv[])
{
   ...

   aClass a;
   auto fp = std::bind(&aClass::test, a, _1, _2);
   function1(fp);

   return 0;
}

how to create a list of lists

You want to create an empty list, then append the created list to it. This will give you the list of lists. Example:

>>> l = []
>>> l.append([1,2,3])
>>> l.append([4,5,6])
>>> l
[[1, 2, 3], [4, 5, 6]]

cURL error 60: SSL certificate: unable to get local issuer certificate

I had this problem appear out-of-the-blue one day, when a Guzzle(5) script was attempting to connect to a host over SSL. Sure, I could disable the VERIFY option in Guzzle/Curl, but that's clearly not the correct way to go.

I tried everything listed here and in similar threads, then eventually went to terminal with openssl to test against the domain with which I was trying to connect:

openssl s_client -connect example.com:443 

... and received first few lines indicating:

CONNECTED(00000003)
depth=0 CN = example.com
verify error:num=20:unable to get local issuer certificate
verify return:1
depth=0 CN = example.com
verify error:num=21:unable to verify the first certificate
verify return:1 

... while everything worked fine when trying other destinations (ie: google.com, etc)

This prompted me to contact the domain I had been trying to connect to, and indeed, they had a problem on THEIR END that had crept up. It was resolved and my script went back to working.

So... if you're pulling your hair out, give openssl a shot and see if there's anything up with the response from the location you are attempting to connect. Maybe the issue isn't so 'local' after all sometimes.

Spark DataFrame groupBy and sort in the descending order (pyspark)

Use orderBy:

df.orderBy('column_name', ascending=False)

Complete answer:

group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)

http://spark.apache.org/docs/2.0.0/api/python/pyspark.sql.html

How to redirect to another page in node.js

@Nazar Medeiros - Your solution uses passport with Express. I am not using passport, just express-jwt. I might be doing something wrong, but when a user logs in, the token needs to return to the client side. From what I have found so far, this means we have to return a json with the token and therefor cannot call redirect. Is there something I am missing there?

To get around this, I simply return the token, store it in my cookies and then make a ajax GET request (with the valid token). When that ajax call returns I replace the body's html with the returned HTML. This is probably not the right way to do it, but I can't find a better way. Here is my JQuery JavaScript code.

function loginUser(){
  $.post("/users/login", {
    username: $( '#login_input_username' ).val(),
   password: $( '#login_input_password' ).val()
 }).done(function(res){
    document.cookie = "token = " + res.token;
    redirectToHome();
  })
}

function redirectToHome(){
  var settings = {
    "async": true,
    "crossDomain": true,
    "url": "/home",
    "type": "GET",
    "headers": {
      "authorization": "Bearer " + getCookie('token'),
      "cache-control": "no-cache"
    }
  }

  $.ajax(settings).done(function (response) {
    $('body').replaceWith(response);
  });
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

Jenkins could not run git

In case the Jenkins is triggering a build by restricting it to run on a slave or any other server (you may find it in the below setting under 'configure')

enter image description here

then the Path to Git executable should be set as per the 'slave_server_hostname' or any other server where the git commands are executed.

How do I list loaded plugins in Vim?

:set runtimepath?

This lists the path of all plugins loaded when a file is opened with Vim.

Html Agility Pack get all elements by class

You can use the following script:

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);

Does Visual Studio have code coverage for unit tests?

Only Visual Studio 2015 Enterprise has code coverage built-in. See the feature matrix for details.

You can use the OpenCover.UI extension for code coverage check inside Visual Studio. It supports MSTest, nUnit, and xUnit.

The new version can be downloaded from here (release notes).

Show tables, describe tables equivalent in redshift

Shortcut

\d for show all tables

\d tablename to describe table

\? for more shortcuts for redshift

Remove stubborn underline from link

As others pointed out, it seems like you can't override nested text-decoration styles... BUT you can change the text-decoration-color.

As a hack, I changed the color to be transparent:

text-decoration-color: transparent;

Getting the parameters of a running JVM

I am adding this new answer because as per JDK8 documentation jcmd is suggested approach now.

It is suggested to use the latest utility, jcmd instead of the previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance overhead.

Below are commands to get your properties/flags you want.

jcmd pid VM.system_properties
jcmd pid VM.flags

We need pid, for this use jcmd -l, like below

username@users-Air:~/javacode$ jcmd -l 
11441 Test 
6294 Test 
29197 jdk.jcmd/sun.tools.jcmd.JCmd -l 

Now time to use these pids to get properties/flags you want

Command: jcmd 11441 VM.system_properties

11441:
#Tue Oct 17 12:44:50 IST 2017
gopherProxySet=false
awt.toolkit=sun.lwawt.macosx.LWCToolkit
file.encoding.pkg=sun.io
java.specification.version=9
sun.cpu.isalist=
sun.jnu.encoding=UTF-8
java.class.path=.
java.vm.vendor=Oracle Corporation
sun.arch.data.model=64
java.vendor.url=http\://java.oracle.com/
user.timezone=Asia/Kolkata
java.vm.specification.version=9
os.name=Mac OS X
sun.java.launcher=SUN_STANDARD
user.country=US
sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib
sun.java.command=Test
http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
jdk.debug=release
sun.cpu.endian=little
user.home=/Users/XXXX
user.language=en
java.specification.vendor=Oracle Corporation
java.home=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
file.separator=/
java.vm.compressedOopsMode=Zero based
line.separator=\n
java.specification.name=Java Platform API Specification
java.vm.specification.vendor=Oracle Corporation
java.awt.graphicsenv=sun.awt.CGraphicsEnvironment
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
java.runtime.version=9+181
user.name=XXXX
path.separator=\:
os.version=10.12.6
java.runtime.name=Java(TM) SE Runtime Environment
file.encoding=UTF-8
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vendor.url.bug=http\://bugreport.java.com/bugreport/
java.io.tmpdir=/var/folders/dm/gd6lc90d0hg220lzw_m7krr00000gn/T/
java.version=9
user.dir=/Users/XXXX/javacode
os.arch=x86_64
java.vm.specification.name=Java Virtual Machine Specification
java.awt.printerjob=sun.lwawt.macosx.CPrinterJob
sun.os.patch.level=unknown
MyParam=2
java.library.path=/Users/XXXX/Library/Java/Extensions\:/Library/Java/Extensions\:/Network/Library/Java/Extensions\:/System/Library/Java/Extensions\:/usr/lib/java\:.
java.vm.info=mixed mode
java.vendor=Oracle Corporation
java.vm.version=9+181
sun.io.unicode.encoding=UnicodeBig
java.class.version=53.0
socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16

Command : jcmd 11441 VM.flags output:

11441:
-XX:CICompilerCount=3 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=4 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=67108864 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=1073741824 -XX:MaxNewSize=643825664 -XX:MinHeapDeltaBytes=1048576 -XX:NonNMethodCodeHeapSize=5830092 -XX:NonProfiledCodeHeapSize=122914074 -XX:ProfiledCodeHeapSize=122914074 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:-UseAOT -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseG1GC 

For more instructions of usages of jcmd, see my blog post

Fill username and password using selenium in python

user = driver.find_element_by_name("username")
password = driver.find_element_by_name("password")
user.clear()
user.send_keys("your_user_name")
password.clear()
password.send_keys("your_password")
driver.find_element_by_name("submit").click()

Note:

  • we useuser.clear() in order to clear the input field.
  • for locating submit button you can use any other method based on the page source code. for info see locating elements

How can I change the default Django date template format?

If you need to show short date and time (11/08/2018 03:23 a.m.) you can do it like this:

{{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}

Details for this tag here and more about dates according to the given format here

Example:

<small class="text-muted">Last updated: {{your_date_field|date:"SHORT_DATE_FORMAT"}} {{your_date_field|time:"h:i a"}}</small>

initializing a boolean array in java

They will be initialized to false by default. In Java arrays are created on heap and every element of the array is given a default value depending on its type. For boolean data type the default value is false.

How do I do a multi-line string in node.js?

Take a look at the mstring module for node.js.

This is a simple little module that lets you have multi-line strings in JavaScript.

Just do this:

var M = require('mstring')

var mystring = M(function(){/*** Ontario Mining and Forestry Group ***/})

to get

mystring === "Ontario\nMining and\nForestry\nGroup"

And that's pretty much it.

How It Works
In Node.js, you can call the .toString method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.

Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.


note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/, so you'll need to hack it in yourself.

"Fatal error: Unable to find local grunt." when running "grunt" command

I had the same issue today on windows 32 bit,with node 0.10.25, and grunt 0.4.5.

I followed dongho's answer, with just few extra steps. here are the steps I used to solve the error:

1) create your package.json

$ npm init

2) install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json

$ npm install grunt --save-dev

3) then create gruntfile.js , with a sample code like this:

module.exports = function(grunt) {

  grunt.initConfig({
    jshint: {
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js'],
      options: {
        globals: {
          jQuery: true
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint']
    }
  });

  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');

  grunt.registerTask('default', ['jshint']);

};

here, src/**/*.js and test/**/*.js should be the paths to actual JS files you are using in your project

4) run npm install grunt-contrib-jshint --save-dev

5) run npm install grunt-contrib-watch --save-dev

6) run $ grunt

Note: when you require common package like concat, uglify etc, you need to add those modules via npm install, just the way we installed jshint and watch in step 4 & 5

Center Triangle at Bottom of Div

Can't you just set left to 50% and then have margin-left set to -25px to account for it's width: http://jsfiddle.net/9AbYc/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 50%;
    margin-left: -50px;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

or if you needed a variable width you could use: http://jsfiddle.net/9AbYc/1/

.hero:after {
    content:'';
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

Slicing a dictionary

You should be iterating over the tuple and checking if the key is in the dict not the other way around, if you don't check if the key exists and it is not in the dict you are going to get a key error:

print({k:d[k] for k in l if k in d})

Some timings:

 {k:d[k] for k in set(d).intersection(l)}

In [22]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in l}
   ....: 
100 loops, best of 3: 11.5 ms per loop

In [23]: %%timeit                        
l = xrange(100000)
{k:d[k] for k in set(d).intersection(l)}
   ....: 
10 loops, best of 3: 20.4 ms per loop

In [24]: %%timeit                        
l = xrange(100000)
l = set(l)                              
{key: d[key] for key in d.viewkeys() & l}
   ....: 
10 loops, best of 3: 24.7 ms per

In [25]: %%timeit                        

l = xrange(100000)
{k:d[k] for k in l if k in d}
   ....: 
100 loops, best of 3: 17.9 ms per loop

I don't see how {k:d[k] for k in l} is not readable or elegant and if all elements are in d then it is pretty efficient.

How do I pass parameters into a PHP script through a webpage?

Presumably you're passing the arguments in on the command line as follows:

php /path/to/wwwpublic/path/to/script.php arg1 arg2

... and then accessing them in the script thusly:

<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>

What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:

Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2

... and access:

<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>

If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:

EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:

<?php
if (PHP_SAPI === 'cli') {
    $argument1 = $argv[1];
    $argument2 = $argv[2];
}
else {
    $argument1 = $_GET['argument1'];
    $argument2 = $_GET['argument2'];
}
?>

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

How to get client IP address in Laravel 5+

Solution 1: You can use this type of function for getting client IP

public function getClientIPaddress(Request $request) {
    $clientIp = $request->ip();
    return $clientIp;
}

Solution 2: if the solution1 is not providing accurate IP then you can use this function for getting visitor real IP.

 public function getClientIPaddress(Request $request) {

    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
        $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
        $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
    }
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP)){
        $clientIp = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP)){
        $clientIp = $forward;
    }
    else{
        $clientIp = $remote;
    }

    return $clientIp;
 }

N.B: When you have used load-balancer/proxy-server in your live server then you need to used solution 2 for getting real visitor ip.

Purpose of a constructor in Java?

A Java constructor has the same name as the name of the class to which it belongs.

Constructorā€™s syntax does not include a return type, since constructors never return a value.

Constructor is always called when object is created. example:- Default constructor

class Student3{  
    int id;  
    String name;  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student3 s1=new Student3();  
        Student3 s2=new Student3();  
        s1.display();  
        s2.display();  
    }  
} 

Output:

0 null
0 null

Explanation: In the above class,you are not creating any constructor so compiler provides you a default constructor.Here 0 and null values are provided by default constructor.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor.

class Student4{  
    int id;  
    String name;  
    Student4(int i,String n){  
        id = i;  
        name = n;  
    }  
    void display(){System.out.println(id+" "+name);}  
    public static void main(String args[]){  
        Student4 s1 = new Student4(111,"Karan");  
        Student4 s2 = new Student4(222,"Aryan");  
        s1.display();  
        s2.display();  
    }  
}  

Output:

111 Karan
222 Aryan

How to create a directory using Ansible

Just need to put condition to execute task for specific distribution

- name: Creates directory
  file: path=/src/www state=directory
  when: ansible_distribution == 'Debian'

Python recursive folder read

I've found the following to be the easiest

from glob import glob
import os

files = [f for f in glob('rootdir/**', recursive=True) if os.path.isfile(f)]

Using glob('some/path/**', recursive=True) gets all files, but also includes directory names. Adding the if os.path.isfile(f) condition filters this list to existing files only

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

1) When to use include directive ?

To prevent duplication of same output logic across multiple jsp's of the web app ,include mechanism is used ie.,to promote the re-usability of presentation logic include directive is used

  <%@ include file="abc.jsp" %>

when the above instruction is received by the jsp engine,it retrieves the source code of the abc.jsp and copy's the same inline in the current jsp. After copying translation is performed for the current page

Simply saying it is static instruction to jsp engine ie., whole source code of "abc.jsp" is copied into the current page

2) When to use include action ?

include tag doesn't include the source code of the included page into the current page instead the output generated at run time by the included page is included into the current page response

include tag functionality is similar to that of include mechanism of request dispatcher of servlet programming

include tag is run-time instruction to jsp engine ie., rather copying whole code into current page a method call is made to "abc.jsp" from current page

Benefits of EBS vs. instance-store (and vice-versa)

If you run multiple instance and assign a scheduled service of AWS Instance as one of your priority on Avoiding Unexpected Charges, I would recommend not to use the instance-store.

As explained on documentation of EBS Volumes and the answer from j2d3 and Siddharth Sharma the instance-store can run for as long as you want, but it cannot be stopped. Means that the service cannot be scheduled by an Automatic Start/Stop or Instance Recovery.

Moreover, for this kind of scheme there is also no benefit to use EBS Backed on Elastic Beanstalk as it is designed to ensure that all the resources you need are keep running. It will always do an automatically relaunches any services that you stop. enter image description here Reviewing all the rest, out of the total charges on using the VPC, EBS and ELB that added to EC2-Classic, the EC2-VPC with ELB is mostly the best choice where unlike on EC2-Classic, a stopped instance retains its associated Elastic IP addresses and the EBS volume is stored automatically.

As conclusion, taking the main part of your question:

it seems that EBS is way more useful (stop, start, persist + better speed) at relatively little difference in cost...?

The answer is yes but if your instance is EBS-based, it can be stopped. It will remain in your account, you will not be charged for it. You will be charge only the volume but EBS is charged hourly. You may also consider that among all available types you have a flexibility to Resize the EBS Volume.

Beside the benefits that already listed by Eric, it shall also be aware that in term of cost S3 may or may not be cheaper than EBS. I agree that it relatively little difference in cost if you keep running both types of instance within the same platform and architecture of the application all the time.

However if there a scenario to run the application on a lower cost service, pull all unhandled task and role them to the VPC/EBS via a pipeline or lambda within a short time basis say <1 hour a day, which impossible to do when you use an instance-store, then it will be a different story.

Center a popup window on screen?

You can use css to do it, just give the following properties to the element to be placed in the center of the popup

element{

position:fixed;
left: 50%;
top: 50%;
-ms-transform: translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-webkit-transform: translate(-50%,-50%);
 transform: translate(-50%,-50%);

}

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

How to find topmost view controller on iOS

I think you need a combination of the accepted answer and @fishstix's

+ (UIViewController*) topMostController
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

Swift 3.0+

func topMostController() -> UIViewController? {
    guard let window = UIApplication.shared.keyWindow, let rootViewController = window.rootViewController else {
        return nil
    }

    var topController = rootViewController

    while let newTopController = topController.presentedViewController {
        topController = newTopController
    }

    return topController
}

c++ array assignment of multiple values

You have to replace the values one by one such as in a for-loop or copying another array over another such as using memcpy(..) or std::copy

e.g.

for (int i = 0; i < arrayLength; i++) {
    array[i] = newValue[i];
}

Take care to ensure proper bounds-checking and any other checking that needs to occur to prevent an out of bounds problem.

Can an int be null in Java?

Integer object would be best. If you must use primitives you can use a value that does not exist in your use case. Negative height does not exist for people, so

public int getHeight(String name){
    if(map.containsKey(name)){
        return map.get(name);
    }else{
        return -1;
    }
}

iPhone Debugging: How to resolve 'failed to get the task for process'?

Open Entitlements.plist and set the boolean value get-task-allow to YES - the debugger can attach now!

How to fix '.' is not an internal or external command error

This error comes when using the following command in Windows. You can simply run the following command by removing the dot '.' and the slash '/'.

Instead of writing:

D:\Gesture Recognition\Gesture Recognition\Debug>./"Gesture Recognition.exe"

Write:

D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"

Facebook Post Link Image

The easiest way is just a link tag:

<link rel="image_src" href="http://stackoverflow.com/images/logo.gif" />

But there are some other things you can add to your site to make it more Social media friendly:

Open Graph Tags

Open Graph tags are tags that you add to the <head> of your website to describe the entity your page represents, whether it is a band, restaurant, blog, or something else.

An Open Graph tag looks like this:

<meta property="og:tag name" content="tag value"/> 

If you use Open Graph tags, the following six are required:

  • og:title - The title of the entity.
  • og:type - The type of entity. You must select a type from the list of Open Graph types.
  • og:image - The URL to an image that represents the entity. Images must be at least 50 pixels by 50 pixels. Square images work best, but you are allowed to use images up to three times as wide as they are tall.
  • og:url - The canonical, permanent URL of the page representing the entity. When you use Open Graph tags, the Like button posts a link to the og:url instead of the URL in the Like button code.
  • og:site_name - A human-readable name for your site, e.g., "IMDb".
  • fb:admins or fb:app_id - A comma-separated list of either the Facebook IDs of page administrators or a Facebook Platform application ID. At a minimum, include only your own Facebook ID.

More information on Open Graph tags and details on Administering your page can be found on the Open Graph protocol documentation.

http://developers.facebook.com/docs/reference/plugins/like

Check if an element is present in a Bash array

Obvious caveats aside, if your array was actually like the one above, you could do

if [[ ${arr[*]} =~ d ]]
then
  do your thing
else
  do something
fi

How to undo a git merge with conflicts

Sourcetree

If you not commit your merge, then just double click on another branch (=checkout) and when sourcetree ask you about discarding all changes then agree

Connect over ssh using a .pem file

For AWS if the user is ubuntu use the following to connect to remote server.

chmod 400 mykey.pem

ssh -i mykey.pem ubuntu@your-ip

How to export table data in MySql Workbench to csv?

U can use mysql dump or query to export data to csv file

SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products

Java; String replace (using regular expressions)?

If this is for any general math expression and parenthetical expressions are allowed, it will be very difficult (perhaps impossible) to do this with regular expressions.

If the only replacements are the ones you showed, it's not that hard to do. First strip out *'s, then use capturing like Can Berk GĆ¼der showed to handle the ^'s.

How to encode URL to avoid special characters in Java?

URL construction is tricky because different parts of the URL have different rules for what characters are allowed: for example, the plus sign is reserved in the query component of a URL because it represents a space, but in the path component of the URL, a plus sign has no special meaning and spaces are encoded as "%20".

RFC 2396 explains (in section 2.4.2) that a complete URL is always in its encoded form: you take the strings for the individual components (scheme, authority, path, etc.), encode each according to its own rules, and then combine them into the complete URL string. Trying to build a complete unencoded URL string and then encode it separately leads to subtle bugs, like spaces in the path being incorrectly changed to plus signs (which an RFC-compliant server will interpret as real plus signs, not encoded spaces).

In Java, the correct way to build a URL is with the URI class. Use one of the multi-argument constructors that takes the URL components as separate strings, and it'll escape each component correctly according to that component's rules. The toASCIIString() method gives you a properly-escaped and encoded string that you can send to a server. To decode a URL, construct a URI object using the single-string constructor and then use the accessor methods (such as getPath()) to retrieve the decoded components.

Don't use the URLEncoder class! Despite the name, that class actually does HTML form encoding, not URL encoding. It's not correct to concatenate unencoded strings to make an "unencoded" URL and then pass it through a URLEncoder. Doing so will result in problems (particularly the aforementioned one regarding spaces and plus signs in the path).

Wheel file installation

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it'll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.

Disabled form inputs do not appear in the request

To post values from disabled inputs in addition to enabled inputs, you can simply re-enable all of the form's inputs as it is being submitted.

<form onsubmit="this.querySelectorAll('input').forEach(i => i.disabled = false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

If you prefer jQuery:

<form onsubmit="$(this).find('input').prop('disabled', false)">
    <!-- Re-enable all input elements on submit so they are all posted, 
         even if currently disabled. -->

    <!-- form content with input elements -->
</form>

For ASP.NET MVC C# Razor, you add the submit handler like this:

using (Html.BeginForm("ActionName", "ControllerName", FormMethod.Post,
    // Re-enable all input elements on submit so they are all posted, even if currently disabled.
    new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" } ))
{
    <!-- form content with input elements -->
}

Correct way to select from two tables in SQL Server with no common field to join on

You can (should) use CROSS JOIN. Following query will be equivalent to yours:

SELECT 
   table1.columnA
 , table2.columnA
FROM table1 
CROSS JOIN table2
WHERE table1.columnA = 'Some value'

or you can even use INNER JOIN with some always true conditon:

FROM table1 
INNER JOIN table2 ON 1=1

.toLowerCase not working, replacement function?

.toLowerCase function only exists on strings. You can call toString() on anything in javascript to get a string representation. Putting this all together:

var ans = 334;
var temp = ans.toString().toLowerCase();
alert(temp);

How to write DataFrame to postgres table?

Faster option:

The following code will copy your Pandas DF to postgres DB much faster than df.to_sql method and you won't need any intermediate csv file to store the df.

Create an engine based on your DB specifications.

Create a table in your postgres DB that has equal number of columns as the Dataframe (df).

Data in DF will get inserted in your postgres table.

from sqlalchemy import create_engine
import psycopg2 
import io

if you want to replace the table, we can replace it with normal to_sql method using headers from our df and then load the entire big time consuming df into DB.

engine = create_engine('postgresql+psycopg2://username:password@host:port/database')

df.head(0).to_sql('table_name', engine, if_exists='replace',index=False) #drops old table and creates new empty table

conn = engine.raw_connection()
cur = conn.cursor()
output = io.StringIO()
df.to_csv(output, sep='\t', header=False, index=False)
output.seek(0)
contents = output.getvalue()
cur.copy_from(output, 'table_name', null="") # null values become ''
conn.commit()

Add/delete row from a table

Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.

How do I disable a Button in Flutter?

For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its ignoring property is set to true, the sub-widget (actually, the entire subtree) is not clickable.

IgnorePointer(
    ignoring: true, // or false
    child: RaisedButton(
        onPressed: _logInWithFacebook,
        child: Text("Facebook sign-in"),
        ),
),

Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().

Bootstrap center heading

Bootstrap comes with many pre-build classes and one of them is class="text-left". Please call this class whenever needed. :-)

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

I found the solution. I misplaced the path to the keystore.jks file. Searched for the file on my computer used that path and everything worked great.

HTML <select> selected option background-color CSS style

In CSS:

SELECT OPTION:checked { background-color: red; }

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

Get size of folder or file

You need FileUtils#sizeOfDirectory(File) from commons-io.

Note that you will need to manually check whether the file is a directory as the method throws an exception if a non-directory is passed to it.

WARNING: This method (as of commons-io 2.4) has a bug and may throw IllegalArgumentException if the directory is concurrently modified.

How to set default value for HTML select?

Note: this is JQuery. See SĆ©bastien answer for Javascript

$(function() {
    var temp="a"; 
    $("#MySelect").val(temp);
});

<select name="MySelect" id="MySelect">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
</select>

MyISAM versus InnoDB

I tried to run insertion of random data into MyISAM and InnoDB tables. The result was quite shocking. MyISAM needed a few seconds less for inserting 1 million rows than InnoDB for just 10 thousand!

Force div element to stay in same place, when page is scrolled

There is something wrong with your code.

position : absolute makes the element on top irrespective of other elements in the same page. But the position not relative to the scroll

This can be solved with position : fixed This property will make the element position fixed and still relative to the scroll.

Or

You can check it out Here

How to use split?

According to MDN, the split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.

Example

var str = 'Hello my friend'

var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]

In your case

var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]

console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

CSS: how to position element in lower right?

Set the CSS position: relative; on the box. This causes all absolute positions of objects inside to be relative to the corners of that box. Then set the following CSS on the "Bet 5 days ago" line:

position: absolute;
bottom: 0;
right: 0;

If you need to space the text farther away from the edge, you could change 0 to 2px or similar.

Unable to create migrations after upgrading to ASP.NET Core 2.0

You can add a class that implements IDesignTimeDbContextFactory inside of your Web project.

Here is the sample code:

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<CodingBlastDbContext>
{
    public CodingBlastDbContext CreateDbContext(string[] args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json")
            .Build();
        var builder = new DbContextOptionsBuilder<CodingBlastDbContext>();
        var connectionString = configuration.GetConnectionString("DefaultConnection");
        builder.UseSqlServer(connectionString);
        return new CodingBlastDbContext(builder.Options);
    }
}

Then, navigate to your Database project and run the following from command line:

dotnet ef migrations add InitialMigration -s ../Web/

dotnet ef database update -s ../Web/

-s stands for startup project and ../Web/ is the location of my web/startup project.

resource

How to form a correct MySQL connection string?

string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";

ValueError: invalid literal for int () with base 10

    readings = (infile.readline())
    print readings
    while readings != 0:
        global count
        readings = int(readings)

There's a problem with that code. readings is a new line read from the file - it's a string. Therefore you should not compare it to 0. Further, you can't just convert it to an integer unless you're sure it's indeed one. For example, empty lines will produce errors here (as you've surely found out).

And why do you need the global count? That's most certainly bad design in Python.

Remove the last character in a string in T-SQL?

To update the record by trimming the last N characters of a particular column:

UPDATE tablename SET columnName = LEFT(columnName , LEN(columnName )-N) where clause

Resize image proportionally with MaxHeight and MaxWidth constraints

Like this?

public static void Test()
{
    using (var image = Image.FromFile(@"c:\logo.png"))
    using (var newImage = ScaleImage(image, 300, 400))
    {
        newImage.Save(@"c:\test.png", ImageFormat.Png);
    }
}

public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
    var ratioX = (double)maxWidth / image.Width;
    var ratioY = (double)maxHeight / image.Height;
    var ratio = Math.Min(ratioX, ratioY);

    var newWidth = (int)(image.Width * ratio);
    var newHeight = (int)(image.Height * ratio);

    var newImage = new Bitmap(newWidth, newHeight);

    using (var graphics = Graphics.FromImage(newImage))
        graphics.DrawImage(image, 0, 0, newWidth, newHeight);

    return newImage;
}

How to get ASCII value of string in C#

From MSDN

string value = "9quali52ty3";

// Convert the string into a byte[].
byte[] asciiBytes = Encoding.ASCII.GetBytes(value);

You now have an array of the ASCII value of the bytes. I got the following:

57 113 117 97 108 105 53 50 116 121 51

Ruby capitalize every word first letter

If you are trying to capitalize the first letter of each word in an array you can simply put this:

array_name.map(&:capitalize)

Difference between adjustResize and adjustPan in android?

adjustResize = resize the page content

adjustPan = move page content without resizing page content

Disabling the long-running-script message in Internet Explorer

This message displays when Internet Explorer reaches the maximum number of synchronous instructions for a piece of JavaScript. The default maximum is 5,000,000 instructions, you can increase this number on a single machine by editing the registry.

Internet Explorer now tracks the total number of executed script statements and resets the value each time that a new script execution is started, such as from a timeout or from an event handler, for the current page with the script engine. Internet Explorer displays a "long-running script" dialog box when that value is over a threshold amount.

The only way to solve the problem for all users that might be viewing your page is to break up the number of iterations your loop performs using timers, or refactor your code so that it doesn't need to process as many instructions.

Breaking up a loop with timers is relatively straightforward:

var i=0;
(function () {
    for (; i < 6000000; i++) {
        /*
            Normal processing here
        */

        // Every 100,000 iterations, take a break
        if ( i > 0 && i % 100000 == 0) {
            // Manually increment `i` because we break
            i++;
            // Set a timer for the next iteration 
            window.setTimeout(arguments.callee);
            break;
        }
    }
})();

Received fatal alert: handshake_failure through SSLHandshakeException

Mine was a TLS version incompatible error.

Previously it was TLSv1 I changed it TLSV1.2 this solved my problem.

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Config Error: This configuration section cannot be used at this path

Before reinstalling iis and possibly all of your sites, go to: C:\inetpub\history

There should be number of folders (example: CFGHISTORY_0000000029). Each time a root config file is modified, and entry is made in there. (by default backups of the last 10 modifications are saved)

Look for a backup folder that has the right date and time for it, Click on it and see if there is a file called; applicationhost.config

Compare this to your current applicationhost.config file, or replace your current version with it (make a backup first!!!).

I recently had my localhost iis file modified by a windows 2004 update package, which locked a few features at the root (such as handlers), which prevented localhost sites from working - hence my search.

If you open the file in Visual Code, you can see each area that is locked with a overrideModeDefault="Deny"

This might get you a step closer, and also a way to recover if this file ever gets corrupted.

Copy all the lines to clipboard

you can press gg to locate your curser to the start of the file,then press yG to copy all the content from the start to end(G located) to buffer.good luck!

How do I specify the JDK for a GlassFish domain?

Had the same problem in my IntelliJ 17 after adding fresh glassfish 4.1.

I had set my JAVA_HOME environment variable as follow:

echo %JAVA_HOME%
C:\Java\jdk1.8.0_121\

Then opened %GLASSFISH_HOME%\glassfish\config\asenv.bat

And just added and the end of the file:

set AS_JAVA=%JAVA_HOME%

Then Glassfish started without problems.

How to git commit a single file/directory

For git 1.9.5 on Windows 7: "my Notes" (double quotes) corrected this issue. In my case putting the file(s) before or after the -m 'message'. made no difference; using single quotes was the problem.

Websocket onerror - how to read error description?

The error Event the onerror handler receives is a simple event not containing such information:

If the user agent was required to fail the WebSocket connection or the WebSocket connection is closed with prejudice, fire a simple event named error at the WebSocket object.

You may have better luck listening for the close event, which is a CloseEvent and indeed has a CloseEvent.code property containing a numerical code according to RFC 6455 11.7 and a CloseEvent.reason string property.

Please note however, that CloseEvent.code (and CloseEvent.reason) are limited in such a way that network probing and other security issues are avoided.

How to convert Double to int directly?

try casting the value

double d = 1.2345;
long l = (long) d;

Finding the number of non-blank columns in an Excel sheet using VBA

Jean-FranƧois Corbett's answer is perfect. To be exhaustive I would just like to add that with some restrictons you could also use UsedRange.Columns.Count or UsedRange.Rows.Count.
The problem is that UsedRange is not always updated when deleting rows/columns (at least until you reopen the workbook).

Stop MySQL service windows

To successfully stop MySQL Service on Windows

  1. Check on services the name of the service for MySQL
  2. Run as administrator : net stop [MySQL Service name]

An error occurred while signing: SignTool.exe not found

After upgrading build tools in DevOps build agent to visual studio 2019, we started getting the below error for 64-bit build step of a WPF application.

C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\amd64\Microsoft.Common.CurrentVersion.targets(3975,5): error MSB3482: An error occurred while signing: SignTool.exe was not found at path

I tried all the above answers except the ones to disable signing or signing security and nothing helped.

Disabled the default MSBUILD step enter image description here

Added a cmd prompt step enter image description here

The path is "C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\MsBuild.exe"

Note: Removed amd64 from the path above.

This is still a workaround. I hope Microsoft will fix it in the following release.

jquery json to string?

I use

$.param(jsonObj)

which gets me the string.

How can I import Swift code to Objective-C?

Importing Swift file inside Objective-c can cause this error, if it doesn't import properly.

NOTE: You don't have to import Swift files externally, you just have to import one file which takes care of swift files.

When you Created/Copied Swift file inside Objective-C project. It would've created a bridging header automatically.

Check Objective-C Generated Interface Header Name at Targets -> Build Settings.

enter image description here

Based on above, I will import KJExpandable-Swift.h as it is.

Your's will be TargetName-Swift.h, Where TargetName differs based on your project name or another target your might have added and running on it.

As below my target is KJExpandable, so it's KJExpandable-Swift.h
enter image description here

Set max-height on inner div so scroll bars appear, but not on parent div

set this :

#inner-right {
    height: 100%;
    max-height: 96%;//change here
    overflow: auto;
    background: ivory;
}

this will solve your problem.

How to convert a JSON string to a dictionary?

With Swift 3, JSONSerialization has a method called json?Object(with:?options:?). json?Object(with:?options:?) has the following declaration:

class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any

Returns a Foundation object from given JSON data.

When you use json?Object(with:?options:?), you have to deal with error handling (try, try? or try!) and type casting (from Any). Therefore, you can solve your problem with one of the following patterns.


#1. Using a method that throws and returns a non-optional type

import Foundation

func convertToDictionary(from text: String) throws -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(dictionary) // prints: ["City": "Paris"]
} catch {
    print(error)
}
let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(dictionary) // prints [:]
} catch {
    print(error)
}
let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(dictionary)
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}

#2. Using a method that throws and returns an optional type

import Foundation

func convertToDictionary(from text: String) throws -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
do {
    let dictionary = try convertToDictionary(from: string1)
    print(String(describing: dictionary)) // prints: Optional(["City": "Paris"])
} catch {
    print(error)
}
let string2 = "{\"Quantity\":100}"
do {
    let dictionary = try convertToDictionary(from: string2)
    print(String(describing: dictionary)) // prints nil
} catch {
    print(error)
}
let string3 = "{\"Object\"}"
do {
    let dictionary = try convertToDictionary(from: string3)
    print(String(describing: dictionary))
} catch {
    print(error) // prints: Error Domain=NSCocoaErrorDomain Code=3840 "No value for key in object around character 9." UserInfo={NSDebugDescription=No value for key in object around character 9.}
}

#3. Using a method that does not throw and returns a non-optional type

import Foundation

func convertToDictionary(from text: String) -> [String: String] {
    guard let data = text.data(using: .utf8) else { return [:] }
    let anyResult: Any? = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String] ?? [:]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(dictionary1) // prints: ["City": "Paris"]
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(dictionary2) // prints: [:]
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(dictionary3) // prints: [:]

#4. Using a method that does not throw and returns an optional type

import Foundation

func convertToDictionary(from text: String) -> [String: String]? {
    guard let data = text.data(using: .utf8) else { return nil }
    let anyResult = try? JSONSerialization.jsonObject(with: data, options: [])
    return anyResult as? [String: String]
}

Usage:

let string1 = "{\"City\":\"Paris\"}"
let dictionary1 = convertToDictionary(from: string1)
print(String(describing: dictionary1)) // prints: Optional(["City": "Paris"])
let string2 = "{\"Quantity\":100}"
let dictionary2 = convertToDictionary(from: string2)
print(String(describing: dictionary2)) // prints: nil
let string3 = "{\"Object\"}"
let dictionary3 = convertToDictionary(from: string3)
print(String(describing: dictionary3)) // prints: nil

window.open with headers

As the best anwser have writed using XMLHttpResponse except window.open, and I make the abstracts-anwser as a instance.

The main Js file is download.js Download-JS

 // var download_url = window.BASE_URL+ "/waf/p1/download_rules";
    var download_url = window.BASE_URL+ "/waf/p1/download_logs_by_dt";
    function download33() {
        var sender_data = {"start_time":"2018-10-9", "end_time":"2018-10-17"};
        var x=new XMLHttpRequest();
        x.open("POST", download_url, true);
        x.setRequestHeader("Content-type","application/json");
//        x.setRequestHeader("Access-Control-Allow-Origin", "*");
        x.setRequestHeader("Authorization", "JWT " + localStorage.token );
        x.responseType = 'blob';
        x.onload=function(e){download(x.response, "test211.zip", "application/zip" ); }
        x.send( JSON.stringify(sender_data) ); // post-data
    }

tell pip to install the dependencies of packages listed in a requirement file

As @Ming mentioned:

pip install -r file.txt

Here's a simple line to force update all dependencies:

while read -r package; do pip install --upgrade --force-reinstall $package;done < pipfreeze.txt

How to start mongodb shell?

In the terminal, use "mongo" command to switch the terminal into the MongoDB shell:

$ mongo
MongoDB shell version: 2.6.10
connecting to: admin
>

Once you get > symbol in the terminal, you have entered into the MongoDB shell.

How to make CREATE OR REPLACE VIEW work in SQL Server?

The accepted solution has an issue with the need to maintain the same statement twice, it isnt very efficient (although it works). In theory Gordon Linoff's solution would be the go, except it does not work in MSSQL because create view must be the first line in a batch.

The drop/create does not answer the question as posed. The following does the job as per the original question.

if not exists (select * from sysobjects where name='TABLE_A' and xtype='V')
exec ('create view SELECT 
VCV.xxxx,
    VCV.yyyy AS yyyy,
    VCV.zzzz AS zzzz
FROM TABLE_A')

How to export SQL Server database to MySQL?

PhpMyAdmin has a Import wizard that lets you import a MSSQL file type too.

See http://dev.mysql.com/doc/refman/5.1/en/sql-mode.html for the types of DB scripts it supports.

Describe table structure

It depends from the database you use. Here is an incomplete list:

  • sqlite3: .schema table_name
  • Postgres (psql): \d table_name
  • SQL Server: sp_help table_name (or sp_columns table_name for only columns)
  • Oracle DB2: desc table_name or describe table_name
  • MySQL: describe table_name (or show columns from table_name for only columns)

need to add a class to an element

You probably need something like:

result.className = 'red'; 

In pure JavaScript you should use className to deal with classes. jQuery has an abstraction called addClass for it.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

you have to check your pip package to be updated to the latest version in your pycharm and then install numpy package. in settings -> project:progLangComp -> Project Interpreter there is a table of packages and their current version (just labelled as Version) and their latest version (labelled as Latest). Pip current version number should be the same as latest version. If you see a blue arrow in front of pip, you have to update it to the latest then trying to install numpy or any other packages that you couldn't install, for me it was pandas which I wanted to install.

enter image description here

How to include (source) R script in other scripts

You could write a function that takes a filename and an environment name, checks to see if the file has been loaded into the environment and uses sys.source to source the file if not.

Here's a quick and untested function (improvements welcome!):

include <- function(file, env) {
  # ensure file and env are provided
  if(missing(file) || missing(env))
    stop("'file' and 'env' must be provided")
  # ensure env is character
  if(!is.character(file) || !is.character(env))
    stop("'file' and 'env' must be a character")

  # see if env is attached to the search path
  if(env %in% search()) {
    ENV <- get(env)
    files <- get(".files",ENV)
    # if the file hasn't been loaded
    if(!(file %in% files)) {
      sys.source(file, ENV)                        # load the file
      assign(".files", c(file, files), envir=ENV)  # set the flag
    }
  } else {
    ENV <- attach(NULL, name=env)      # create/attach new environment
    sys.source(file, ENV)              # load the file
    assign(".files", file, envir=ENV)  # set the flag
  }
}

python: after installing anaconda, how to import pandas

If you are facing same problem as mine. Here is the solution which works for me.

  1. Uninstall every python and anaconda.
  2. Download anaconda from here "http://continuum.io/downloads" and only install it (no other python is needed).
  3. Open spyder and import.
  4. If you get any error, type in command prompt

    pip install module_name

I hope it will work for you too

Class 'ViewController' has no initializers in swift

For me was a declaration incomplete. For example:

var isInverted: Bool

Instead the correct way:

var isInverted: Bool = false

How to input automatically when running a shell over SSH?

For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.

Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command

Importing CommonCrypto in a Swift framework

WARNING: iTunesConnect may reject apps that are using this method.


New member on my team accidentally broke the solution given by one of the top answers, so I decided to consolidate it in a small wrapper project called CommonCryptoModule. You can install it manually or via Cocoapods:

pod 'CommonCryptoModule', '~> 1.0.2'

Then, all you have to do is to import the module where you need CommonCrypto, like so:

import CommonCryptoModule

Hope someone else finds this useful.

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

JavaScript/jQuery - How to check if a string contain specific words

This will

/\bword\b/.test("Thisword is not valid");

return false, when this one

/\bword\b/.test("This word is valid");

will return true.

Command to get time in milliseconds

  • date +"%T.%N" returns the current time with nanoseconds.

    06:46:41.431857000
    
  • date +"%T.%6N" returns the current time with nanoseconds rounded to the first 6 digits, which is microseconds.

    06:47:07.183172
    
  • date +"%T.%3N" returns the current time with nanoseconds rounded to the first 3 digits, which is milliseconds.

    06:47:42.773
    

In general, every field of the date command's format can be given an optional field width.

Is it possible to create a File object from InputStream

Since Java 7, you can do it in one line even without using any external libraries:

Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

See the API docs.

isset in jQuery?

You can simply use this:

if ($("#one")){
   alert('yes');
}

if ($("#two")){
   alert('yes');
}

if ($("#three")){
   alert('yes');
}

if ($("#four")){
   alert('no');
}

Sorry, my mistake, it does not work.

Callback functions in C++

There is also the C way of doing callbacks: function pointers

//Define a type for the callback signature,
//it is not necessary, but makes life easier

//Function pointer called CallbackType that takes a float
//and returns an int
typedef int (*CallbackType)(float);  


void DoWork(CallbackType callback)
{
  float variable = 0.0f;

  //Do calculations

  //Call the callback with the variable, and retrieve the
  //result
  int result = callback(variable);

  //Do something with the result
}

int SomeCallback(float variable)
{
  int result;

  //Interpret variable

  return result;
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWork(&SomeCallback);
}

Now if you want to pass in class methods as callbacks, the declarations to those function pointers have more complex declarations, example:

//Declaration:
typedef int (ClassName::*CallbackType)(float);

//This method performs work using an object instance
void DoWorkObject(CallbackType callback)
{
  //Class instance to invoke it through
  ClassName objectInstance;

  //Invocation
  int result = (objectInstance.*callback)(1.0f);
}

//This method performs work using an object pointer
void DoWorkPointer(CallbackType callback)
{
  //Class pointer to invoke it through
  ClassName * pointerInstance;

  //Invocation
  int result = (pointerInstance->*callback)(1.0f);
}

int main(int argc, char ** argv)
{
  //Pass in SomeCallback to the DoWork
  DoWorkObject(&ClassName::Method);
  DoWorkPointer(&ClassName::Method);
}

Sending intent to BroadcastReceiver from adb

The true way to send a broadcast from ADB command is :

adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test from adb"

And, -a means ACTION, --es means to send a String extra.


PS. There are other data type you can send by specifying different params like:

[-e|--es <EXTRA_KEY> <EXTRA_STRING_VALUE> ...]
[--esn <EXTRA_KEY> ...]
[--ez <EXTRA_KEY> <EXTRA_BOOLEAN_VALUE> ...]
[--ei <EXTRA_KEY> <EXTRA_INT_VALUE> ...]
[--el <EXTRA_KEY> <EXTRA_LONG_VALUE> ...]
[--ef <EXTRA_KEY> <EXTRA_FLOAT_VALUE> ...]
[--eu <EXTRA_KEY> <EXTRA_URI_VALUE> ...]
[--ecn <EXTRA_KEY> <EXTRA_COMPONENT_NAME_VALUE>]
[--eia <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]
    (mutiple extras passed as Integer[])
[--eial <EXTRA_KEY> <EXTRA_INT_VALUE>[,<EXTRA_INT_VALUE...]]
    (mutiple extras passed as List<Integer>)
[--ela <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]
    (mutiple extras passed as Long[])
[--elal <EXTRA_KEY> <EXTRA_LONG_VALUE>[,<EXTRA_LONG_VALUE...]]
    (mutiple extras passed as List<Long>)
[--efa <EXTRA_KEY> <EXTRA_FLOAT_VALUE>[,<EXTRA_FLOAT_VALUE...]]
    (mutiple extras passed as Float[])
[--efal <EXTRA_KEY> <EXTRA_FLOAT_VALUE>[,<EXTRA_FLOAT_VALUE...]]
    (mutiple extras passed as List<Float>)
[--esa <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
    (mutiple extras passed as String[]; to embed a comma into a string,
     escape it using "\,")
[--esal <EXTRA_KEY> <EXTRA_STRING_VALUE>[,<EXTRA_STRING_VALUE...]]
    (mutiple extras passed as List<String>; to embed a comma into a string,
     escape it using "\,")
[-f <FLAG>]

For example, you can send an int value by:

--ei int_key 0

Can't stop rails server

killall -9 ruby will kill all the ruby processes, and at-least on my machine, rails servers appear as ruby processes. killall -9 rails is much more specific and doesn't work for older versions of rails servers (it gives a 'rails:no process found' because the process is named ruby)

Encountered this problem a while ago. After submitting a form in activeadmin, the rails server just hanged and I was unable to kill it using normal means (even after ctrl+z it was still running in the background). Learner's answer helped, but this command doesn't need process id.

Specifying row names when reading in a file

See ?read.table. Basically, when you use read.table, you specify a number indicating the column:

##Row names in the first column
read.table(filname.txt, row.names=1)

Get month and year from a datetime in SQL Server 2005

The question is about SQL Server 2005, many of the answers here are for later version SQL Server.

select convert (varchar(7), getdate(),20)
--Typical output 2015-04

SQL Server 2005 does not have date function which was introduced in SQL Server 2008

Python dictionary get multiple values

You can use At from pydash:

from pydash import at
dict = {'a': 1, 'b': 2, 'c': 3}
list = at(dict, 'a', 'b')
list == [1, 2]

What is the maximum float in Python?

If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931

>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

Filter by Dates in SQL

Well you are trying to compare Date with Nvarchar which is wrong. Should be

Where dates between date1 And date2
-- both date1 & date2 should be date/datetime

If date1,date2 strings; server will convert them to date type before filtering.

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

'make' is a command for UNIX/Linux. Instead of it, use 'nmake' command in MS Windows. Or you'd better use an emulator like CYGWIN.

Retrieve WordPress root directory path?

You can use get_site_url() function to get the base url of the wordpress site.

For more information, please visit http://codex.wordpress.org/Function_Reference/get_site_url

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

how to set start value as "0" in chartjs?

For Chart.js 2.*, the option for the scale to begin at zero is listed under the configuration options of the linear scale. This is used for numerical data, which should most probably be the case for your y-axis. So, you need to use this:

options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero: true
            }
        }]
    }
}

A sample line chart is also available here where the option is used for the y-axis. If your numerical data is on the x-axis, use xAxes instead of yAxes. Note that an array (and plural) is used for yAxes (or xAxes), because you may as well have multiple axes.

Retrieve the maximum length of a VARCHAR column in SQL Server

Many times you want to identify the row that has that column with the longest length, especially if you are troubleshooting to find out why the length of a column on a row in a table is so much longer than any other row, for instance. This query will give you the option to list an identifier on the row in order to identify which row it is.

select ID, [description], len([description]) as descriptionlength
FROM [database1].[dbo].[table1]
where len([description]) = 
 (select max(len([description]))
  FROM [database1].[dbo].[table1]

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

Which programming languages can be used to develop in Android?

Java and C:

  • C used for low level functionalities and device connectivities
  • Java used for Framework and Application Level

You may find more information in Android developers site.

Display help message with python argparse when script is called without any arguments

Set your positional arguments with nargs, and check if positional args are empty.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
args = parser.parse_args()
if not args.file:
    parser.print_help()

Reference Python nargs

How can I get the count of milliseconds since midnight for the current?

In Java 8 you can simply do

ZonedDateTime.now().toInstant().toEpochMilli()

returns : the number of milliseconds since the epoch of 1970-01-01T00:00:00Z

Code for Greatest Common Divisor in Python

gcd = lambda m,n: m if not n else gcd(n,m%n)

How to get a user's time zone?

func getCurrentTimeZone() -> String {
        let localTimeZoneAbbreviation: Int = TimeZone.current.secondsFromGMT()
        let gmtAbbreviation = (localTimeZoneAbbreviation / 60)
        return "\(gmtAbbreviation)"
}

You can get current time zone abbreviation.

Python, Matplotlib, subplot: How to set the axis range?

Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes or AxesSubplot object. The functions of interest are set_autoscale_on, set_autoscalex_on, and set_autoscaley_on.

In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on property to False. Here is a modified version of the FFT subplot snippet from your code:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))

How to set the part of the text view is clickable

I would suggest a different approach that I think requires less code and is more "localization-friendly".

Supposing that your destination activity is called "ActivityStack", define in the manifest an intent filter for it with a custom scheme (e.g. "myappscheme") in AndroidManifest.xml:

<activity
    android:name=".ActivityStack">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:host="stack"/>
        <data android:scheme="myappscheme" />
    </intent-filter>
</activity>

Define the TextView without any special tag (it is important to NOT use the "android:autoLink" tag, see: https://stackoverflow.com/a/20647011/1699702):

<TextView
    android:id="@+id/stackView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/stack_string" />

then use a link with custom scheme and host in the text of the TextView as (in String.xml):

<string name="stack_string">Android is a Software <a href="myappscheme://stack">stack</a></string>

and "activate" the link with setMovementMethod() (in onCreate() for activities or onCreateView() for fragments):

TextView stack = findViewById(R.id.stackView);
stack.setMovementMethod(LinkMovementMethod.getInstance());

This will open the stack activity with a tap on the "stack" word.

Plotting using a CSV file

You can also plot to a png file using gnuplot (which is free):

terminal commands

gnuplot> set title '<title>'
gnuplot> set ylabel '<yLabel>'
gnuplot> set xlabel '<xLabel>'
gnuplot> set grid
gnuplot> set term png
gnuplot> set output '<Output file name>.png'
gnuplot> plot '<fromfile.csv>'

note: you always need to give the right extension (.png here) at set output

Then it is also possible that the ouput is not lines, because your data is not continues. To fix this simply change the 'plot' line to:

plot '<Fromfile.csv>' with line lt -1 lw 2

More line editing options (dashes and line color ect.) at: http://gnuplot.sourceforge.net/demo_canvas/dashcolor.html

  • gnuplot is available in most linux distros via the package manager (e.g. on an apt based distro, run apt-get install gnuplot)
  • gnuplot is available in windows via Cygwin
  • gnuplot is available on macOS via homebrew (run brew install gnuplot)

How can I align text directly beneath an image?

You can use HTML5 <figcaption>:

<figure>
  <img src="img.jpg" alt="my img"/>
  <figcaption> Your text </figcaption>
</figure>

Working example.

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

Syntax error: Illegal return statement in JavaScript

This can happen in ES6 if you use the incorrect (older) syntax for static methods:

export default class MyClass
{
    constructor()
    {
       ...
    }

    myMethod()
    {
       ...
    }
}

MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works

MyClass.anotherMethod() //or
MyClass.anotherMethod = function()
{
   return something; //doesn't work
}

Whereas the correct syntax is:

export default class MyClass
{
    constructor()
    {
       ...
    }

    myMethod()
    {
       ...
    }

    static anotherMethod()
    {
       return something; //works
    }
}

MyClass.someEnum = {Red: 0, Green: 1, Blue: 2}; //works

How to choose the right bean scope?

Since JSF 2.3 all the bean scopes defined in package javax.faces.bean package have been deprecated to align the scopes with CDI. Moreover they're only applicable if your bean is using @ManagedBean annotation. If you are using JSF versions below 2.3 refer to the legacy answer at the end.


From JSF 2.3 here are scopes that can be used on JSF Backing Beans:

1. @javax.enterprise.context.ApplicationScoped: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. This is useful when you have data for whole application.

2. @javax.enterprise.context.SessionScoped: The session scope persists from the time that a session is established until session termination. The session context is shared between all requests that occur in the same HTTP session. This is useful when you wont to save data for a specific client for a particular session.

3. @javax.enterprise.context.ConversationScoped: The conversation scope persists as log as the bean lives. The scope provides 2 methods: Conversation.begin() and Conversation.end(). These methods should called explicitly, either to start or end the life of a bean.

4. @javax.enterprise.context.RequestScoped: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

5. @javax.faces.flow.FlowScoped: The Flow scope persists as long as the Flow lives. A flow may be defined as a contained set of pages (or views) that define a unit of work. Flow scoped been is active as long as user navigates with in the Flow.

6. @javax.faces.view.ViewScoped: A bean in view scope persists while the same JSF page is redisplayed. As soon as the user navigates to a different page, the bean goes out of scope.


The following legacy answer applies JSF version before 2.3

As of JSF 2.x there are 4 Bean Scopes:

  • @SessionScoped
  • @RequestScoped
  • @ApplicationScoped
  • @ViewScoped

Session Scope: The session scope persists from the time that a session is established until session termination. A session terminates if the web application invokes the invalidate method on the HttpSession object, or if it times out.

RequestScope: The request scope is short-lived. It starts when an HTTP request is submitted and ends after the response is sent back to the client. If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage.

ApplicationScope: The application scope persists for the entire duration of the web application. That scope is shared among all requests and all sessions. You place managed beans into the application scope if a single bean should be shared among all instances of a web application. The bean is constructed when it is first requested by any user of the application, and it stays alive until the web application is removed from the application server.

ViewScope: View scope was added in JSF 2.0. A bean in view scope persists while the same JSF page is redisplayed. (The JSF specification uses the term view for a JSF page.) As soon as the user navigates to a different page, the bean goes out of scope.

Choose the scope you based on your requirement.

Source: Core Java Server Faces 3rd Edition by David Geary & Cay Horstmann [Page no. 51 - 54] enter image description here

How to checkout in Git by date?

To keep your current changes

You can keep your work stashed away, without commiting it, with git stash. You would than use git stash pop to get it back. Or you can (as carleeto said) git commit it to a separate branch.

Checkout by date using rev-parse

You can checkout a commit by a specific date using rev-parse like this:

git checkout 'master@{1979-02-26 18:30:00}'

More details on the available options can be found in the git-rev-parse.

As noted in the comments this method uses the reflog to find the commit in your history. By default these entries expire after 90 days. Although the syntax for using the reflog is less verbose you can only go back 90 days.

Checkout out by date using rev-list

The other option, which doesn't use the reflog, is to use rev-list to get the commit at a particular point in time with:

git checkout `git rev-list -n 1 --first-parent --before="2009-07-27 13:37" master`

Note the --first-parent if you want only your history and not versions brought in by a merge. That's what you usually want.

Custom bullet symbol for <li> elements in <ul> that is a regular character, and not an image

You can use the :before pseudo-selector to insert content in front of the list item. You can find an example on Quirksmode, at http://www.quirksmode.org/css/beforeafter.html. I use this to insert giant quotes around blockquotes...

HTH.

Python != operation vs "is not"

>>> () is ()
True
>>> 1 is 1
True
>>> (1,) == (1,)
True
>>> (1,) is (1,)
False
>>> a = (1,)
>>> b = a
>>> a is b
True

Some objects are singletons, and thus is with them is equivalent to ==. Most are not.

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

jQuery checkbox event handling

$('#myform :checkbox').change(function() {
    // this will contain a reference to the checkbox   
    if (this.checked) {
        // the checkbox is now checked 
    } else {
        // the checkbox is now no longer checked
    }
});

Is it possible to specify a different ssh port when using rsync?

I was not able to get rsync to connect via ssh on a different port, but I was able to redirect the ssh connection to the computer I wanted via iptables. This is not the solution I was looking for, but it solved my problem.

Reading in from System.in - Java

You would read from System.in just like you would for keyboard input using, for example, InputStreamReader or Scanner.

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

How do I delete multiple rows in Entity Framework (without foreach)

In EF 6.2 this works perfectly, sending the delete directly to the database without first loading the entities:

context.Widgets.Where(predicate).Delete();

With a fixed predicate it's quite straightforward:

context.Widgets.Where(w => w.WidgetId == widgetId).Delete();

And if you need a dynamic predicate have a look at LINQKit (Nuget package available), something like this works fine in my case:

Expression<Func<Widget, bool>> predicate = PredicateBuilder.New<Widget>(x => x.UserID == userID);
if (somePropertyValue != null)
{
    predicate = predicate.And(w => w.SomeProperty == somePropertyValue);
}
context.Widgets.Where(predicate).Delete();

Converting bool to text in C++

This should be fine:


const char* bool_cast(const bool b) {
    return b ? "true" : "false";
}

But, if you want to do it more C++-ish:


#include <iostream>
#include <string>
#include <sstream>
using namespace std;

string bool_cast(const bool b) {
    ostringstream ss;
    ss << boolalpha << b;
    return ss.str();
}

int main() {
    cout << bool_cast(true) << "\n";
    cout << bool_cast(false) << "\n";
}

How to change the name of an iOS app?

In Xcode 3.2 just select the Project entry in the Groups & Files panel, then select the menu item Project -> Renameā€¦ Worked for me.

Trying to handle "back" navigation button action in iOS

In Swift 4 or above:

override func didMove(toParent parent: UIViewController?) {
    if parent == nil {
        //"Back pressed"
    }
}

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Getting the closest string match

If you're doing this in the context of a search engine or frontend against a database, you might consider using a tool like Apache Solr, with the ComplexPhraseQueryParser plugin. This combination allows you to search against an index of strings with the results sorted by relevance, as determined by Levenshtein distance.

We've been using it against a large collection of artists and song titles when the incoming query may have one or more typos, and it's worked pretty well (and remarkably fast considering the collections are in the millions of strings).

Additionally, with Solr, you can search against the index on demand via JSON, so you won't have to reinvent the solution between the different languages you're looking at.

A CORS POST request works from plain JavaScript, but why not with jQuery?

Modify your Jquery in following way:

$.ajax({
            url: someurl,
            contentType: 'application/json',
            data: JSONObject,
            headers: { 'Access-Control-Allow-Origin': '*' }, //add this line
            dataType: 'json',
            type: 'POST',                
            success: function (Data) {....}
});

LDAP root query syntax to search more than one specific OU

You can!!! In short use this as the connection string:

ldap://<host>:3268/DC=<my>,DC=<domain>?cn

together with your search filter, e.g.

(&(sAMAccountName={0})(&((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=<some-special-nested-group>,OU=<ou3>,OU=<ou2>,OU=<ou1>,DC=<dc3>,DC=<dc2>,DC=<dc1>))))

That will search in the so called Global Catalog, that had been available out-of-the-box in our environment.

Instead of the known/common other versions (or combinations thereof) that did NOT work in our environment with multiple OUs:

ldap://<host>/DC=<my>,DC=<domain>
ldap://<host>:389/DC=<my>,DC=<domain>  (standard port)
ldap://<host>/OU=<someOU>,DC=<my>,DC=<domain>
ldap://<host>/CN=<someCN>,DC=<my>,DC=<domain>
ldap://<host>/(|(OU=<someOU1>)(OU=<someOU2>)),DC=<my>,DC=<domain> (search filters here shouldn't work at all by definition)

(I am a developer, not an AD/LDAP guru:) Damn I had been searching for this solution everywhere for almost 2 days and almost gave up, getting used to the thought I might have to implement this obviously very common scenario by hand (with Jasperserver/Spring security(/Tomcat)). (So this shall be a reminder if somebody else or me should have this problem again in the future :O) )

Here some other related threads I found during my research that had been mostly of little help:

And here I will provide our anonymized Tomcat LDAP config in case it may be helpful (/var/lib/tomcat7/webapps/jasperserver/WEB-INF/applicationContext-externalAUTH-LDAP.xml):

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

<!-- ############ LDAP authentication ############ - Sample configuration 
    of external authentication via an external LDAP server. -->


<bean id="proxyAuthenticationProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.BaseAuthenticationProcessingFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />
    </property>

    <property name="sessionRegistry">
        <ref bean="sessionRegistry" />
    </property>

    <property name="internalAuthenticationFailureUrl" value="/login.html?error=1" />
    <property name="defaultTargetUrl" value="/loginsuccess.html" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>

<bean id="proxyAuthenticationSoapProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationSoapProcessingFilter">
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
    <property name="filterProcessesUrl" value="/services" />
</bean>

<bean id="proxyRequestParameterAuthenticationFilter"
    class="com.jaspersoft.jasperserver.war.util.ExternalRequestParameterAuthenticationFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationFailureUrl">
        <value>/login.html?error=1</value>
    </property>
    <property name="excludeUrls">
        <list>
            <value>/j_spring_switch_user</value>
        </list>
    </property>
</bean>

<bean id="proxyBasicProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalAuthBasicProcessingFilter">
    <property name="authenticationManager" ref="ldapAuthenticationManager" />
    <property name="externalDataSynchronizer" ref="externalDataSynchronizer" />

    <property name="authenticationEntryPoint">
        <ref local="basicProcessingFilterEntryPoint" />
    </property>
</bean>

<bean id="proxyAuthenticationRestProcessingFilter"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.DefaultAuthenticationRestProcessingFilter">
    <property name="authenticationManager">
        <ref local="ldapAuthenticationManager" />
    </property>
    <property name="externalDataSynchronizer">
        <ref local="externalDataSynchronizer" />
    </property>

    <property name="filterProcessesUrl" value="/rest/login" />
    <property name="invalidateSessionOnSuccessfulAuthentication"
        value="true" />
    <property name="migrateInvalidatedSessionAttributes" value="true" />
</bean>



<bean id="ldapAuthenticationManager" class="org.springframework.security.providers.ProviderManager">
    <property name="providers">
        <list>
            <ref local="ldapAuthenticationProvider" />
            <ref bean="${bean.daoAuthenticationProvider}" />
            <!--anonymousAuthenticationProvider only needed if filterInvocationInterceptor.alwaysReauthenticate 
                is set to true <ref bean="anonymousAuthenticationProvider"/> -->
        </list>
    </property>
</bean>

<bean id="ldapAuthenticationProvider"
    class="org.springframework.security.providers.ldap.LdapAuthenticationProvider">
    <constructor-arg>
        <bean
            class="org.springframework.security.providers.ldap.authenticator.BindAuthenticator">
            <constructor-arg>
                <ref local="ldapContextSource" />
            </constructor-arg>
            <property name="userSearch" ref="userSearch" />
        </bean>
    </constructor-arg>
    <constructor-arg>
        <bean
            class="org.springframework.security.ldap.populator.DefaultLdapAuthoritiesPopulator">
            <constructor-arg index="0">
                <ref local="ldapContextSource" />
            </constructor-arg>
            <constructor-arg index="1">
                <value></value>
            </constructor-arg>

            <property name="groupRoleAttribute" value="cn" />
            <property name="convertToUpperCase" value="true" />
            <property name="rolePrefix" value="ROLE_" />
            <property name="groupSearchFilter"
                value="(&amp;(member={0})(&amp;(objectCategory=Group)(objectclass=group)(cn=my-nested-group-name)))" />
            <property name="searchSubtree" value="true" />
            <!-- Can setup additional external default roles here <property name="defaultRole" 
                value="LDAP"/> -->
        </bean>
    </constructor-arg>
</bean>

<bean id="userSearch"
    class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
    <constructor-arg index="0">
        <value></value>
    </constructor-arg>
    <constructor-arg index="1">
        <value>(&amp;(sAMAccountName={0})(&amp;((objectCategory=person)(objectclass=user)(mail=*)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(memberOf:1.2.840.113556.1.4.1941:=CN=my-nested-group-name,OU=ou3,OU=ou2,OU=ou1,DC=dc3,DC=dc2,DC=dc1))))
        </value>
    </constructor-arg>
    <constructor-arg index="2">
        <ref local="ldapContextSource" />
    </constructor-arg>
    <property name="searchSubtree">
        <value>true</value>
    </property>
</bean>

<bean id="ldapContextSource"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ldap.JSLdapContextSource">
    <constructor-arg value="ldap://myhost:3268/DC=dc3,DC=dc2,DC=dc1?cn" />
    <!-- manager user name and password (may not be needed) -->
    <property name="userDn" value="CN=someuser,OU=ou4,OU=1,DC=dc3,DC=dc2,DC=dc1" />
    <property name="password" value="somepass" />
    <!--End Changes -->
</bean>
<!-- ############ LDAP authentication ############ -->

<!-- ############ JRS Synchronizer ############ -->
<bean id="externalDataSynchronizer"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.ExternalDataSynchronizerImpl">
    <property name="externalUserProcessors">
        <list>
            <ref local="externalUserSetupProcessor" />
            <!-- Example processor for creating user folder -->
            <!--<ref local="externalUserFolderProcessor"/> -->
        </list>
    </property>
</bean>

<bean id="abstractExternalProcessor"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.AbstractExternalUserProcessor"
    abstract="true">
    <property name="repositoryService" ref="${bean.repositoryService}" />
    <property name="userAuthorityService" ref="${bean.userAuthorityService}" />
    <property name="tenantService" ref="${bean.tenantService}" />
    <property name="profileAttributeService" ref="profileAttributeService" />
    <property name="objectPermissionService" ref="objectPermissionService" />
</bean>

<bean id="externalUserSetupProcessor"
    class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserSetupProcessor"
    parent="abstractExternalProcessor">
    <property name="userAuthorityService">
        <ref bean="${bean.internalUserAuthorityService}" />
    </property>
    <property name="defaultInternalRoles">
        <list>
            <value>ROLE_USER</value>
        </list>
    </property>

    <property name="organizationRoleMap">
        <map>
            <!-- Example of mapping customer roles to JRS roles -->
            <entry>
                <key>
                    <value>ROLE_MY-NESTED-GROUP-NAME</value>
                </key>
                <!-- JRS role that the <key> external role is mapped to -->
                <value>ROLE_USER</value>
            </entry>
        </map>
    </property>
</bean>

<!--bean id="externalUserFolderProcessor" class="com.jaspersoft.jasperserver.api.security.externalAuth.processors.ExternalUserFolderProcessor" 
    parent="abstractExternalProcessor"> <property name="repositoryService" ref="${bean.unsecureRepositoryService}"/> 
    </bean -->

<!-- ############ JRS Synchronizer ############ -->

make image( not background img) in div repeat?

You have use to repeat-y as style="background-repeat:repeat-y;width: 200px;" instead of style="repeat-y".

Try this inside the image tag or you can use the below css for the div

.div_backgrndimg
{
    background-repeat: repeat-y;
    background-image: url("/image/layout/lotus-dreapta.png");
    width:200px;
}

RestSharp simple complete example

Changing

RestResponse response = client.Execute(request);

to

IRestResponse response = client.Execute(request);

worked for me.