Programs & Examples On #Git bare

A bare git repository is so named because it has no working directory; it only contains files that are normally hidden away in the .git subdirectory. In other words, it maintains the history of a project, and never holds a snapshot of any given version.

How to convert a normal Git repository to a bare one?

Simply read

Pro Git Book: 4.2 Git on the Server - Getting Git on a Server

which boild down to

$ git clone --bare my_project my_project.git
Cloning into bare repository 'my_project.git'...

Then put my_project.git to the server

Which mainly is, what answer #42 tried to point out. Shurely one could reinvent the wheel ;-)

How do I create a master branch in a bare Git repository?

You don't need to use a second repository - you can do commands like git checkout and git commit on a bare repository, if only you supply a dummy work directory using the --work-tree option.

Prepare a dummy directory:

$ rm -rf /tmp/empty_directory
$ mkdir  /tmp/empty_directory

Create the master branch without a parent (works even on a completely empty repo):

$ cd your-bare-repository.git

$ git checkout --work-tree=/tmp/empty_directory --orphan master
Switched to a new branch 'master'                  <--- abort if "master" already exists

Create a commit (it can be a message-only, without adding any files, because what you need is simply having at least one commit):

$ git commit -m "Initial commit" --allow-empty --work-tree=/tmp/empty_directory 

$ git branch
* master

Clean up the directory, it is still empty.

$ rmdir  /tmp/empty_directory

Tested on git 1.9.1. (Specifically for OP, the posh-git is just a PowerShell wrapper for standard git.)

What's the -practical- difference between a Bare and non-Bare repository?

Non bare repository allows you to (into your working tree) capture changes by creating new commits.

Bare repositories are only changed by transporting changes from other repositories.

How to enter in a Docker container already running with a new TTY

With docker 1.3, there is a new command docker exec. This allows you to enter a running container:

docker exec -it [container-id] bash

How to close <img> tag properly?

Actually, only the first one is valid in HTML5

<img src='stackoverflow.png'>  

Only the last two are valid in XHTML

<img src='stackoverflow.png'></img>  
<img src='stackoverflow.png' />

(Though not stricly required, an alt attribute _usually_ should also be included).

That said, your HTML5 page will probably display as intended because browsers will rewrite or interpret your html to what it thinks you meant. That may mean it turns a tag, for example, from
<div /> into <div></div>. Or maybe it just ignores the final slash on <img ... />.
see 2016: Serve HTML5 as XHTML 5.0 for legacy validation.
see: 2011 discussion and additional links here, though over time some bits may have changed

Partly this is because browsers try very hard to error correct. Also, because there has much confusion about self-closing tags, and void tags. Finally, The spec has changed, or hasn't always been clear, and browsers try to be backwards compatible.

So, while you can probably get away with any of the three options,
only the first adheres to the HTML5 standard, and is guaranteed to pass a HTML5 validator.

A sound strategy might be to:

  • Write new code without the closing slash.
  • When re-factoring code, update nearby image tags, as you run across them.
  • Not overly worry about tags in legacy files that you do not touch, unless a particular need arises.

Here is a list of tags that should not be closed in HTML5:

 <br>    <hr>    <input>       
 <img>  <link>   <source>  
 <col>  <area>   <base>
 <meta> <embed>  <param>  
<track>  <wbr>   <keygen> (HTML 5.2 Draft removed)

React - clearing an input value after form submit

this.mainInput doesn't actually point to anything. Since you are using a controlled component (i.e. the value of the input is obtained from state) you can set to null:

onHandleSubmit(e) {
  const city =;
  this.setState({ city: '' });

How to show soft-keyboard when edittext is focused

You can try to force the soft keyboard to appear, it works for me:

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

How to disable CSS in Browser for testing purposes

While inspecting HTML with the Browser Development tool you prefer (eg Chrome Devtools) find the <head> element and delete it at all.

Notice that this will also remove js but for me it is the fastest way to get the page naked.

How to trim leading and trailing white spaces of a string?

There's a bunch of functions to trim strings in go.

See them there : Trim

Here's an example, adapted from the documentation, removing leading and trailing white spaces :

fmt.Printf("[%q]", strings.Trim(" Achtung  ", " "))

Unable to ping vmware guest from another vmware guest

On both Operation Systems, must turnoff firewall. I using MS SERVER 2012 R2 & MS WIN-7 as a client. First of all call "RUN BOX" window logo button+ R, once RUN box appeared type "firewall.cpl" at Window Firewall setting you will see "Turn Window Firewall On or Off" like this you click it & chose "turn off window firewall" on both Private and Public Setting then OK. Ping again on guests OS. GOOD-LUCK Aungkokokhant

SQL select max(date) and corresponding value

Ah yes, that is how it is intended in SQL. You get the Max of every column seperately. It seems like you want to return values from the row with the max date, so you have to select the row with the max date. I prefer to do this with a subselect, as the queries keep compact easy to read.

SELECT TrainingID, CompletedDate, Notes
FROM HR_EmployeeTrainings ET 
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID) 
AND CompletedDate in 
   (Select Max(CompletedDate) from HR_EmployeeTrainings B
    where B.TrainingID = ET.TrainingID)

If you also want to match by AntiRecID you should include that in the subselect as well.

Save Screen (program) output to a file

The 'script' command under Unix should do the trick. Just run it at the start of your new console and you should be good.

Does --disable-web-security Work In Chrome Anymore?

If you want to automate this: Kill chrome from task Manager First. In Windows - Right Click (or Shift+right click, in-case of taskbar) on Chrome Icon. Select Properties. In "Target" text-box, add --disable-web-security flag.

So text in text-box should look like

C:\Users\njadhav\AppData\Local\Google\Chrome SxS\Application\chrome.exe" --disable-web-security

Click Ok and launch chrome.

Opacity of background-color, but not the text

Use rgba!

.alpha60 {
    /* Fallback for web browsers that don't support RGBa */
    background-color: rgb(0, 0, 0);
    /* RGBa with 0.6 opacity */
    background-color: rgba(0, 0, 0, 0.6);
    /* For IE 5.5 - 7*/
    filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000);
    /* For IE 8*/
    -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#99000000, endColorstr=#99000000)";

In addition to this, you have to declare background: transparent for IE web browsers, preferably served via conditional comments or similar!


How to add property to object in PHP >= 5.3 strict mode without generating error

I don't know whether its the newer version of php, but this works. I'm using php 5.6

    class Person
       public $name;

       public function save()

   $p = new Person;
   $p->name = "Ganga";
   $p->age = 23;


This is the result. The save method actually gets the new property

    Person Object
       [name] => Ganga
       [age] => 23

Setting the correct PATH for Eclipse

Like Abob said:

Eclipse doesn't consult the JAVA_HOME variable

You should specify where Eclipse should find your JDK in the file eclipse.ini. Specifically, the following parameter (note that it is 2 separate lines in the ini file):


or wherever your javaw.exe happens to be.

Note: The format of the ini file is very particular; make sure to consult to ensure you get it exactly right.

mcrypt is deprecated, what is the alternative?

You should use OpenSSL over mcrypt as it's actively developed and maintained. It provides better security, maintainability and portability. Secondly it performs AES encryption/decryption much faster. It uses PKCS7 padding by default, but you can specify OPENSSL_ZERO_PADDING if you need it. To use with a 32-byte binary key, you can specify aes-256-cbc which is much obvious than MCRYPT_RIJNDAEL_128.

Here is the code example using Mcrypt:

Unauthenticated AES-256-CBC encryption library written in Mcrypt with PKCS7 padding.

 * This library is unsafe because it does not MAC after encrypting
class UnsafeMcryptAES

    public static function encrypt($message, $key)
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        $ivsize = mcrypt_get_iv_size(self::CIPHER);
        $iv = mcrypt_create_iv($ivsize, MCRYPT_DEV_URANDOM);

        // Add PKCS7 Padding
        $block = mcrypt_get_block_size(self::CIPHER);
        $pad = $block - (mb_strlen($message, '8bit') % $block, '8bit');
        $message .= str_repeat(chr($pad), $pad);

        $ciphertext = mcrypt_encrypt(

        return $iv . $ciphertext;

    public static function decrypt($message, $key)
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        $ivsize = mcrypt_get_iv_size(self::CIPHER);
        $iv = mb_substr($message, 0, $ivsize, '8bit');
        $ciphertext = mb_substr($message, $ivsize, null, '8bit');

        $plaintext = mcrypt_decrypt(

        $len = mb_strlen($plaintext, '8bit');
        $pad = ord($plaintext[$len - 1]);
        if ($pad <= 0 || $pad > $block) {
            // Padding error!
            return false;
        return mb_substr($plaintext, 0, $len - $pad, '8bit');

And here is the version written using OpenSSL:

 * This library is unsafe because it does not MAC after encrypting
class UnsafeOpensslAES
    const METHOD = 'aes-256-cbc';

    public static function encrypt($message, $key)
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        $ivsize = openssl_cipher_iv_length(self::METHOD);
        $iv = openssl_random_pseudo_bytes($ivsize);

        $ciphertext = openssl_encrypt(

        return $iv . $ciphertext;

    public static function decrypt($message, $key)
        if (mb_strlen($key, '8bit') !== 32) {
            throw new Exception("Needs a 256-bit key!");
        $ivsize = openssl_cipher_iv_length(self::METHOD);
        $iv = mb_substr($message, 0, $ivsize, '8bit');
        $ciphertext = mb_substr($message, $ivsize, null, '8bit');

        return openssl_decrypt(

Source: If You're Typing the Word MCRYPT Into Your PHP Code, You're Doing It Wrong.

How to resolve TypeError: Cannot convert undefined or null to object


if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged


if (obj === undefined) { return undefined;} // return undefined for undefined 
if (obj === null) { return null;} // null unchanged

How to convert color code into media.brush?

Sorry to be so late to the party! I came across a similar issue, in WinRT. I'm not sure whether you're using WPF or WinRT, but they do differ in some ways (some better than others). Hopefully this will help people across the board, whichever situation they're in.

You could always use the code from the converter class I created to re-use and do in your C# code-behind, or wherever you're using it, to be honest:

I made it with the intention that a 6-digit (RGB), or an 8-digit (ARGB) Hex value could be used either way.

So I created a converter class:

public class StringToSolidColorBrushConverter : IValueConverter
    public object Convert(object value, Type targetType, object parameter, string language)
        var hexString = (value as string).Replace("#", "");

        if (string.IsNullOrWhiteSpace(hexString)) throw new FormatException();
        if (hexString.Length != 6 || hexString.Length != 8) throw new FormatException();

            var a = hexString.Length == 8 ? hexString.Substring(0, 2) : "255";
            var r = hexString.Length == 8 ? hexString.Substring(2, 2) : hexString.Substring(0, 2);
            var g = hexString.Length == 8 ? hexString.Substring(4, 2) : hexString.Substring(2, 2);
            var b = hexString.Length == 8 ? hexString.Substring(6, 2) : hexString.Substring(4, 2);

            return new SolidColorBrush(ColorHelper.FromArgb(
                byte.Parse(a, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(r, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(g, System.Globalization.NumberStyles.HexNumber),
                byte.Parse(b, System.Globalization.NumberStyles.HexNumber)));
            throw new FormatException();

    public object ConvertBack(object value, Type targetType, object parameter, string language)
        throw new NotImplementedException();

Added it into my App.xaml:

    <converters:StringToSolidColorBrushConverter x:Key="StringToSolidColorBrushConverter" />

And used it in my View's Xaml:

    <Rectangle Fill="{Binding RectangleColour,
               Converter={StaticResource StringToSolidColorBrushConverter}}"
               Height="20" Width="20" />

Works a charm!

Side note... Unfortunately, WinRT hasn't got the System.Windows.Media.BrushConverter that H.B. suggested; so I needed another way, otherwise I would have made a VM property that returned a SolidColorBrush (or similar) from the RectangleColour string property.

"No cached version... available for offline mode."

I had same error...Please Uncheck the offline work in Settings.

File => Settings => Build, Execution, Deployment => Build Tools => Gradle => Offline Work

After Gradle Sync Finished, Please Restart Your Android Studio.

Extract text from a string

If program name is always the first thing in (), and doesn't contain other )s than the one at end, then $yourstring -match "[(][^)]+[)]" does the matching, result will be in $Matches[0]

Send multiple checkbox data to PHP via jQuery ajax()

var myCheckboxes = new Array();
$("input:checked").each(function() {

You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push

Android and setting width and height programmatically in dp units

simplest way(and even works from api 1) that tested is:


From documentations:

Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.

How to convert a string into double and vice versa?

from this example here, you can see the the conversions both ways:

NSString *str=@"5678901234567890";

long long verylong;
NSRange range;
range.length = 15;
range.location = 0;

[[NSScanner scannerWithString:[str substringWithRange:range]] scanLongLong:&verylong];

NSLog(@"long long value %lld",verylong);

What's a standard way to do a no-op in python?

If you need a function that behaves as a nop, try

nop = lambda *a, **k: None

Sometimes I do stuff like this when I'm making dependencies optional:

    import foo

# Doesn't break when foo is missing:

Problems with local variable scope. How to solve it?

Firstly, we just CAN'T make the variable final as its state may be changing during the run of the program and our decisions within the inner class override may depend on its current state.

Secondly, good object-oriented programming practice suggests using only variables/constants that are vital to the class definition as class members. This means that if the variable we are referencing within the anonymous inner class override is just a utility variable, then it should not be listed amongst the class members.

But – as of Java 8 – we have a third option, described here :

Starting in Java SE 8, if you declare the local class in a method, it can access the method's parameters.

So now we can simply put the code containing the new inner class & its method override into a private method whose parameters include the variable we call from inside the override. This static method is then called after the btnInsert declaration statement :-

 . . . .
 . . . .

 Statement statement = null;                                 

 . . . .
 . . . .

 Button btnInsert = new Button(shell, SWT.NONE);
 addMouseListener(Button btnInsert, Statement statement);    // Call new private method

 . . . 
 . . .
 . . . 

 private static void addMouseListener(Button btn, Statement st) // New private method giving access to statement 
    btn.addMouseListener(new MouseAdapter() 
      public void mouseDown(MouseEvent e) 
        String name = text.getText();
        String from = text_1.getText();
        String to = text_2.getText();
        String price = text_3.getText();
        String query = "INSERT INTO booking (name, fromst, tost,price) VALUES ('"+name+"', '"+from+"', '"+to+"', '"+price+"')";
        catch (SQLException e1) 
            e1.printStackTrace();                                    // TODO Auto-generated catch block

 . . . .
 . . . .
 . . . .

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

Output first 100 characters in a string

Slicing of arrays is done with [first:last+1].

One trick I tend to use a lot of is to indicate extra information with ellipses. So, if your field is one hundred characters, I would use:

if len(s) <= 100:
    print s
    print "%s..."%(s[:97])

And yes, I know () is superfluous in this case for the % formatting operator, it's just my style.

'adb' is not recognized as an internal or external command, operable program or batch file

If you want to use it every time add the path of adb to your system variables: enter to cmd (command prompt) and write the following:

echo %PATH%

this command will show you what it was before you will add adb path

setx PATH "%PATH%;C:\Program Files\android-sdk-windows\platform-tools"

be careful the path that you want to add if it contains double quote

after you restart your cmd rewrite:

echo %PATH%

you will find that the path is added

PS: if you just want to add the path to cmd just to this session you can use:

set PATH=%PATH%;C:\Program Files\android-sdk-windows\platform-tools

How to get First and Last record from a sql query?

select *
from {Table_Name}
where {x_column_name}=(
    select d.{x_column_name} 
    from (
        select rownum as rno,{x_column_name}
        from {Table_Name})d
        where d.rno=(
            select count(*)
            from {Table_Name}));

What is the best way to initialize a JavaScript Date to midnight?

A one-liner for object configs:

new Date(new Date().setHours(0,0,0,0));

When creating an element:

dateFieldConfig = {
      name: "mydate",
      value: new Date(new Date().setHours(0, 0, 0, 0)),

How can I add shadow to the widget in flutter?

Add box shadow to container in flutter

      margin: EdgeInsets.only(left: 30, top: 100, right: 30, bottom: 50),
      height: double.infinity,
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(10),
            topRight: Radius.circular(10),
            bottomLeft: Radius.circular(10),
            bottomRight: Radius.circular(10)
        boxShadow: [
            color: Colors.grey.withOpacity(0.5),
            spreadRadius: 5,
            blurRadius: 7,
            offset: Offset(0, 3), // changes position of shadow

Here is my output enter image description here

How to force Chrome's script debugger to reload javascript?

You can always clear a specific file by doing the following:

  1. Open Dev Tools
  2. Click on the Sources tab
  3. Find your script / image / file
  4. Check the right panel to see if your file is up to date

If not:

  1. Right click the resource in the left panel and choose 'Open Link in New Tab'
  2. Force a reload of the resource with the methods above. (See @Bishoy Hanna's example)

This is very handy if you have resources that are in frames and CTRL+F5 is not force refreshing them.

clientHeight/clientWidth returning different values on different browsers

The body element takes the available width, which is usually your browser viewport. As such, it will be different dimensions cross browser due to browser chrome borders, scrollbars, vertical space being take up by menus and whatnot...

The fact that the heights also vary, also tells me you set the body/html height to 100% through css since the height is usually dependant on elements inside the body..

Unless you set the width of the body element to a fixed value through css or it's style property, it's dimensions will as a rule, always vary cross browsers/versions and perhaps even depending on plugins you installed for the browser. Constant values in such a case is more an exception to the rule...

When you invoke .clientWidth on other elements that do not take the automatic width of the browser viewport, it will always return the elements 'width' + 'padding'. So a div with width 200 and a padding of 20 will have clientWidth = 240 (20 padding left and right).

The main reason however, why one would invoke clientWidth, is exactly due to possible expected discrepancies in results. If you know you will get a constant width and the value is known, then invoking clientWidth is redundant...

jQuery Determine if a matched class has a given id

You could also check if the id element is used by doing so:

if(typeof $(.div).attr('id') == undefined){
   //element has no id
} else {
   //element has id selector

I use this method for global dataTables and specific ordered dataTables

What is the size limit of a post request?

You can post large amount of data by setting php.ini variable: max_input_vars Default size of this variable is 1000 but if you want to sent large amount of data you have to increase the size accordingly. If you can't set the size from ini_set you have to do it through htaccess or by doing changes into php.ini file directly.

max_input_vars  2500
memory_limit    256M

How can I pass an Integer class correctly by reference?

If you change your inc() function to this

 public static Integer inc(Integer i) {
      Integer iParam = i;
      i = i+1;    // I think that this must be **sneakally** creating a new integer...  
      System.out.println(i == iParam);
      return i;

then you will see that it always prints "false". That means that the addition creates a new instance of Integer and stores it in the local variable i ("local", because i is actually a copy of the reference that was passed), leaving the variable of the calling method untouched.

Integer is an immutable class, meaning that you cannot change it's value but must obtain a new instance. In this case you don't have to do it manually like this:

i = new Integer(i+1); //actually, you would use Integer.valueOf(i.intValue()+1);

instead, it is done by autoboxing.

SimpleDateFormat and locale based format string

String text = new SimpleDateFormat("E, MMM d, yyyy").format(date);

Select last N rows from MySQL

select * from Table ORDER BY id LIMIT 30

Notes: * id should be unique. * You can control the numbers of rows returned by replacing the 30 in the query

How can I add "href" attribute to a link dynamically using JavaScript?

More actual solution:

<a id="someId">Link</a>

const a = document.querySelector('#someId');
a.href = 'url';

What is let-* in Angular 2 templates?

The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>. The let keyword declares a template input variable that you reference within the template.

Detect backspace and del on "input" event?

Use .onkeydown and cancel the removing with return false;. Like this:

var input = document.getElementById('myInput');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;

Or with jQuery, because you added a jQuery tag to your question:

jQuery(function($) {
  var input = $('#myInput');
  input.on('keydown', function() {
    var key = event.keyCode || event.charCode;

    if( key == 8 || key == 46 )
        return false;


What is the best way to insert source code examples into a Microsoft Word document?

I have tried all your methods, but they didn't work for me, in fact I have created an easier method using MS Word Tables.


  1. More beautiful
  2. Easier to manage & more consistent
  3. Are less prone to problems
  4. No need for external plugins or MS Word micro coding.
  5. Easier to handle by simple users (such as myself).

Cons: It will not maintain code colouring although someone could improve my trick.


  1. Insert a 3x3 table, in my case I always make the total width of the table equals the free page's width (3 rows minimum to test the tables style).

  2. Use invisible borders ("No Borders" option), and activate "View Gridlines" option. it should have this aspect. Be ware that those lines are for you to see the table's grid, and the will not be printed.

enter image description here

  1. Make the adjustments to cells' spacing and columns' width to get the aspect you like. (You will have to get in "Table Properties" for fine tuning). enter image description here

  2. Create a "Paragraph Style" with the name of "Code" just for your code snippets (check to get the idea, you don't have to follow all of it)

  3. Create another "Paragraph Style" with the name of "Code_numberline" that will be based upon the previous created style. enter image description here

  4. In the newly created "Code_numberline" add the numbering style that you like (this will automate line numbering). enter image description here

  5. Apply "Code_numberline" to the first column, and "Code" to the 3 column. enter image description here

  6. Add a fill in the middle column. enter image description here

  7. Save that table style and enjoy!

fast way to copy formatting in excel

For me, you can't. But if that suits your needs, you could have speed and formatting by copying the whole range at once, instead of looping:

range("B2:B5002").Copy Destination:=Sheets("Output").Cells(startrow, 2)

And, by the way, you can build a custom range string, like Range("B2:B4, B6, B11:B18")

edit: if your source is "sparse", can't you just format the destination at once when the copy is finished ?

Python memory leaks

As far as best practices, keep an eye for recursive functions. In my case I ran into issues with recursion (where there didn't need to be). A simplified example of what I was doing:

def my_function():
    # lots of memory intensive operations
    # like operating on images or huge dictionaries and lists
    my_flag = True
    if my_flag:  # restart the function if a certain flag is true

def main():

operating in this recursive manner won't trigger the garbage collection and clear out the remains of the function, so every time through memory usage is growing and growing.

My solution was to pull the recursive call out of my_function() and have main() handle when to call it again. this way the function ends naturally and cleans up after itself.

def my_function():
    # lots of memory intensive operations
    # like operating on images or huge dictionaries and lists
    my_flag = True
    return my_flag

def main():
    result = my_function()
    if result:

How can I get just the first row in a result set AFTER ordering?

An alternative way:

FROM bla
WHERE finalDate = (SELECT MAX(finalDate) FROM bla) AND
      rownum = 1

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

egyamado's answer was really helpful! You can enhance it for your particular setup with something like this:

import sublime, sublime_plugin
import webbrowser

class OpenBrowserCommand(sublime_plugin.TextCommand):
   def run(self, edit, keyPressed, localHost, pathToFiles):  
      for region in self.view.sel():  
         if not region.empty():  
            # Get the selected text  
            url = self.view.substr(region)  
            # prepend beginning of local host url 
            url = localHost + url  
            # prepend beginning of local host url 
            url = localHost + self.view.file_name()
            # replace local path to file
            url = url.replace(pathToFiles, "")

         if keyPressed == "1":
            navigator = webbrowser.get("open -a /Applications/ %s")
         if keyPressed == "2":
            navigator = webbrowser.get("open -a /Applications/Google\ %s")
         if keyPressed == "3":
            navigator = webbrowser.get("open -a /Applications/ %s")

And then in your keybindings:

{ "keys": ["alt+1"], "command": "open_browser", "args": {"keyPressed": "1", "localHost": "", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+2"], "command": "open_browser", "args": {"keyPressed": "2", "localHost": "", "pathToFiles":"/opt/local/apache2/htdocs"}},
{ "keys": ["alt+3"], "command": "open_browser", "args": {"keyPressed": "3", "localHost": "", "pathToFiles":"/opt/local/apache2/htdocs"}}

We store sample urls at the top of all our templates, so the first part allows you to highlight that sample URL and launch it in a browser. If no text is highlighted, it will simply use the file name. You can adjust the command calls in the keybindings to your localhost url and the system path to the documents you're working on.

How do I extract the contents of an rpm?

Copy the .rpm file in a separate folder then run the following command $ yourfile.rpm | cpio -idmv

Alternative to file_get_contents?

You should try something like this, I am doing this for my project, its a fallback system

//function to get the remote data
function url_get_contents ($url) {
    if (function_exists('curl_exec')){ 
        $conn = curl_init($url);
        curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($conn, CURLOPT_FRESH_CONNECT,  true);
        curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
        $url_get_contents_data = (curl_exec($conn));
        $url_get_contents_data = file_get_contents($url);
    }elseif(function_exists('fopen') && function_exists('stream_get_contents')){
        $handle = fopen ($url, "r");
        $url_get_contents_data = stream_get_contents($handle);
        $url_get_contents_data = false;
return $url_get_contents_data;

then later you can do like this

$data = url_get_contents("");
//Do Something....

remove duplicates from sql union

If you are using T-SQL you could use a temporary table in a stored procedure and update or insert the records of your query accordingly.

Reinitialize Slick js after successful ajax call

Try this code, it helped me!

  dots: true,
  arrows: false,
  setPosition: true

Convert floating point number to a certain precision, and then copy to string

In case the precision is not known until runtime, this other formatting option is useful:

>>> n = 9
>>> '%.*f' % (n, numvar)

How to find if div with specific id exists in jQuery?

Nick's answer nails it. You could also use the return value of getElementById directly as your condition, rather than comparing it to null (either way works, but I personally find this style a little more readable):

if (document.getElementById(name)) {
  alert('this record already exists');
} else {
  // do stuff

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

.state('public', {
    abstract: true,
    module: 'public'
.state('public.login', {
    url: '/login',
    module: 'public'
.state('tool', {
    abstract: true,
    module: 'private'
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module +, route.config);

  this.$get = function () {
    return {
      config: this.config

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

How do I loop through or enumerate a JavaScript object?

An object becomes an iterator when it implements the .next() method

const james = {
  name: 'James',
  height: `5'10"`,
  weight: 185,

  [Symbol.iterator]() {
    let properties = []
    for (let key of Object.keys(james)) {

    index = 0;
    return {
      next: () => {
        let key = properties[index];
        let value = this[key];
        let done = index >= properties.length - 1;
        return {


const iterator = james[Symbol.iterator]();

console.log(; // 'James'
console.log(; // `5'10`
console.log(; // 185

How do I change tab size in Vim?

:set tabstop=4
:set shiftwidth=4
:set expandtab

This will insert four spaces instead of a tab character. Spaces are a bit more “stable”, meaning that text indented with spaces will show up the same in the browser and any other application.

Short rot13 function - Python

I couldn't leave this question here with out a single statement using the modulo operator.

def rot13(s):
    return ''.join([chr(x.islower() and ((ord(x) - 84) % 26) + 97
                        or x.isupper() and ((ord(x) - 52) % 26) + 65
                        or ord(x))
                    for x in s])

This is not pythonic nor good practice, but it works!

>> rot13("Hello World!")
Uryyb Jbeyq!

How to convert InputStream to FileInputStream

You need something like:

    URL resource = this.getClass().getResource("/path/to/resource.res");
    File is = null;
    try {
        is = new File(resource.toURI());
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
    try {
        FileInputStream input = new FileInputStream(is);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block

But it will work only within your IDE, not in runnable JAR. I had same problem explained here.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

How does one parse XML files?

You can use ExtendedXmlSerializer to serialize and deserialize.

Instalation You can install ExtendedXmlSerializer from nuget or run the following command:

Install-Package ExtendedXmlSerializer


ExtendedXmlSerializer serializer = new ExtendedXmlSerializer();
var obj = new Message();
var xml = serializer.Serialize(obj);


var obj2 = serializer.Deserialize<Message>(xml);

Standard XML Serializer in .NET is very limited.

  • Does not support serialization of class with circular reference or class with interface property,
  • Does not support Dictionaries,
  • There is no mechanism for reading the old version of XML,
  • If you want create custom serializer, your class must inherit from IXmlSerializable. This means that your class will not be a POCO class,
  • Does not support IoC.

ExtendedXmlSerializer can do this and much more.

ExtendedXmlSerializer support .NET 4.5 or higher and .NET Core. You can integrate it with WebApi and AspCore.

Biggest differences of Thrift vs Protocol Buffers?

They both offer many of the same features; however, there are some differences:

  • Thrift supports 'exceptions'
  • Protocol Buffers have much better documentation/examples
  • Thrift has a builtin Set type
  • Protocol Buffers allow "extensions" - you can extend an external proto to add extra fields, while still allowing external code to operate on the values. There is no way to do this in Thrift
  • I find Protocol Buffers much easier to read

Basically, they are fairly equivalent (with Protocol Buffers slightly more efficient from what I have read).

cannot import name patterns


from django.conf.urls.defaults import ... # is for django 1.3
from django.conf.urls  import ...         # is for django 1.4

I met this problem too.

Creating a new dictionary in Python

>>> dict.fromkeys(['a','b','c'],[1,2,3])

{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

Secure FTP using Windows batch script

The built in FTP command doesn't have a facility for security. Use cUrl instead. It's scriptable, far more robust and has FTP security.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

Use This This Will work For sure

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ProtectedConfigFile {

    private static final char[] PASSWORD = "enfldsgbnlsngdlksdsgm".toCharArray();
    private static final byte[] SALT = { (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12, (byte) 0xde, (byte) 0x33,
            (byte) 0x10, (byte) 0x12, };

    public static void main(String[] args) throws Exception {
        String originalPassword = "Aman";
        System.out.println("Original password: " + originalPassword);
        String encryptedPassword = encrypt(originalPassword);
        System.out.println("Encrypted password: " + encryptedPassword);
        String decryptedPassword = decrypt(encryptedPassword);
        System.out.println("Decrypted password: " + decryptedPassword);

    private static String encrypt(String property) throws GeneralSecurityException, UnsupportedEncodingException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return base64Encode(pbeCipher.doFinal(property.getBytes("UTF-8")));

    private static String base64Encode(byte[] bytes) {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Encoder().encode(bytes);

    private static String decrypt(String property) throws GeneralSecurityException, IOException {
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
        pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
        return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");

    private static byte[] base64Decode(String property) throws IOException {
        // NB: This class is internal, and you probably should use another impl
        return new BASE64Decoder().decodeBuffer(property);


Merge two HTML table cells

Add an attribute colspan (abbriviation for 'column span') in your top cell (<td>) and set its value to 2. Your table should resembles the following;

        <td colspan = "2">
            <!-- Merged Columns -->

            <!-- Column 1 -->

            <!-- Column 2 -->

See also
     W3 official docs on HTML Tables

batch file to copy files to another location?

Batch file to copy folder is easy.

xcopy /Y C:\Source\*.* C:\NewFolder

Save the above as a batch file, and get Windows to run it on start up.

To do the same thing when folder is updated is trickier, you'll need a program that monitors the folder every x time and check for changes. You can write the program in VB/Java/whatever then schedule it to run every 30mins.

C++ error 'Undefined reference to Class::Function()'

In the definition of your Card class, a declaration for a default construction appears:

class Card
    // ...

    Card(); // <== Declaration of default constructor!

    // ...

But no corresponding definition is given. In fact, this function definition (from card.cpp):

void Card() {

Does not define a constructor, but rather a global function called Card that returns void. You probably meant to write this instead:

Card::Card() {

Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.

The same applies to your constructor accepting two arguments. This:

void Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;

Should be rewritten into this:

Card::Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;

And the same also applies for other member functions: it seems you did not add the Card:: qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.

Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp:

Card::~Card() { }

Routing HTTP Error 404.0 0x80070002

The solution suggested

  <modules runAllManagedModulesForAllRequests="true" >
    <remove name="UrlRoutingModule"/>    

works, but can degrade performance and can even cause errors, because now all registered HTTP modules run on every request, not just managed requests (e.g. .aspx). This means modules will run on every .jpg .gif .css .html .pdf etc.

A more sensible solution is to include this in your web.config:

    <remove name="UrlRoutingModule-4.0" />
    <add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="" />

Credit for his goes to Colin Farr. Check-out his post about this topic at

SQL Error: ORA-00922: missing or invalid option

The error you're getting appears to be the result of the fact that there is no underscore between "chartered" and "flight" in the table name. I assume you want something like this where the name of the table is chartered_flight.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, takeoff_at CHAR (3) NOT NULL
, destination CHAR (3) NOT NULL)

Generally, there is no benefit to declaring a column as CHAR(3) rather than VARCHAR2(3). Declaring a column as CHAR(3) doesn't force there to be three characters of (useful) data. It just tells Oracle to space-pad data with fewer than three characters to three characters. That is unlikely to be helpful if someone inadvertently enters an incorrect code. Potentially, you could declare the column as VARCHAR2(3) and then add a CHECK constraint that LENGTH(takeoff_at) = 3.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, takeoff_at CHAR (3) NOT NULL CHECK( length( takeoff_at ) = 3 )
, destination CHAR (3) NOT NULL CHECK( length( destination ) = 3 )

Since both takeoff_at and destination are airport codes, you really ought to have a separate table of valid airport codes and define foreign key constraints between the chartered_flight table and this new airport_code table. That ensures that only valid airport codes are added and makes it much easier in the future if an airport code changes.

And from a naming convention standpoint, since both takeoff_at and destination are airport codes, I would suggest that the names be complementary and indicate that fact. Something like departure_airport_code and arrival_airport_code, for example, would be much more meaningful.

How do I redirect users after submit button click?

// similar behavior as an HTTP redirect

// similar behavior as clicking on a link
window.location.href = "";

How to make URL/Phone-clickable UILabel?

extension UITapGestureRecognizer {

    func didTapAttributedTextInLabel(label: UILabel, inRange targetRange: NSRange) -> Bool {

        let layoutManager = NSLayoutManager()
        let textContainer = NSTextContainer(size:
        let textStorage = NSTextStorage(attributedString: label.attributedText!)

        // Configure layoutManager and textStorage

        // Configure textContainer
        textContainer.lineFragmentPadding = 0.0
        textContainer.lineBreakMode = label.lineBreakMode
        textContainer.maximumNumberOfLines = label.numberOfLines
        textContainer.size = label.bounds.size

        // main code
        let locationOfTouchInLabel = self.location(in: label)

        let indexOfCharacter = layoutManager.characterIndex(for: locationOfTouchInLabel, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
        let indexOfCharacterRange = NSRange(location: indexOfCharacter, length: 1)
        let indexOfCharacterRect = layoutManager.boundingRect(forGlyphRange: indexOfCharacterRange, in: textContainer)
        let deltaOffsetCharacter = indexOfCharacterRect.origin.x + indexOfCharacterRect.size.width

        if locationOfTouchInLabel.x > deltaOffsetCharacter {
            return false
        } else {
            return NSLocationInRange(indexOfCharacter, targetRange)

How to programmatically set SelectedValue of Dropdownlist when it is bound to XmlDataSource

This is working code

protected void Page_Load(object sender, EventArgs e)
            if (!Page.IsPostBack)
                    DropDownList1.DataTextField = "user_name";
                    DropDownList1.DataValueField = "user_id";
                    DropDownList1.DataSource = getData();// get the data into the list you can set it

    DropDownList1.SelectedIndex = DropDownList1.Items.IndexOf(DropDownList1.Items.FindByText("your default selected text"));

Pure CSS checkbox image replacement

If you are still looking for further more customization,

Check out the following library:


Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

creating a new list with subset of list using index in python


a = ['a', 'b', 'c', 3, 4, 'd', 6, 7, 8]

and the list of indexes is stored in

b= [0, 1, 2, 4, 6, 7, 8]

then a simple one-line solution will be

c = [a[i] for i in b]

Perl - If string contains text?

if ($string =~ m/something/) {
   # Do work

Where something is a regular expression.

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();

There is a difference between

List<string> list; 


List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

How do I make text bold in HTML?

The Markup Way:

<strong>I'm Bold!</strong> and <b>I'm Bold Too!</b>

The Styling Way:

.bold {

<span class="bold">I'm Bold!</span>



This element encloses text which should be rendered by the browser as boldface. Because the meaning of the B element defines the appearance of the content it encloses, this element is considered a "physical" markup element. As such, it doesn't convey the meaning of a semantic markup element such as strong.


Description This element brackets text which should be strongly emphasized. Stronger than the em element.

Adding form action in html in laravel

if you want to call controller from form action that time used following code:

<form action="{{ action('SchoolController@getSchool') }}"  >

Here SchoolController is a controller name and getSchool is a method name, you must use get or post before method name which should be same as in form tag.

Extract filename and extension in Bash

You can use

sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-

to get file name and

sed 's/^/./' | rev | cut -d. -f1  | rev

to get extension.

Test case:

echo "filename.gz"     | sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-
echo "filename.gz"     | sed 's/^/./' | rev | cut -d. -f1  | rev
echo "filename"        | sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-
echo "filename"        | sed 's/^/./' | rev | cut -d. -f1  | rev
echo "filename.tar.gz" | sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-
echo "filename.tar.gz" | sed 's/^/./' | rev | cut -d. -f1  | rev

Difference between javacore, thread dump and heap dump in Websphere

JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects.

JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads.

Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place. Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser.

Core dump is a os level memory usage of objects. It has more informaiton than a head dump. core dump is not created when we kill a process purposely.

How to add a second css class with a conditional value in razor MVC 4

You can add property to your model as follows:

    public string DetailsClass { get { return Details.Count > 0 ? "show" : "hide" } }

and then your view will be simpler and will contain no logic at all:

    <div class="details @Model.DetailsClass"/>

This will work even with many classes and will not render class if it is null:

    <div class="@Model.Class1 @Model.Class2"/>

with 2 not null properties will render:

    <div class="class1 class2"/>

if class1 is null

    <div class=" class2"/>

Detect Safari using jQuery

This will determine whether the browser is Safari or not.

if(navigator.userAgent.indexOf('Safari') !=-1 && navigator.userAgent.indexOf('Chrome') == -1)
    alert(its safari);
}else {
    alert('its not safari');

jquery how to catch enter key and change event to tab

I know this question is older than god, but I never saw an answer that was all that elegant.

doc.on('keydown', 'input', function(e, ui) {
    if(e.keyCode === 13){

that seems to get the job done in as few lines as humanly possible.

Eclipse C++ : "Program "g++" not found in PATH"

I had the same problem in Sublime..

  1. Right click on my computer
  2. Advanced system settings
  3. Environment variables
  4. in system variables, change path to location of '...\MinGW\bin'

Example: D:\work\sublime\MinGW\bin

Why do you need to put #!/bin/bash at the beginning of a script file?

It's called a shebang. In unix-speak, # is called sharp (like in music) or hash (like hashtags on twitter), and ! is called bang. (You can actually reference your previous shell command with !!, called bang-bang). So when put together, you get haSH-BANG, or shebang.

The part after the #! tells Unix what program to use to run it. If it isn't specified, it will try with bash (or sh, or zsh, or whatever your $SHELL variable is) but if it's there it will use that program. Plus, # is a comment in most languages, so the line gets ignored in the subsequent execution.

center a row using Bootstrap 3

you can use grid system without adding empty columns

<div class="col-xs-2 center-block" style="float:none"> ... </div>

change col-xs-2 to suit your layout.

check preview:

How to get domain URL and application name?

If you are being passed a url as a String and want to extract the context root of that application, you can use this regex to extract it. It will work for full urls or relative urls that begin with the context root.

url.replaceAll("^(.*\\/\\/)?.*?\\/(.+?)\\/.*|\\/(.+)$", "$2$3")

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

I use this:


It works for Hash and ActiveSupport::HashWithIndifferentAccess.

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

Whilst you certainly can use MySQL's IF() control flow function as demonstrated by dbemerlin's answer, I suspect it might be a little clearer to the reader (i.e. yourself, and any future developers who might pick up your code in the future) to use a CASE expression instead:

         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
         ELSE A

Of course, in this specific example it's a little wasteful to set A to itself in the ELSE clause—better entirely to filter such conditions from the UPDATE, via the WHERE clause:

         WHEN A > 0 AND A < 1 THEN 1
         WHEN A > 1 AND A < 2 THEN 2
WHERE  (A > 0 AND A < 1) OR (A > 1 AND A < 2)

(The inequalities entail A IS NOT NULL).

Or, if you want the intervals to be closed rather than open (note that this would set values of 0 to 1—if that is undesirable, one could explicitly filter such cases in the WHERE clause, or else add a higher precedence WHEN condition):

         WHEN A BETWEEN 0 AND 1 THEN 1
         WHEN A BETWEEN 1 AND 2 THEN 2

Though, as dbmerlin also pointed out, for this specific situation you could consider using CEIL() instead:


Razor Views not seeing System.Web.Mvc.HtmlHelper

My situation only occurred after I created a custom class called BaseViewPage that overrode the WebViewPage class. I initially added the following to my Main Web.confg file:

<pages pageBaseType="ZooResourceLibrary.Web.Support.BaseViewPage">

And the same to the View folders web.config file:

<pages pageBaseType="ZooResourceLibrary.Web.Support.BaseViewPage">

I tried many of the other answers and none did the trick while still allowing me to keep my BaseViewPage class. The way I fixed it was to remove the pageBaseType attribute from the Main Web.config file only. Keep it in the View web.config.

Is it possible to cast a Stream in Java 8?

I don't think there is a way to do that out-of-the-box. A possibly cleaner solution would be:

    .filter(c -> c instanceof Client)
    .map(c -> (Client) c)

or, as suggested in the comments, you could use the cast method - the former may be easier to read though:


cURL not working (Error #77) for SSL connections on CentOS for non-root users

The error is due to corrupt or missing SSL chain certificate files in the PKI directory. You’ll need to make sure the files ca-bundle, following steps: In your console/terminal:

mkdir /usr/src/ca-certificates && cd /usr/src/ca-certificates

Enter this site: , get your ca-certificate, for yout SO, for example: << CentOS. Copy url of download and paste in url: wget your_url_donwload_ca-ceritificated.rpm now, install yout rpm:

rpm2cpio your_url_donwload_ca-ceritificated.rpm | cpio -idmv

now restart your service: my example this command:

sudo service2 httpd restart

very great good look

Add rows to CSV File in powershell

Simple to me is like this:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"

"$Time,$Description"|Add-Content -Path $File # Keep no space between content variables

If you have a lot of columns, then create a variable like $NewRow like:

$Time = Get-Date -Format "yyyy-MM-dd HH:mm K"
$Description = "Done on time"
$NewRow = "$Time,$Description" # No space between variables, just use comma(,).

$NewRow | Add-Content -Path $File # Keep no space between content variables

Please note the difference between Set-Content (overwrites the existing contents) and Add-Content (appends to the existing contents) of the file.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

Declaring and initializing arrays in C

There is no such particular way in which you can initialize the array after declaring it once.

There are three options only:

1.) initialize them in different lines :

int array[SIZE];

array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 4;

But thats not what you want i guess.

2.) Initialize them using a for or while loop:

for (i = 0; i < MAX ; i++)  {
    array[i] = i;

This is the BEST WAY by the way to achieve your goal.

3.) In case your requirement is to initialize the array in one line itself, you have to define at-least an array with initialization. And then copy it to your destination array, but I think that there is no benefit of doing so, in that case you should define and initialize your array in one line itself.

And can I ask you why specifically you want to do so???

Turning multiple lines into one comma separated line

xargs -a your_file | sed 's/ /,/g'

This is a shorter way.


The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.

For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.

In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

try this too

pd.set_option("max_columns", None) # show all cols
pd.set_option('max_colwidth', None) # show full width of showing cols
pd.set_option("expand_frame_repr", False) # print cols side by side as it's supposed to be

Get DOM content of cross-domain iframe

You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you that. I'm sorry, but this is a design flaw, you should drop the idea.


Note that if you have editing access to the website loaded into the iframe, you can use postMessage (also see the browser compatibility)

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

Best way to retrieve variable values from a text file?

But what i'll love is to refer to the variable direclty, as i declared it in the python script..

Assuming you're happy to change your syntax slightly, just use python and import the "config" module.


var_a = 'home'
var_b = 'car'
var_c = 15.5

Then do

from myconfig import *

And you can reference them by name in your current context.

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

How to read a line from a text file in c/c++?

In c, you could use fopen, and getch. Usually, if you can't be exactly sure of the length of the longest line, you could allocate a large buffer (e.g. 8kb) and almost be guaranteed of getting all lines.

If there's a chance you may have really really long lines and you have to process line by line, you could malloc a resonable buffer, and use realloc to double it's size each time you get close to filling it.

#include <stdio.h>
#include <stdlib.h>

void handle_line(char *line) {
  printf("%s", line);

int main(int argc, char *argv[]) {
    int size = 1024, pos;
    int c;
    char *buffer = (char *)malloc(size);

    FILE *f = fopen("myfile.txt", "r");
    if(f) {
      do { // read all lines in file
        pos = 0;
        do{ // read one line
          c = fgetc(f);
          if(c != EOF) buffer[pos++] = (char)c;
          if(pos >= size - 1) { // increase buffer length - leave room for 0
            size *=2;
            buffer = (char*)realloc(buffer, size);
        }while(c != EOF && c != '\n');
        buffer[pos] = 0;
        // line is now in buffer
      } while(c != EOF); 
    return 0;

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

go to the phpmyadmin and open the console and execute this request


Windows 10 SSH keys

I finally got it to work by running opening command line with "Run a Administrator" even though I was already admin and could create directory manually

Align text in a table header

Try to use text-align in style attribute to align center.

<th class="not_mapped_style" style="text-align:center">DisplayName</th>

CSS: stretching background image to 100% width and height of screen?

The VH unit can be used to fill the background of the viewport, aka the browser window.


.body {
     background: url(image.jpg) no-repeat center top; 
     background-size: cover; 

Explain why constructor inject is better than other options

To make it simple, let us say that we can use constructor based dependency injection for mandatory dependencies and setter based injection for optional dependencies. It is a rule of thumb!!

Let's say for example.

If you want to instantiate a class you always do it with its constructor. So if you are using constructor based injection, the only way to instantiate the class is through that constructor. If you pass the dependency through constructor it becomes evident that it is a mandatory dependency.

On the other hand, if you have a setter method in a POJO class, you may or may not set value for your class variable using that setter method. It is completely based on your need. i.e. it is optional. So if you pass the dependency through setter method of a class it implicitly means that it is an optional dependency. Hope this is clear!!

scale Image in an UIButton to AspectFit?

1 - clear Button default text (important)

2 - set alignment like image

3 - set content mode like image

enter image description here

Google access token expiration time

Have a look at:

It says:

Other parameters included in the response include expires_in and token_type. These parameters describe the lifetime of the token in seconds...

Does Git Add have a verbose switch

For some git-commands you can specify --verbose,

git 'command' --verbose


git 'command' -v.

Make sure the switch is after the actual git command. Otherwise - it won't work!

Also useful:

git 'command' --dry-run 

(SC) DeleteService FAILED 1072

I had the same issue. After I closing and re-opening the Computer Management window the service was removed from the list. I'm running windows 7

Converting a String to DateTime

I just found an elegant way:

Convert.ChangeType("2020-12-31", typeof(DateTime));

Convert.ChangeType("2020/12/31", typeof(DateTime));

Convert.ChangeType("2020-01-01 16:00:30", typeof(DateTime));

Convert.ChangeType("2020/12/31 16:00:30", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("en-GB"));

Convert.ChangeType("11/?????/1437", typeof(DateTime), System.Globalization.CultureInfo.GetCultureInfo("ar-SA"));

Convert.ChangeType("2020-02-11T16:54:51.466+03:00", typeof(DateTime)); // format: "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffzzz"

Factorial using Recursion in Java

Your confusion, I believe, comes from the fact that you think there is only one result variable, whereas actually there is a result variable for each function call. Therefor, old results aren't replaced, but returned.


int fact(int n)
    int result;

     return 1;

   result = fact(n-1) * n;
   return result;

Assume a call to fact(2):

int result;
if ( n == 1 ) // false, go to next statement
result = fact(1) * 2; // calls fact(1):
|    int result;  //different variable
|    if ( n == 1 )  // true
|        return 1;  // this will return 1, i.e. call to fact(1) is 1
result = 1 * 2; // because fact(1) = 1
return 2;

Hope it's clearer now.

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

Yep, why not?

fs.Write(myByteArray, 0, myByteArray.Length);

How to convert a String to JsonObject using gson library

String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

I do this, and it worked.

OR, AND Operator

I'm not sure if this answers your question, but for example:

if (A || B)

if (A && B)

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Are you sure you can't just run cl.exe without any input for it to report its version?

I've just tested running cl.exe in the command prompt for VS 2008, 2005, and .NET 2003 and they all reported its version.

For 2008:

d:\Program Files\Microsoft Visual Studio 9.0\VC>cl

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86

For 2005, SP 1 (added Safe Standard C++ classes):

C:\Program Files\Microsoft Visual Studio 8\VC>cl

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86

For 2005:

C:\Program Files\Microsoft Visual Studio 8\VC>cl

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86

For .NET 2003:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.6030 for 80x86


For 2010, it will be along the line of:

Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.XX.YYYYY.ZZ for 80x86

or depending on targeted platform

Microsoft (R) C/C++ Optimizing Compiler Version 16.XX.YYYYY.ZZ for x64

For 2012:

Microsoft (R) C/C++ Optimizing Compiler Version 17.XX.YYYYY.ZZ for $$$

where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX, YYYYY, and ZZ are minor version numbers.

For 2013:

Microsoft (R) C/C++ Optimizing Compiler Version 18.XX.YYYYY.ZZ for $$$

where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX, YYYYY, and ZZ are minor version numbers.

For 2015:

Microsoft (R) C/C++ Optimizing Compiler Version 19.XX.YYYYY for $$$

where $$$ is the targeted platform (e.g. x86, x64, ARM), and XX and YYYYY are minor version numbers.

Wait 5 seconds before executing next line

This solution comes from React Native's documentation for a refresh control:

function wait(timeout) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);

To apply this to the OP's question, you could use this function in coordination with await:

await wait(5000);
if (newState == -1) {

How to drop unique in MySQL?

For MySQL 5.7.11

Step-1: First get the Unique Key

Use this query to get it:


In the last, it will be like this:



UNIQUE KEY UK_8bv559q1gobqoulqpitq0gvr6 (phoneNum)



Step-2: Remove the Unique key by this query.

ALTER TABLE User DROP INDEX UK_8bv559q1gobqoulqpitq0gvr6;

Step-3: Check the table info, by this query:

DESC User;

This should show that the index is removed

Thats All.

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data


Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
    Set acc = Nothing
End Sub

RegEx for matching "A-Z, a-z, 0-9, _" and "."


From beginning until the end of the string, match one or more of these characters.


Note that ^ and $ match the beginning and the end of a line. When multiline is enabled, this can mean that one line matches, but not the complete string.

Use \A for the beginning of the string, and \z for the end.

See for example:

How to concatenate int values in java?

Others have pointed out that multiplying b by 1000 shouldn't cause a problem - but if a were zero, you'd end up losing it. (You'd get a 4 digit string instead of 5.)

Here's an alternative (general purpose) approach - which assumes that all the values are in the range 0-9. (You should quite possibly put in some code to throw an exception if that turns out not to be true, but I've left it out here for simplicity.)

public static String concatenateDigits(int... digits)
    char[] chars = new char[digits.length];
    for (int i = 0; i < digits.length; i++)
        chars[i] = (char)(digits[i] + '0');
    return new String(chars);

In this case you'd call it with:

String result = concatenateDigits(a, b, c, d, e);

How to use document.getElementByName and getElementByTag?

  1. The getElementsByName() method accesses all elements with the specified name. this method returns collection of elements that is an array.
  2. The getElementsByTagName() method accesses all elements with the specified tagname. this method returns collection of elements that is an array.
  3. Accesses the first element with the specified id. this method returns only a single element.


<script type="text/javascript">
    function getElements() {
        var x=document.getElementById("y");
    <input name="x" id="y" type="text" size="20" /><br />

This will return a single HTML element and display the value attribute of it.

<script type="text/javascript">
    function getElements() {
        var x=document.getElementsByName("x");
    <input name="x" id="y" type="text" size="20" /><br />
    <input name="x" id="y" type="text" size="20" /><br />

this will return an array of HTML elements and number of elements that match the name attribute.

Extracted from w3schools.

List<T> OrderBy Alphabetical Order

This is a generic sorter. Called with the switch below.

dvm.PagePermissions is a property on my ViewModel of type List T in this case T is a EF6 model class called page_permission.

dvm.UserNameSortDir is a string property on the viewmodel that holds the next sort direction. The one that is actaully used in the view.

switch (sortColumn)
    case "user_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.user_name, ref sortDir);
        dvm.UserNameSortDir = sortDir;
    case "role_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.role_name, ref sortDir);
        dvm.RoleNameSortDir = sortDir;
    case "page_name":
        dvm.PagePermissions = Sort(dvm.PagePermissions, p => p.page_name, ref sortDir);
        dvm.PageNameSortDir = sortDir;

public List<T> Sort<T,TKey>(List<T> list, Func<T, TKey> sorter, ref string direction)
        if (direction == "asc")
            list = list.OrderBy(sorter).ToList();
            direction = "desc";
            list = list.OrderByDescending(sorter).ToList();
            direction = "asc";
        return list;

C++ equivalent of java's instanceof

#include <iostream.h>

template<class T>
void fun(T a)
  if(typeid(T) == typeid(int))
     //Do something
  else if(typeid(T) == typeid(float))
     //Do Something else

void main()

Capturing console output from a .NET application (C#)

This can be quite easily achieved using the ProcessStartInfo.RedirectStandardOutput property. A full sample is contained in the linked MSDN documentation; the only caveat is that you may have to redirect the standard error stream as well to see all output of your application.

Process compiler = new Process();
compiler.StartInfo.FileName = "csc.exe";
compiler.StartInfo.Arguments = "/r:System.dll /out:sample.exe stdstr.cs";
compiler.StartInfo.UseShellExecute = false;
compiler.StartInfo.RedirectStandardOutput = true;



How do I return a proper success/error message for JQuery .ajax() using PHP?

In order to build an AJAX webservice, you need TWO files :

  • A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
  • A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)

So, first you call your webservice using this JQuery syntax, in the JavaScript file :

     url : 'mywebservice.php',
     type : 'POST',
     data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
     dataType : 'json',
     success: function (data) {
          alert("The file is "+data.fichierZIP);
     error: function(data) {
          var responseText=JSON.parse(data.responseText);
          alert("Error(s) while building the ZIP file:\n"+responseText.messages);

Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:

    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
    //$errors is a string that may contain an error message while preparing the ZIP file
    //In the end, I check if there has been an error, and if so, I return an error object

    if ($errors==''){
        //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
        header('Content-Type: application/json; charset=UTF-8');
        $result['ZIPFILENAME'] = basename($filename); 
        print json_encode($result);
    } else {
        //if there is an error, you should return a special header, followed by another JSON object
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        $result['messages'] = $errors;
        //feel free to add other information like $result['errorcode']

How to use comparison operators like >, =, < on BigDecimal

Here is an example for all six boolean comparison operators (<, ==, >, >=, !=, <=):

BigDecimal big10 = new BigDecimal(10);
BigDecimal big20 = new BigDecimal(20);

System.out.println(big10.compareTo(big20) < -1);  // false
System.out.println(big10.compareTo(big20) <= -1); // true
System.out.println(big10.compareTo(big20) == -1); // true
System.out.println(big10.compareTo(big20) >= -1); // true
System.out.println(big10.compareTo(big20) > -1);  // false
System.out.println(big10.compareTo(big20) != -1); // false

System.out.println(big10.compareTo(big20) < 0);   // true
System.out.println(big10.compareTo(big20) <= 0);  // true
System.out.println(big10.compareTo(big20) == 0);  // false
System.out.println(big10.compareTo(big20) >= 0);  // false
System.out.println(big10.compareTo(big20) > 0);   // false
System.out.println(big10.compareTo(big20) != 0);  // true

System.out.println(big10.compareTo(big20) < 1);   // true
System.out.println(big10.compareTo(big20) <= 1);  // true
System.out.println(big10.compareTo(big20) == 1);  // false
System.out.println(big10.compareTo(big20) >= 1);  // false
System.out.println(big10.compareTo(big20) > 1);   // false
System.out.println(big10.compareTo(big20) != 1);  // true

How to merge 2 JSON objects from 2 files using jq?

Here's a version that works recursively (using *) on an arbitrary number of objects:

echo '{"A": {"a": 1}}' '{"A": {"b": 2}}' '{"B": 3}' |\
  jq --slurp 'reduce .[] as $item ({}; . * $item)'

  "A": {
    "a": 1,
    "b": 2
  "B": 3

How to limit file upload type file size in PHP?

If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:

`upload_max_filesize = 2M` `post_max_size = 2M`

that will set the maximum upload limit to 2 MB

Android error while retrieving information from server 'RPC:s-5:AEC-0' in Google Play?

There's no need to remove an account: I switched Google Play to a second Google account, installed an update, and switched back to my original account.

Though apparently, it's sufficient to just switch to a second Google Account, and switch back to the original account, no need to install an update.

How to replace multiple substrings of a string?

You could just make a nice little looping function.

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

where text is the complete string and dic is a dictionary — each definition is a string that will replace a match to the term.

Note: in Python 3, iteritems() has been replaced with items()

Careful: Python dictionaries don't have a reliable order for iteration. This solution only solves your problem if:

  • order of replacements is irrelevant
  • it's ok for a replacement to change the results of previous replacements

Update: The above statement related to ordering of insertion does not apply to Python versions greater than or equal to 3.6, as standard dicts were changed to use insertion ordering for iteration.

For instance:

d = { "cat": "dog", "dog": "pig"}
my_sentence = "This is my cat and this is my dog."
replace_all(my_sentence, d)

Possible output #1:

"This is my pig and this is my pig."

Possible output #2

"This is my dog and this is my pig."

One possible fix is to use an OrderedDict.

from collections import OrderedDict
def replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text
od = OrderedDict([("cat", "dog"), ("dog", "pig")])
my_sentence = "This is my cat and this is my dog."
replace_all(my_sentence, od)


"This is my pig and this is my pig."

Careful #2: Inefficient if your text string is too big or there are many pairs in the dictionary.

Create Test Class in IntelliJ

Use @Test annotation on one of the test methods or annotate your test class with @RunWith(JMockit.class) if using jmock. Intellij should identify that as test class & enable navigation. Also make sure junit plugin is enabled.

Center Triangle at Bottom of Div

You can use following css to make an element middle aligned styled with position: absolute:

.element {
  transform: translateX(-50%);
  position: absolute;
  left: 50%;

With CSS having only left: 50% we will have following effect:

Image with left: 50% property only

While combining left: 50% with transform: translate(-50%) we will have following:

Image with transform: translate(-50%) as well

.hero {  _x000D_
  background-color: #e15915;_x000D_
  position: relative;_x000D_
  height: 320px;_x000D_
  width: 100%;_x000D_
.hero:after {_x000D_
  border-right: solid 50px transparent;_x000D_
  border-left: solid 50px transparent;_x000D_
  border-top: solid 50px #e15915;_x000D_
  transform: translateX(-50%);_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
  content: '';_x000D_
  top: 100%;_x000D_
  left: 50%;_x000D_
  height: 0;_x000D_
  width: 0;_x000D_
<div class="hero">_x000D_

Gitignore not working

@Ahmad's answer is working but if you just want to git ignore 1 specific file or few files do as @Nicolas suggests

step 1

add filename to .gitignore file

step 2

[remove filename (file path) from git cache

git rm --cached filename

setp 3

commit changes git add filename

git commit -m "add filename to .gitignore"

it will keep your git history clean because if you do git rm -r --cached . and add back all and commit them it will pollute your git history (it will show that you add a lot of files at one commit) not sure am I expressing my thought right but hope you get the point

Android open pdf file

As of API 24, sending a file:// URI to another app will throw a FileUriExposedException. Instead, use FileProvider to send a content:// URI:

public File getFile(Context context, String fileName) {
    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        return null;

    File storageDir = context.getExternalFilesDir(null);
    return new File(storageDir, fileName);

public Uri getFileUri(Context context, String fileName) {
    File file = getFile(context, fileName);
    return FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".provider", file);

You must also define the FileProvider in your manifest:

        android:resource="@xml/file_paths" />

Example file_paths.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="">
    <external-files-path name="name" path="path" />

Replace "name" and "path" as appropriate.

To give the PDF viewer access to the file, you also have to add the FLAG_GRANT_READ_URI_PERMISSION flag to the intent:

private void displayPdf(String fileName) {
    Uri uri = getFileUri(this, fileName);

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(uri, "application/pdf");

    // FLAG_GRANT_READ_URI_PERMISSION is needed on API 24+ so the activity opening the file can read it

    if (intent.resolveActivity(getPackageManager()) == null) {
        // Show an error
    } else {

See the FileProvider documentation for more details.

Deploy a project using Git push

Update: I'm now using Lloyd Moore solution with the key agent ssh -A .... Pushing to a main repo and then pulling from it in parallel from all your machines is a bit faster and requires less setup on those machines.

Not seeing this solution here. just push via ssh if git is installed on the server.

You'll need the following entry in your local .git/config

[remote "amazon"]
    url = amazon:/path/to/project.git
    fetch = +refs/heads/*:refs/remotes/amazon/*

But hey, whats that with amazon:? In your local ~/.ssh/config you'll need to add the following entry:

Host amazon
    Hostname <YOUR_IP>
    User <USER>
    IdentityFile ~/.ssh/amazon-private-key

now you can call

git push amazon master
ssh <USER>@<YOUR_IP> 'cd /path/to/project && git pull'

(BTW: /path/to/project.git is different to the actual working directory /path/to/project)

"You may need an appropriate loader to handle this file type" with Webpack and Babel

In my case, I had such error since import path was wrong:

Wrong: import Select from "react-select/src/Select"; // it was auto-generated by IDE ;)

Correct: import Select from "react-select";

Get the Id of current table row with Jquery

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<script type="text/javascript"><!--

function getVal(e) {
    var targ;
    if (!e) var e = window.event;
    if ( targ =;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;


onload = function() {
    var t = document.getElementById("main").getElementsByTagName("td");
    for ( var i = 0; i < t.length; i++ )
        t[i].onclick = getVal;



<table id="main"><tr>


UITableView example for Swift

The example below is an adaptation and simplification of a longer post from We ? Swift. This is what it will look like:

enter image description here

Create a New Project

It can be just the usual Single View Application.

Add the Code

Replace the ViewController.swift code with the following:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    // Data model: These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"
    // don't forget to hook this up from the storyboard
    @IBOutlet var tableView: UITableView!
    override func viewDidLoad() {
        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        // (optional) include this line if you want to remove the extra empty cell divider lines
        // self.tableView.tableFooterView = UIView()

        // This view controller itself will provide the delegate methods and row data for the table view.
        tableView.delegate = self
        tableView.dataSource = self
    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // create a new cell if needed or reuse an old one
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        // set the text from the data model
        cell.textLabel?.text = self.animals[indexPath.row]
        return cell
    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")

Read the in-code comments to see what is happening. The highlights are

  • The view controller adopts the UITableViewDelegate and UITableViewDataSource protocols.
  • The numberOfRowsInSection method determines how many rows there will be in the table view.
  • The cellForRowAtIndexPath method sets up each row.
  • The didSelectRowAtIndexPath method is called every time a row is tapped.

Add a Table View to the Storyboard

Drag a UITableView onto your View Controller. Use auto layout to pin the four sides.

enter image description here

Hook up the Outlets

Control drag from the Table View in IB to the tableView outlet in the code.


That's all. You should be able run your app now.

This answer was tested with Xcode 9 and Swift 4


Row Deletion

You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.

enter image description here

Row Spacing

If you would like to have spacing between your rows, see this supplemental example.

enter image description here

Custom cells

The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.

enter image description here

Dynamic Cell Height

Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.

enter image description here

Further Reading

How to create duplicate table with new name in SQL Server 2008

In SSMS right click on a desired table > script as > create to > new query
-change the name of the table (ex. table2)
-change the PK key for the table (ex. PK_table2)



CREATE TABLE [dbo].[table_2](
[id] [int] NOT NULL,
[name] [varchar](50) NULL,
[reference] ASC

Referring to a Column Alias in a WHERE Clause

You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;

DBFiddle Demo


  • single definition of expression(easier to maintain/no need of copying-paste)
  • no need for wrapping entire query with CTE/outerquery
  • possibility to refer in WHERE/GROUP BY/ORDER BY
  • possible better performance(single execution)

Change key pair for ec2 instance

I noticed that when managed by Elastic Beanstalk, you can change your active EC2 key pair. Under Elastic Beanstalk > Configuration > Security, choose the new key from the EC2 key pair drop-down. You'll see this message asking if you're sure:

EC2KeyName: Changes to option EC2KeyName settings will not take effect immediately. Each of your existing EC2 instances will be replaced and your new settings will take effect then.

My instance was already terminated when I did this. It then started, terminated, and started again. Apparently "replacing" means terminating and creating a new instance. If you've modified your boot volume, create an AMI first, then specify that AMI in the same Elastic Beanstalk > Configuration > Instances form as the Custom AMI ID. This also warns about replacing the EC2 instances.

After you've modified your EC2 key pair and Custom AMI ID, and after seeing warnings about both, click Save to continue.

Remember that the IP address changes when the instance is re-created so you'll need to retrieve a new IP address from the EC2 console to use when connecting via SSH.

Hiding user input on terminal in Linux script

for a solution that works without bash or certain features from read you can use stty to disable echo

stty_orig=$(stty -g)
stty -echo
read password
stty $stty_orig

What is sharding and why is it important?

Sharding is just another name for "horizontal partitioning" of a database. You might want to search for that term to get it clearer.

From Wikipedia:

Horizontal partitioning is a design principle whereby rows of a database table are held separately, rather than splitting by columns (as for normalization). Each partition forms part of a shard, which may in turn be located on a separate database server or physical location. The advantage is the number of rows in each table is reduced (this reduces index size, thus improves search performance). If the sharding is based on some real-world aspect of the data (e.g. European customers vs. American customers) then it may be possible to infer the appropriate shard membership easily and automatically, and query only the relevant shard.

Some more information about sharding:

Firstly, each database server is identical, having the same table structure. Secondly, the data records are logically split up in a sharded database. Unlike the partitioned database, each complete data record exists in only one shard (unless there's mirroring for backup/redundancy) with all CRUD operations performed just in that database. You may not like the terminology used, but this does represent a different way of organizing a logical database into smaller parts.

Update: You wont break MVC. The work of determining the correct shard where to store the data would be transparently done by your data access layer. There you would have to determine the correct shard based on the criteria which you used to shard your database. (As you have to manually shard the database into some different shards based on some concrete aspects of your application.) Then you have to take care when loading and storing the data from/into the database to use the correct shard.

Maybe this example with Java code makes it somewhat clearer (it's about the Hibernate Shards project), how this would work in a real world scenario.

To address the "why sharding": It's mainly only for very large scale applications, with lots of data. First, it helps minimizing response times for database queries. Second, you can use more cheaper, "lower-end" machines to host your data on, instead of one big server, which might not suffice anymore.

python: how to send mail with TO, CC and BCC?

Email headers don't matter to the smtp server. Just add the CC and BCC recipients to the toaddrs when you send your email. For CC, add them to the CC header.

toaddr = '[email protected]'
cc = ['[email protected]','[email protected]']
bcc = ['[email protected]']
fromaddr = '[email protected]'
message_subject = "disturbance in sector 7"
message_text = "Three are dead in an attack in the sewers below sector 7."
message = "From: %s\r\n" % fromaddr
        + "To: %s\r\n" % toaddr
        + "CC: %s\r\n" % ",".join(cc)
        + "Subject: %s\r\n" % message_subject
        + "\r\n" 
        + message_text
toaddrs = [toaddr] + cc + bcc
server = smtplib.SMTP('')
server.sendmail(fromaddr, toaddrs, message)

To check if string contains particular word

Solution-1: - If you want to search for a combination of characters or an independent word from a sentence.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".*Beneficent.*")) {return true;}
else{return false;}

Solution-2: - There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word. For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true. For this remember to add space in your regular expression.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".* cent .*")) {return true;}
else{return false;}

Now in Solution-2 it wll return false because no independent cent word exist.

Additional: You can add or remove space on either side in 2nd solution according to your requirements.

Convert a numpy.ndarray to string(or bytes) and convert it back to numpy.ndarray

I know, I am late but here is the correct way of doing it. using base64. This technique will convert the array to string.

import base64
import numpy as np
random_array = np.random.randn(32,32)
string_repr = base64.binascii.b2a_base64(random_array).decode("ascii")
array = np.frombuffer(base64.binascii.a2b_base64(string_repr.encode("ascii"))) 

For array to string

Convert binary data to a line of ASCII characters in base64 coding and decode to ASCII to get string repr.

For string to array

First, encode the string in ASCII format then Convert a block of base64 data back to binary and return the binary data.

Post request in Laravel - Error - 419 Sorry, your session/ 419 your page has expired

Just to put it out there, i had the same problems. On my local homestead it would work as expected but after pushing it to the development server i got the session timeout message as well. Figuring its a environment issue i changed from apache to nginx and that miraculously made the problem go away.

JavaScript array to CSV

If your data contains any newlines or commas, you will need to escape those first:

const escape = text =>
    text.replace(/\\/g, "\\\\")
        .replace(/\n/g, "\\n")
        .replace(/,/g, "\\,")

escaped_array = =>

Then simply do:

csv = => fields.join(","))

If you want to make it downloadable in-browser:

dl = "data:text/csv;charset=utf-8," + csv

Should I initialize variable within constructor or outside constructor

I tend to use the second one to avoid a complicated constructor (or a useless one), also I don't really consider this as an initialization (even if it is an initialization), but more like giving a default value.

For example in your second snippet, you can remove the constructor and have a clearer code.

PHP preg_match - only allow alphanumeric strings and - _ characters

if(!preg_match('/^[\w-]+$/', $string1)) {
   echo "String 1 not acceptable acceptable";
   // String2 acceptable

How to make git mark a deleted and a new file as a file move?

The other answers already cover that you can simply git add NEW && git rm OLD in order to make git recognize the move.

However, if you have already modified the file in the working directory, the add+rm approach will add the modifications to the index, which may be undesired in some cases (e.g. in case of substantial modifications, git might not recognize anymore that it is a file rename).

Let's assume you want to add the rename to the index, but not any modifications. The obvious way to achieve this, is to do a back and forth rename mv NEW OLD && git mv OLD NEW.

But there is also a (slighty more complicated) way to do this directly in the index without renaming the file in the working tree:

info=$(git ls-files -s -- "OLD" | cut -d' ' -f-2 | tr ' ' ,)
git update-index --add --cacheinfo "$info,NEW" &&
git rm --cached "$old"

This can also be put as an alias in your ~/.gitconfig:

    mv-index = "!f() { \
      old=\"$1\"; \
      new=\"$2\"; \
      info=$(git ls-files -s -- \"$old\" | cut -d' ' -f-2 | tr ' ' ,); \
      git update-index --add --cacheinfo \"$info,$new\" && \
      git rm --cached \"$old\"; \
    }; f"

how to overwrite css style

Using !important is not recommended but in this situation I think you should -

Write this in your internal CSS -

.flex-control-thumbs li {
  width: auto !important;
  float: none !important;

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

What's the best way to join on the same table twice?

The first method is the proper approach and will do what you need. However, with the inner joins, you will only select rows from Table1 if both phone numbers exist in Table2. You may want to do a LEFT JOIN so that all rows from Table1 are selected. If the phone numbers don't match, then the SomeOtherFields would be null. If you want to make sure you have at least one matching phone number you could then do WHERE t2.PhoneNumber IS NOT NULL OR t3.PhoneNumber IS NOT NULL

The second method could have a problem: what happens if Table2 has both PhoneNumber1 and PhoneNumber2? Which row will be selected? Depending on your data, foreign keys, etc. this may or may not be a problem.

How to drop all user tables?

The easiest way would be to drop the tablespace then build the tablespace back up. But I'd rather not have to do that. This is similar to Henry's except that I just do a copy/paste on the resultset in my gui.

     ELSE ';'
 FROM user_objects

eclipse won't start - no java virtual machine was found


check if you have both java 32 and 64 bit install then

Setting Path on Windows

Windows 8

Drag the Mouse pointer to the Right bottom corner of the screen

Click on the Search icon and type: Control Panel

Click on -> Control Panel -> System -> Advanced

Click on Environment Variables, under System Variables, find PATH, and click on it.

In the Edit windows, modify PATH by adding the location of the class to the value for PATH, Or simply make sure that the variable name is in ALL CAPS

If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.

Close the window.

Reopen Command prompt window, and run your java code.

SQL Query to find missing rows between two related tables






Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Doctrine2: Best way to handle many-to-many with extra columns in reference table

This really useful example. It lacks in the documentation doctrine 2.

Very thank you.

For the proxies functions can be done :

class AlbumTrack extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {} 

class TrackAlbum extends AlbumTrackAbstract {
   ... proxy method.
   function getTitle() {}

class AlbumTrackAbstract {
   private $id;


/** @OneToMany(targetEntity="TrackAlbum", mappedBy="album") */
protected $tracklist;

/** @OneToMany(targetEntity="AlbumTrack", mappedBy="track") */
protected $albumsFeaturingThisTrack;

Convert JSONArray to String Array

Bit late for an answer, but here's what I came up with using Gson:

for a jsonarray foo: [{"test": "bar"}, {"test": "bar2"}]

JsonArray foo = getJsonFromWherever();
String[] test = new String[foo.size()]
foo.forEach(x -> {test = ArrayUtils.add(test, x.get("test").getAsString());});

Is there an easy way to strike through text in an app widget?

I tried few options but, this works best for me:

String text = "<strike><font color=\'#757575\'>Some text</font></strike>";


Creating .pem file for APNS?


  1. Create a CSR Using Key Chain Access
  2. Create a P12 Using Key Chain Access using private key
  3. APNS App ID and certificate

This gives you three files:

  • The CSR
  • The private key as a p12 file (PushChatKey.p12)
  • The SSL certificate, aps_development.cer

Go to the folder where you downloaded the files, in my case the Desktop:

$ cd ~/Desktop/

Convert the .cer file into a .pem file:

$ openssl x509 -in aps_development.cer -inform der -out PushChatCert.pem

Convert the private key’s .p12 file into a .pem file:

$ openssl pkcs12 -nocerts -out PushChatKey.pem -in PushChatKey.p12

Enter Import Password:

MAC verified OK Enter PEM pass phrase: Verifying - Enter PEM pass phrase:

You first need to enter the passphrase for the .p12 file so that openssl can read it. Then you need to enter a new passphrase that will be used to encrypt the PEM file. Again for this tutorial I used “pushchat” as the PEM passphrase. You should choose something more secure. Note: if you don’t enter a PEM passphrase, openssl will not give an error message but the generated .pem file will not have the private key in it.

Finally, combine the certificate and key into a single .pem file:

$ cat PushChatCert.pem PushChatKey.pem > ck.pem

PyCharm error: 'No Module' when trying to import own module (python script)

The key confusing step that must be done is to recreate the run configuration for the source file that you're trying to execute, so that the IDE picks up the new paths.

The way that actually worked for me was to go to Run/Edit Configurations..., select the configuration for the file that you're trying to run on the left side, uncheck the "Add source roots to PYTHONPATH" box, save, and then go back and check the box and save. THEN it would work.

Program to find largest and smallest among 5 numbers without using array

Works for any number of numbers taken from standard input:

#include <algorithm>
#include <iterator>
#include <iostream>

int main()
    std::istream_iterator<int> it_begin(std::cin), it_end;
    auto p = std::minmax_element(it_begin, it_end);
    if (p.first != it_end)
        std::cout << "min: " << *p.first << " max: " << *p.second;

Technicaly, this isn't required to work by C++ standard. The minimum iterator category required for minmax_element is ForwardIterator which stream iterators are not. Once an input iterator is dereferenced or incremented, its copies are no longer guaranteed to be dereferenceable or comparable to other iterators. It Works On My MachineTM. :)

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

How to get Last record from Sqlite?

If you have already got the cursor, then this is how you may get the last record from cursor:

cursor.moveToPosition(cursor.getCount() - 1);
//then use cursor to read values

How can I get the current class of a div with jQuery?

<div  id="my_id" class="my_class"></div>

if that is the first div then address it like so:

document.write("div CSS class: " + document.getElementsByTagName('div')[0].className);

alternatively do this:

document.write("alternative way: " + document.getElementById('my_id').className);

It yields the following results:

div CSS class: my_class
alternative way: my_class

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

Following @GregaKešpret you can make an infix operator:

`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x

Batch file to perform start, run, %TEMP% and delete all

@echo off    
del /s /f /q %windir%\temp\*.*    
rd /s /q %windir%\temp    
md %windir%\temp    
del /s /f /q %windir%\Prefetch\*.*    
rd /s /q %windir%\Prefetch    
md %windir%\Prefetch    
del /s /f /q %windir%\system32\dllcache\*.*    
rd /s /q %windir%\system32\dllcache    
md %windir%\system32\dllcache    
del /s /f /q "%SysteDrive%\Temp"\*.*    
rd /s /q "%SysteDrive%\Temp"    
md "%SysteDrive%\Temp"    
del /s /f /q %temp%\*.*    
rd /s /q %temp%    
md %temp%    
del /s /f /q "%USERPROFILE%\Local Settings\History"\*.*    
rd /s /q "%USERPROFILE%\Local Settings\History"    
md "%USERPROFILE%\Local Settings\History"    
del /s /f /q "%USERPROFILE%\Local Settings\Temporary Internet Files"\*.*    
rd /s /q "%USERPROFILE%\Local Settings\Temporary Internet Files"    
md "%USERPROFILE%\Local Settings\Temporary Internet Files"    
del /s /f /q "%USERPROFILE%\Local Settings\Temp"\*.*    
rd /s /q "%USERPROFILE%\Local Settings\Temp"    
md "%USERPROFILE%\Local Settings\Temp"    
del /s /f /q "%USERPROFILE%\Recent"\*.*    
rd /s /q "%USERPROFILE%\Recent"    
md "%USERPROFILE%\Recent"    
del /s /f /q "%USERPROFILE%\Cookies"\*.*    
rd /s /q "%USERPROFILE%\Cookies"    
md "%USERPROFILE%\Cookies"

Stop Chrome Caching My JS Files

A few ideas:

  1. When you refresh your page in Chrome, do a CTRL+F5 to do a full refresh.
  2. Even if you set the expires to 0, it will still cache during the session. You'll have to close and re-open your browser again.
  3. Make sure when you save the files on the server, the timestamps are getting updated. Chrome will first issue a HEAD command instead of a full GET to see if it needs to download the full file again, and the server uses the timestamp to see.

If you want to disable caching on your server, you can do something like:

Header set Expires "Thu, 19 Nov 1981 08:52:00 GM"
Header set Cache-Control "no-store, no-cache, must-revalidate, post-check=0, pre-check=0"
Header set Pragma "no-cache"

In .htaccess

How to parse a JSON string into JsonNode in Jackson?

You need to use an ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getJsonFactory(); // since 2.1 use mapper.getFactory() instead
JsonParser jp = factory.createJsonParser("{\"k1\":\"v1\"}");
JsonNode actualObj = mapper.readTree(jp);

Further documentation about creating parsers can be found here.

Passing data between different controller action methods

HTTP and redirects

Let's first recap how ASP.NET MVC works:

  1. When an HTTP request comes in, it is matched against a set of routes. If a route matches the request, the controller action corresponding to the route will be invoked.
  2. Before invoking the action method, ASP.NET MVC performs model binding. Model binding is the process of mapping the content of the HTTP request, which is basically just text, to the strongly typed arguments of your action method

Let's also remind ourselves what a redirect is:

An HTTP redirect is a response that the webserver can send to the client, telling the client to look for the requested content under a different URL. The new URL is contained in a Location header that the webserver returns to the client. In ASP.NET MVC, you do an HTTP redirect by returning a RedirectResult from an action.

Passing data

If you were just passing simple values like strings and/or integers, you could pass them as query parameters in the URL in the Location header. This is what would happen if you used something like

return RedirectToAction("ActionName", "Controller", new { arg = updatedResultsDocument });

as others have suggested

The reason that this will not work is that the XDocument is a potentially very complex object. There is no straightforward way for the ASP.NET MVC framework to serialize the document into something that will fit in a URL and then model bind from the URL value back to your XDocument action parameter.

In general, passing the document to the client in order for the client to pass it back to the server on the next request, is a very brittle procedure: it would require all sorts of serialisation and deserialisation and all sorts of things could go wrong. If the document is large, it might also be a substantial waste of bandwidth and might severely impact the performance of your application.

Instead, what you want to do is keep the document around on the server and pass an identifier back to the client. The client then passes the identifier along with the next request and the server retrieves the document using this identifier.

Storing data for retrieval on the next request

So, the question now becomes, where does the server store the document in the meantime? Well, that is for you to decide and the best choice will depend upon your particular scenario. If this document needs to be available in the long run, you may want to store it on disk or in a database. If it contains only transient information, keeping it in the webserver's memory, in the ASP.NET cache or the Session (or TempData, which is more or less the same as the Session in the end) may be the right solution. Either way, you store the document under a key that will allow you to retrieve the document later:

int documentId = _myDocumentRepository.Save(updatedResultsDocument);

and then you return that key to the client:

return RedirectToAction("UpdateConfirmation", "ApplicationPoolController ", new { id = documentId });

When you want to retrieve the document, you simply fetch it based on the key:

 public ActionResult UpdateConfirmation(int id)
      XDocument doc = _myDocumentRepository.GetById(id);

      ConfirmationModel model = new ConfirmationModel(doc);

      return View(model);

No converter found capable of converting from type to type

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {

    @Query("select new package.DeadlineType(, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {

    String getId();

    String getText();


Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();

how to print a string to console in c++

yes it's possible to print a string to the console.

#include "stdafx.h"
#include <string>
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
    string strMytestString("hello world");
    cout << strMytestString;
    return 0;

stdafx.h isn't pertinent to the solution, everything else is.

Push commits to another branch

when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.

git push origin master:demo

A html space is showing as %2520 instead of %20

The following code snippet resolved my issue. Thought this might be useful to others.

var strEnc = this.$.txtSearch.value.replace(/\s/g, "-");_x000D_
strEnc = strEnc.replace(/-/g, " ");

Rather using default encodeURIComponent my first line of code is converting all spaces into hyphens using regex pattern /\s\g and the following line just does the reverse, i.e. converts all hyphens back to spaces using another regex pattern /-/g. Here /g is actually responsible for finding all matching characters.

When I am sending this value to my Ajax call, it traverses as normal spaces or simply %20 and thus gets rid of double-encoding.

How do I include a JavaScript file in another JavaScript file?

Yes, there is...

Keep reading. In ES6, we can export and import part or whole JavaScript file into another one...

But wait, ES6 is not supported in all the browsers, so you need to transpile it using babel.js for example...

So you create a class like below:

class Person {
  constructor(name) { = name;

  build() {
    return new Person(this);

module.exports = Person;

In another JavaScript file, do the import like:

import { Person } from 'Person';

You also can require the file like:

const Person = require('./Person');

If you are using an older JavaScript version you can use requirejs:

requirejs(["helper/util"], function(util) {
    // This function is called when scripts/helper/util.js is loaded.
    // If util.js calls define(), then this function is not fired until
    // util's dependencies have loaded, and the util argument will hold
    // the module value for "helper/util".

If you want to stick to older version of stuff, like jQuery, you can also use something like getScript:

jQuery.getScript('./another-script.js', function() {
    // Call back after another-script loaded

Last, but not the least, don't forget you can do the traditional way of putting a script together using the <script> tag...

<script src="./first-script.js"></script>
<script src="./second-script.js"></script>
<script src="./third-script.js"></script>

There are also the async and defer attributes which I should mention here...

Note: There are several ways an external script can be executed:

  • If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing)
  • If async is not present and defer is present: The script is executed when the page has finished parsing
  • If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page

Custom HTTP Authorization Header

No, that is not a valid production according to the "credentials" definition in RFC 2617. You give a valid auth-scheme, but auth-param values must be of the form token "=" ( token | quoted-string ) (see section 1.2), and your example doesn't use "=" that way.

Python: How to get stdout after running os.system?

These answers didn't work for me. I had to use the following:

import subprocess
p = subprocess.Popen(["pwd"], stdout=subprocess.PIPE)
out =
print out

Or as a function (using shell=True was required for me on Python 2.6.7 and check_output was not added until 2.7, making it unusable here):

def system_call(command):
    p = subprocess.Popen([command], stdout=subprocess.PIPE, shell=True)

Using python map and other functional tools

>>> from itertools import repeat
>>> for foo, bars in zip(foos, repeat(bars)):
...     print foo, bars
1.0 [1, 2, 3]
2.0 [1, 2, 3]
3.0 [1, 2, 3]
4.0 [1, 2, 3]
5.0 [1, 2, 3]

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.

Batch script loop

Very basic way to implement looping in cmd programming using labels

@echo off
SET /A "index=1"
SET /A "count=5"
if %index% leq %count% (
   echo The value of index is %index%
   SET /A "index=index + 1"
   goto :while

finding the type of an element using jQuery

It is worth noting that @Marius's second answer could be used as pure Javascript solution.


Show/hide 'div' using JavaScript

Using style:

<style type="text/css">
   .hidden {
        display: none;
   .visible {
        display: block;

Using an event handler in JavaScript is better than the onclick="" attribute in HTML:

<button id="RenderPortfolio_Btn">View Portfolio</button>
<button id="RenderResults_Btn">View Results</button>

<div class="visible" id="portfolio">

<div class"hidden" id="results">


<script type="text/javascript">

    var portfolioDiv = document.getElementById('portfolio');
    var resultsDiv = document.getElementById('results');

    var portfolioBtn = document.getElementById('RenderPortfolio_Btn');
    var resultsBtn = document.getElementById('RenderResults_Btn');

    portfolioBtn.onclick = function() {
        resultsDiv.setAttribute('class', 'hidden');
        portfolioDiv.setAttribute('class', 'visible');

    resultsBtn.onclick = function() {
        portfolioDiv.setAttribute('class', 'hidden');
        resultsDiv.setAttribute('class', 'visible');


jQuery may help you to manipulate DOM elements easy!

Java: Calculating the angle between two points in degrees

Based on Saad Ahmed's answer, here is a method that can be used for any two points.

public static double calculateAngle(double x1, double y1, double x2, double y2)
    double angle = Math.toDegrees(Math.atan2(x2 - x1, y2 - y1));
    // Keep angle between 0 and 360
    angle = angle + Math.ceil( -angle / 360 ) * 360;

    return angle;

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

For Swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image

For Swift 4

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 @objc func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image

Is there any quick way to get the last two characters in a string?

The existing answers will fail if the string is empty or only has one character. Options:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;


String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

Is the NOLOCK (Sql Server hint) bad practice?

The better solutions, when possible are:

  • Replicate your data (using log-replication) to a reporting database.
  • Use SAN snapshots and mount a consistent version of the DB
  • Use a database which has a better fundamental transaction isolation level

The SNAPSHOT transaction isolation level was created because MS was losing sales to Oracle. Oracle uses undo/redo logs to avoid this problem. Postgres uses MVCC. In the future MS's Heckaton will use MVCC, but that's years away from being production ready.

MessageBodyWriter not found for media type=application/json

Below should be in your pom.xml above other jersy/jackson dependencies. In my case it as below jersy-client dep-cy and i got MessageBodyWriter not found for media type=application/json.


How can you represent inheritance in a database?

In addition at the Daniel Vassallo solution, if you use SQL Server 2016+, there is another solution that I used in some cases without considerable lost of performances.

You can create just a table with only the common field and add a single column with the JSON string that contains all the subtype specific fields.

I have tested this design for manage inheritance and I am very happy for the flexibility that I can use in the relative application.

phpinfo() - is there an easy way for seeing it?

If you are using WAMP then type the following in the browser
http://localhost/?phpinfo=-1, you will get the phpinfo page.

phpinfo() from localhost

You can also click the localhost icon in the wamp menu from the systray and then find the phpinfo page. WAMP localhost from WAMP Menu

Converting String to Double in Android

String sc1="0.0";
Double s1=Double.parseDouble(sc1.toString());

Laravel Request::all() Should Not Be Called Statically

use Illuminate\Http\Request;
public function store(Request $request){

is same in context saying

use Request;
public function store(){

how to find my angular version in my project?

you can use ng --version for angular version 7

How to iterate over columns of pandas dataframe to run regression

I landed on this question as I was looking for a clean iterator of columns only (Series, no names).

Unless I am mistaken, there is no such thing, which, if true, is a bit annoying. In particular, one would sometimes like to assign a few individual columns (Series) to variables, e.g.:

x, y = df[['x', 'y']]  # does not work

There is df.items() that gets close, but it gives an iterator of tuples (column_name, column_series). Interestingly, there is a corresponding df.keys() which returns df.columns, i.e. the column names as an Index, so a, b = df[['x', 'y']].keys() assigns properly a='x' and b='y'. But there is no corresponding df.values(), and for good reason, as df.values is a property and returns the underlying numpy array.

One (inelegant) way is to do:

x, y = (v for _, v in df[['x', 'y']].items())

but it's less pythonic than I'd like.

Load and execute external js file in node.js with access to local variables?

If you are planning to load an external javascript file's functions or objects, load on this context using the following code – note the runInThisContext method:

var vm = require("vm");
var fs = require("fs");

var data = fs.readFileSync('./externalfile.js');
const script = new vm.Script(data);

// here you can use externalfile's functions or objects as if they were instantiated here. They have been added to this context.