Programs & Examples On #Menu

A menu is a user interface mechanism that provides the user a means to view and execute application operations. (Generic; please use platform and/or language tags when possible instead)

jQuery add class .active on menu

No other "addClass" methods worked for me when adding a class to an 'a' element on menu except this one:

$(function () {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
        $('a').each(function () {
                            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                $(this).addClass('active');
            }
        });
    });

This took me four hours to find it.

How to copy text programmatically in my Android app?

ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
ClipData clip = ClipData.newPlainText("label", "Text to copy");
if (clipboard == null || clip == null)
    return;
clipboard.setPrimaryClip(clip);

And import import android.content.ClipboardManager;

How to update a menu item shown in the ActionBar?

I have used this code:

public boolean onPrepareOptionsMenu (Menu menu) {       
    MenuInflater inflater = getMenuInflater();
    TextView title  = (TextView) findViewById(R.id.title);
    menu.getItem(0).setTitle(
        getString(R.string.payFor) + " " + title.getText().toString());
    menu.getItem(1).setTitle(getString(R.string.payFor) + "...");
    return true;        
}

And worked like a charm to me you can find OnPrepareOptionsMenu here

Call method when home button pressed

use onPause() method to do what you want to do on home button.

How to make the HTML link activated by clicking on the <li>?

You could try an "onclick" event inside the LI tag, and change the "location.href" as in javascript.

You could also try placing the li tags within the a tags, however this is probably not valid HTML.

Adding a right click menu to an item

This is a comprehensive answer to this question. I have done this because this page is high on the Google search results and the answer does not go into enough detail. This post assumes that you are competent at using Visual Studio C# forms. This is based on VS2012.

  1. Start by simply dragging a ContextMenuStrip onto the form. It will just put it into the top left corner where you can add your menu items and rename it as you see fit.

  2. You will have to view code and enter in an event yourself on the form. Create a mouse down event for the item in question and then assign a right click event for it like so (I have called the ContextMenuStrip "rightClickMenuStrip"):

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
    {
    switch (e.Button)
        {
            case MouseButtons.Right:
            {
                rightClickMenuStrip.Show(this, new Point(e.X, e.Y));//places the menu at the pointer position
            }
            break;
        }
    }
    
  3. Assign the event handler manually to the form.designer (you may need to add a "using" for System.Windows.Forms; You can just resolve it):

    this.pictureBox1.MouseDown += new MouseEventHandler(this.pictureBox1_MouseDown);
    
  4. All that is needed at this point is to simply double click each menu item and do the desired operations for each click event in the same way you would for any other button.

This is the basic code for this operation. You can obviously modify it to fit in with your coding practices.

Changing Locale within the app itself

This is for my comment on Andrey's answer but I cant include code in the comments.

Is you preference activity being called from you main activity? you could place this in the on resume...

@Override
protected void onResume() {
    if (!(PreferenceManager.getDefaultSharedPreferences(
            getApplicationContext()).getString("listLanguage", "en")
            .equals(langPreference))) {
        refresh();
    }
    super.onResume();
}

private void refresh() {
    finish();
    Intent myIntent = new Intent(Main.this, Main.class);
    startActivity(myIntent);
}

Android custom dropdown/popup menu

Update: To create a popup menu in android with Kotlin refer my answer here.

To create a popup menu in android with Java:

Create a layout file activity_main.xml under res/layout directory which contains only one button.

Filename: activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    android:paddingBottom="@dimen/activity_vertical_margin"  
    android:paddingLeft="@dimen/activity_horizontal_margin"  
    android:paddingRight="@dimen/activity_horizontal_margin"  
    android:paddingTop="@dimen/activity_vertical_margin"  
    tools:context=".MainActivity" >  

    <Button  
        android:id="@+id/button1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentLeft="true"  
        android:layout_alignParentTop="true"  
        android:layout_marginLeft="62dp"  
        android:layout_marginTop="50dp"  
        android:text="Show Popup" />  

</RelativeLayout>  

Create a file popup_menu.xml under res/menu directory

It contains three items as shown below.

Filename: poupup_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >  

    <item  
        android:id="@+id/one"  
        android:title="One"/>  

    <item  
        android:id="@+id/two"  
        android:title="Two"/>  

    <item  
        android:id="@+id/three"  
        android:title="Three"/>  

</menu>  

MainActivity class which displays the popup menu on button click.

Filename: MainActivity.java

public class MainActivity extends Activity {  
    private Button button1;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //Creating the instance of PopupMenu
                PopupMenu popup = new PopupMenu(MainActivity.this, button1);
                //Inflating the Popup using xml file
                popup.getMenuInflater()
                    .inflate(R.menu.popup_menu, popup.getMenu());

                //registering popup with OnMenuItemClickListener
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(
                            MainActivity.this,
                            "You Clicked : " + item.getTitle(),
                            Toast.LENGTH_SHORT
                        ).show();
                        return true;
                    }
                });

                popup.show(); //showing popup menu
            }
        }); //closing the setOnClickListener method
    }
}

To add programmatically:

PopupMenu menu = new PopupMenu(this, view);

menu.getMenu().add("One");
menu.getMenu().add("Two");
menu.getMenu().add("Three");

menu.show();

Follow this link for creating menu programmatically.

how to set active class to nav menu from twitter bootstrap

For single page sites, the following is what I used. It not only sets the active element based on what's been clicked but it also checks for a hash value within the URL location on initial page load.

$(document).ready(function () {

    var removeActive = function() {
        $( "nav a" ).parents( "li, ul" ).removeClass("active");
    };

    $( ".nav li" ).click(function() {
        removeActive();
        $(this).addClass( "active" );
    });

    removeActive();
    $( "a[href='" + location.hash + "']" ).parent( "li" ).addClass( "active" );

});

How to get selected value of a dropdown menu in ReactJS

You can handle it all within the same function as following

_x000D_
_x000D_
<select className="form-control mb-3" onChange={(e) => this.setState({productPrice: e.target.value})}>_x000D_
_x000D_
  <option value="5">5 dollars</option>_x000D_
  <option value="10">10 dollars</option>_x000D_
                                         _x000D_
</select>
_x000D_
_x000D_
_x000D_

as you can see when the user select one option it will set a state and get the value of the selected event without furder coding require!

How to change menu item text dynamically in Android

I needed to change the menu icon for the fragment. I altered Charles’s answer to this question a bit for the fragment:

    private Menu top_menu;

    //...
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

       setHasOptionsMenu(true);
       //...
       rootview = inflater.inflate(R.layout.first_content,null);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment_menu, menu);
        this.top_menu = menu;
    }


    // my procedure
    private void updateIconMenu() {
         if(top_menu!= null) {
             MenuItem nav_undo = top_menu.findItem(R.id.action_undo);
             nav_undo.setIcon( R.drawable.back);
         }
    }

How to make jQuery UI nav menu horizontal?

This post has inspired me to try the jQuery ui menu.

http://jsfiddle.net/7Bvap/

<ul id="nav">
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a>
        <ul>
            <li><a href="#">Item 3-1</a>
            <ul>
                <li><a href="#">Item 3-11</a></li>
                <li><a href="#">Item 3-12</a></li>
                <li><a href="#">Item 3-13</a></li>
            </ul>
            </li>
            <li><a href="#">Item 3-2</a></li>
            <li><a href="#">Item 3-3</a></li>
            <li><a href="#">Item 3-4</a></li>
            <li><a href="#">Item 3-5</a></li>
        </ul>
    </li>
    <li><a href="#">Item 4</a></li>
    <li><a href="#">Item 5</a></li>
</ul>


.ui-menu { 
    overflow: hidden;
}
.ui-menu .ui-menu {
    overflow: visible !important;
}
.ui-menu > li { 
    float: left;
    display: block;
    width: auto !important;
}
.ui-menu ul li {
    display:block;
    float:none;
}
.ui-menu ul li ul {
    left:120px !important;
    width:100%;
}
.ui-menu ul li ul li {
    width:auto;
}
.ui-menu ul li ul li a {
    float:left;
}
.ui-menu > li {
    margin: 5px 5px !important;
    padding: 0 0 !important;
}
.ui-menu > li > a { 
    float: left;
    display: block;
    clear: both;
    overflow: hidden;
}
.ui-menu .ui-menu-icon { 
    margin-top: 0.3em !important;
}
.ui-menu .ui-menu .ui-menu li { 
    float: left;
    display: block;
}


$( "#nav" ).menu({position: {at: "left bottom"}});

http://jsfiddle.net/vapD7/

<ul id="nav">
    <li><a href="#">Item 1</a></li>
    <li><a href="#">Item 2</a></li>
    <li><a href="#">Item 3</a>
        <ul>
            <li><a href="#">Item 3-1</a>
            <ul>
                <li><a href="#">Item 3-11</a></li>
                <li><a href="#">Item 3-12</a></li>
                <li><a href="#">Item 3-13</a></li>
            </ul>
            </li>
            <li><a href="#">Item 3-2</a></li>
            <li><a href="#">Item 3-3</a></li>
            <li><a href="#">Item 3-4</a></li>
            <li><a href="#">Item 3-5</a></li>
        </ul>
    </li>
    <li><a href="#">Item 4</a></li>
    <li><a href="#">Item 5</a></li>
</ul>

.ui-menu { list-style:none; padding: 2px; margin: 0; display:block; outline: none; }
.ui-menu .ui-menu { margin-top: -3px; position: absolute; }
.ui-menu .ui-menu-item {
    display: inline-block;
    float: left;
    margin: 0;
    padding: 0;
    width: auto;
}
.ui-menu .ui-menu-divider { margin: 5px -2px 5px -2px; height: 0; font-size: 0; line-height: 0; border-width: 1px 0 0 0; }
.ui-menu .ui-menu-item a { text-decoration: none; display: block; padding: 2px .4em; line-height: 1.5; zoom: 1; font-weight: normal; }
.ui-menu .ui-menu-item a.ui-state-focus,
.ui-menu .ui-menu-item a.ui-state-active { font-weight: normal; margin: -1px; }

.ui-menu .ui-state-disabled { font-weight: normal; margin: .4em 0 .2em; line-height: 1.5; }
.ui-menu .ui-state-disabled a { cursor: default; }
.ui-menu:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

$( "#nav" ).menu({position: {at: "left bottom"}});

Creating a Menu in Python

There were just a couple of minor amendments required:

ans=True
while ans:
    print ("""
    1.Add a Student
    2.Delete a Student
    3.Look Up Student Record
    4.Exit/Quit
    """)
    ans=raw_input("What would you like to do? ") 
    if ans=="1": 
      print("\n Student Added") 
    elif ans=="2":
      print("\n Student Deleted") 
    elif ans=="3":
      print("\n Student Record Found") 
    elif ans=="4":
      print("\n Goodbye") 
    elif ans !="":
      print("\n Not Valid Choice Try again") 

I have changed the four quotes to three (this is the number required for multiline quotes), added a closing bracket after "What would you like to do? " and changed input to raw_input.

Twitter Bootstrap add active class to li

Here is complete Twitter bootstrap example and applied active class based on query string.

Few steps to follow to achieve correct solution:

1) Include latest jquery.js and bootstrap.js javascript file.

2) Include latest bootstrap.css file

3) Include querystring-0.9.0.js for getting query string variable value in js.

4) HTML:

<div class="navbar">
  <div class="navbar-inner">
    <div class="container">
      <ul class="nav">
        <li class="active">
          <a href="#?page=0">
            Home
          </a>
        </li>
        <li>
          <a href="#?page=1">
            Forums
          </a>
        </li>
        <li>
          <a href="#?page=2">
            Blog
          </a>
        </li>
        <li>
          <a href="#?page=3">
            FAQ's
          </a>
        </li>
        <li>
          <a href="#?page=4">
            Item
          </a>
        </li>
        <li>
          <a href="#?page=5">
            Create
          </a>
        </li>
      </ul>
    </div>
  </div>
</div>

JQuery in Script Tag:

$(function() {
    $(".nav li").click(function() {
        $(".nav li").removeClass('active');
        setTimeout(function() {
            var page = $.QueryString("page");
            $(".nav li:eq(" + page + ")").addClass("active");
        }, 300);

    });
});

I have done complete bin, so please click here http://codebins.com/bin/4ldqpaf

How can I make content appear beneath a fixed DIV element?

If your menu height is variable (for responsiveness or because it's loaded dynamically), you can set the top margin to where the fixed div ends. For example:

CSS

.fixed-header {
    width: 100%;
    margin: 0 auto;
    position: fixed;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
    z-index: 999;
}

Javascript

$(document).ready(function() {
    var contentPlacement = $('#header').position().top + $('#header').height();
    $('#content').css('margin-top',contentPlacement);
});

HTML

...
<div id="header" class="fixed-header"></div>
<div id="content">...</div>
...

Here's a fiddle (https://jsfiddle.net/632k9xkv/5/) that goes a little beyond this with both a fixed nav menu and header in an attempt to hopefully make this a useful sample.

What is the hamburger menu icon called and the three vertical dots icon called?

We call it the "ant" menu. Guess it was a good time to change since everyone had just gotten used to the hamburger.

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

Changing text color of menu item in navigation drawer

try this in java class

yourNavigationView.setItemTextColor(new ColorStateList(
            new int [] [] {
                    new int [] {android.R.attr.state_pressed},
                    new int [] {android.R.attr.state_focused},
                    new int [] {}
            },
            new int [] {
                    Color.rgb (255, 128, 192),
                    Color.rgb (100, 200, 192),
                    Color.WHITE
            }
    ));

How to make a HTML list appear horizontally instead of vertically using CSS only?

You will have to use something like below

_x000D_
_x000D_
#menu ul{_x000D_
  list-style: none;_x000D_
}_x000D_
#menu li{_x000D_
  display: inline;_x000D_
}_x000D_
 
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>First menu item</li>_x000D_
    <li>Second menu item</li>_x000D_
    <li>Third menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Python: How to get values of an array at certain index positions?

Just index using you ind_pos

ind_pos = [1,5,7]
print (a[ind_pos]) 
[88 85 16]


In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]

In [56]: import numpy as np

In [57]: arr = np.array(a)

In [58]: ind_pos = [1,5,7]

In [59]: arr[ind_pos]
Out[59]: array([88, 85, 16])

How best to include other scripts?

An alternative to:

scriptPath=$(dirname $0)

is:

scriptPath=${0%/*}

.. the advantage being not having the dependence on dirname, which is not a built-in command (and not always available in emulators)

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

Vue.js getting an element within a component

Composition API

Template refs section tells how this has been unified:

  • within template, use ref="myEl"; :ref= with a v-for
  • within script, have a const myEl = ref(null) and expose it from setup

The reference carries the DOM element from mounting onwards.

If input value is blank, assign a value of "empty" with Javascript

I'm guessing this is what you want...

When the form is submitted, check if the value is empty and if so, send a value = empty.

If so, you could do the following with jQuery.

$('form').submit(function(){
    var input = $('#test').val();
    if(input == ''){
         $('#test').val('empty');
    }    
});

HTML

<form> 
    <input id="test" type="text" />
</form>

http://jsfiddle.net/jasongennaro/NS6Ca/

Click your cursor in the box and then hit enter to see the form submit the value.

How do I run git log to see changes only for a specific branch?

If you want only those commits which are done by you in a particular branch, use the below command.

git log branch_name --author='Dyaniyal'

Regex to remove all special characters from string?

For my purposes I wanted all English ASCII chars, so this worked.

html = Regex.Replace(html, "[^\x00-\x80]+", "")

Checking for empty or null List<string>

Because you initialize myList with 'new', the list itself will never be null.

But it can be filled with 'null' values.

In that case .Count > 0 and .Any() will be true. You can check this with the .All(s => s == null)

var myList = new List<object>();
if (myList.Any() || myList.All(s => s == null))

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

How to prevent sticky hover effects for buttons on touch devices

A solution that has worked for me:

html {
   -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}

Add this code to your stylesheet.

I wanted to get rid of the grey background that appears on iOS Safari when a link is clicked. But it appears to do more. Now clicking a button (with a :hover pseudoclass!) gets opened right away! I only tested it on an iPad, I don't know if it'll work on other devices.

Stretch and scale a CSS image in the background - with CSS only

In order to scale your images appropriately based on the container size, use the following:

background-size: contain;
background-repeat: no-repeat;

jQuery .live() vs .on() method for adding a click event after loading dynamic html

.on() is for jQuery version 1.7 and above. If you have an older version, use this:

$("#SomeId").live("click",function(){
    //do stuff;
});

How to set upload_max_filesize in .htaccess?

What to do to correct this is create a file called php.ini and save it in the same location as your .htaccess file and enter the following code instead:

upload_max_filesize = "250M"
post_max_size = "250M"

Precision String Format Specifier In Swift

Swift 4

let string = String(format: "%.2f", locale: Locale.current, arguments: 15.123)

How to check the presence of php and apache on ubuntu server through ssh

How to tell on Ubuntu if apache2 is running:

sudo service apache2 status

/etc/init.d/apache2 status

ps aux | grep apache

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

SQL Server JOIN missing NULL values

You can be explicit about the joins:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN
     Table2
      ON (Table1.Col1 = Table2.Col1 or Table1.Col1 is NULL and Table2.Col1 is NULL) AND
         (Table1.Col2 = Table2.Col2 or Table1.Col2 is NULL and Table2.Col2 is NULL)

In practice, I would be more likely to use coalesce() in the join condition:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN
     Table2
     ON (coalesce(Table1.Col1, '') = coalesce(Table2.Col1, '')) AND
        (coalesce(Table1.Col2, '') = coalesce(Table2.Col2, ''))

Where '' would be a value not in either of the tables.

Just a word of caution. In most databases, using any of these constructs prevents the use of indexes.

Read line by line in bash script

xargs is the most flexible solution for splitting output into command arguments.

It is also very human readable and easy to use due to its simple parameterisation.

Format is xargs -n $NUMLINES mycommand.

For example, to echo each individual line in a file /tmp/tmp.txt you'd do:

cat /tmp/tmp.txt | xargs -n 1 echo

Or to diff each successive pair of files listed as lines in a file of the above name you'd do:

cat /tmp/tmp.txt | xargs -n 2 diff

The -n 2 instructs xargs to consume and pass as separate arguments two lines of what you've piped into it at a time.

You can tailor xargs to split on delimiters besides carriage return/newline.

Use man xargs and google to find out more about the power of this versatile utility.

jQuery SVG, why can't I addClass?

Just add the missing prototype constructor to all SVG nodes:

SVGElement.prototype.hasClass = function (className) {
  return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.getAttribute('class'));
};

SVGElement.prototype.addClass = function (className) { 
  if (!this.hasClass(className)) {
    this.setAttribute('class', this.getAttribute('class') + ' ' + className);
  }
};

SVGElement.prototype.removeClass = function (className) {
  var removedClass = this.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2');
  if (this.hasClass(className)) {
    this.setAttribute('class', removedClass);
  }
};

You can then use it this way without requiring jQuery:

this.addClass('clicked');

this.removeClass('clicked');

All credit goes to Todd Moto.

How to destroy JWT Tokens on logout?

The JWT is stored on browser, so remove the token deleting the cookie at client side

If you need also to invalidate the token from server side before its expiration time, for example account deleted/blocked/suspended, password changed, permissions changed, user logged out by admin, take a look at Invalidating JSON Web Tokens for some commons techniques like creating a blacklist or rotating tokens

Get string between two strings in a string

Since the : and the - are unique you could use:

string input;
string output;
input = "super example of string key : text I want to keep - end of my string";
output = input.Split(new char[] { ':', '-' })[1];

ImportError: No module named 'selenium'

Navigate to your scripts folder in Python directory (C:\Python27\Scripts) and open command line there (Hold shift and right click then select open command window here). Run pip install -U selenium
If you don't have pip installed, go ahead and install pip first

How do you do relative time in Rails?

I've written this, but have to check the existing methods mentioned to see if they are better.

module PrettyDate
  def to_pretty
    a = (Time.now-self).to_i

    case a
      when 0 then 'just now'
      when 1 then 'a second ago'
      when 2..59 then a.to_s+' seconds ago' 
      when 60..119 then 'a minute ago' #120 = 2 minutes
      when 120..3540 then (a/60).to_i.to_s+' minutes ago'
      when 3541..7100 then 'an hour ago' # 3600 = 1 hour
      when 7101..82800 then ((a+99)/3600).to_i.to_s+' hours ago' 
      when 82801..172000 then 'a day ago' # 86400 = 1 day
      when 172001..518400 then ((a+800)/(60*60*24)).to_i.to_s+' days ago'
      when 518400..1036800 then 'a week ago'
      else ((a+180000)/(60*60*24*7)).to_i.to_s+' weeks ago'
    end
  end
end

Time.send :include, PrettyDate

Commenting out a set of lines in a shell script

What if you just wrap your code into function?

So this:

cd ~/documents
mkdir test
echo "useless script" > about.txt

Becomes this:

CommentedOutBlock() {
  cd ~/documents
  mkdir test
  echo "useless script" > about.txt
}

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

For those that are going to come here after me, if it's Xcode 11 and ios 13 then your layout might look a little different than what you see in the main answer to this question.

Firstly do this as it was mentioned on the answer, Add your Apple ID in Xcode Preferences > Accounts > Add Apple ID.

Then click on the project name which is located in the left panel then you'll get a window of settings then look for signing & Capabilities and that's where you'll be able to see "Team" and select your name as the option. enter image description here

Importing .py files in Google Colab

  1. You can upload local files to google colab by using upload() function in google.colab.files
  2. If you have files on github, then clone the repo using !git clone https://github.com/username/repo_name.git. Then just like in jupyter notebook load it using the magic function %load %load filename.py.

Uncaught TypeError: Cannot read property 'top' of undefined

If this error appears whenever you click on the <a> tag. Try the code below.

CORRECT :

<a href="javascript:void(0)">

This malfunction occurs because your href is set to # inside of your <a> tag. Basically, your app is trying to find href which does not exist. The right way to set empty href is shown above.

WRONG :

<a href="#">

Filter Excel pivot table using VBA

Latest versions of Excel has a new tool called Slicers. Using slicers in VBA is actually more reliable that .CurrentPage (there have been reports of bugs while looping through numerous filter options). Here is a simple example of how you can select a slicer item (remember to deselect all the non-relevant slicer values):

Sub Step_Thru_SlicerItems2()
Dim slItem As SlicerItem
Dim i As Long
Dim searchName as string

Application.ScreenUpdating = False
searchName="Value1"

    For Each slItem In .VisibleSlicerItems
        If slItem.Name <> .SlicerItems(1).Name Then _
            slItem.Selected = False
        Else
            slItem.Selected = True
        End if
    Next slItem
End Sub

There are also services like SmartKato that would help you out with setting up your dashboards or reports and/or fix your code.

How do you detect Credit card type based on number?

// abobjects.com, parvez ahmad ab bulk mailer
use below script

function isValidCreditCard2(type, ccnum) {
       if (type == "Visa") {
          // Visa: length 16, prefix 4, dashes optional.
          var re = /^4\d{3}?\d{4}?\d{4}?\d{4}$/;
       } else if (type == "MasterCard") {
          // Mastercard: length 16, prefix 51-55, dashes optional.
          var re = /^5[1-5]\d{2}?\d{4}?\d{4}?\d{4}$/;
       } else if (type == "Discover") {
          // Discover: length 16, prefix 6011, dashes optional.
          var re = /^6011?\d{4}?\d{4}?\d{4}$/;
       } else if (type == "AmEx") {
          // American Express: length 15, prefix 34 or 37.
          var re = /^3[4,7]\d{13}$/;
       } else if (type == "Diners") {
          // Diners: length 14, prefix 30, 36, or 38.
          var re = /^3[0,6,8]\d{12}$/;
       }
       if (!re.test(ccnum)) return false;
       return true;
       /*
       // Remove all dashes for the checksum checks to eliminate negative numbers
       ccnum = ccnum.split("-").join("");
       // Checksum ("Mod 10")
       // Add even digits in even length strings or odd digits in odd length strings.
       var checksum = 0;
       for (var i=(2-(ccnum.length % 2)); i<=ccnum.length; i+=2) {
          checksum += parseInt(ccnum.charAt(i-1));
       }
       // Analyze odd digits in even length strings or even digits in odd length strings.
       for (var i=(ccnum.length % 2) + 1; i<ccnum.length; i+=2) {
          var digit = parseInt(ccnum.charAt(i-1)) * 2;
          if (digit < 10) { checksum += digit; } else { checksum += (digit-9); }
       }
       if ((checksum % 10) == 0) return true; else return false;
       */

    }
jQuery.validator.addMethod("isValidCreditCard", function(postalcode, element) { 
    return isValidCreditCard2($("#cardType").val(), $("#cardNum").val()); 

}, "<br>credit card is invalid");


     Type</td>
                                          <td class="text">&nbsp; <form:select path="cardType" cssclass="fields" style="border: 1px solid #D5D5D5;padding: 0px 0px 0px 0px;width: 130px;height: 22px;">
                                              <option value="SELECT">SELECT</option>
                                              <option value="MasterCard">Mastercard</option>
                                              <option value="Visa">Visa</option>
                                               <option value="AmEx">American Express</option>
                                              <option value="Discover">Discover</option>
                                            </form:select> <font color="#FF0000">*</font> 

$("#signupForm").validate({

    rules:{
       companyName:{required: true},
       address1:{required: true},
       city:{required: true},
       state:{required: true},
       zip:{required: true},
       country:{required: true},
       chkAgree:{required: true},
       confPassword:{required: true},
       lastName:{required: true},
       firstName:{required: true},
       ccAddress1:{required: true},
       ccZip:{         
           postalcode : true
       },
       phone:{required: true},
       email:{
           required: true,
           email: true
           },
       userName:{
           required: true,
           minlength: 6
           },
       password:{
           required: true,
           minlength: 6
           },          
       cardNum:{           
            isValidCreditCard : true
       },

How to calculate the time interval between two time strings

Both time and datetime have a date component.

Normally if you are just dealing with the time part you'd supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime for each with the day set to today and subtract the start from the stop time to get the interval (timedelta).

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Convert number to varchar in SQL with formatting

Correción: 3-LEN

declare @t  TINYINT 
set @t =233
SELECT ISNULL(REPLICATE('0',3-LEN(@t)),'') + CAST(@t AS VARCHAR) 

C# Interfaces. Implicit implementation versus Explicit implementation

In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.

/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
    string Title { get; }
    string ISBN { get; }
}

/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
    string Title { get; }
    string Forename { get; }
    string Surname { get; }
}

/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
    /// <summary>
    /// This method is shared by both Book and Person
    /// </summary>
    public string Title
    {
        get
        {
            string personTitle = "Mr";
            string bookTitle = "The Hitchhikers Guide to the Galaxy";

            // What do we do here?
            return null;
        }
    }

    #region IPerson Members

    public string Forename
    {
        get { return "Lee"; }
    }

    public string Surname
    {
        get { return "Oades"; }
    }

    #endregion

    #region IBook Members

    public string ISBN
    {
        get { return "1-904048-46-3"; }
    }

    #endregion
}

This code compiles and runs OK, but the Title property is shared.

Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.

string IBook.Title
{
    get
    {
        return "The Hitchhikers Guide to the Galaxy";
    }
}

string IPerson.Title
{
    get
    {
        return "Mr";
    }
}

public string Title
{
    get { return "Still shared"; }
}

Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.

Note also that you can still have a "shared" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.

If you do not define the "shared" (implicit) Title, consumers of Class1 must explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.

Python: Removing list element while iterating over list

You could always iterate over a copy of the list, leaving you free to modify the original:

for item in list(somelist):
  ...
  somelist.remove(item)

How to get user name using Windows authentication in asp.net?

These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source

Safe navigation operator (?.) or (!.) and null property paths

Building on @Pvl's answer, you can include type safety on your returned value as well if you use overrides:

function dig<
  T,
  K1 extends keyof T
  >(obj: T, key1: K1): T[K1];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1]
  >(obj: T, key1: K1, key2: K2): T[K1][K2];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2]
  >(obj: T, key1: K1, key2: K2, key3: K3): T[K1][K2][K3];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3]
  >(obj: T, key1: K1, key2: K2, key3: K3, key4: K4): T[K1][K2][K3][K4];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3],
  K5 extends keyof T[K1][K2][K3][K4]
  >(obj: T, key1: K1, key2: K2, key3: K3, key4: K4, key5: K5): T[K1][K2][K3][K4][K5];

function dig<
  T,
  K1 extends keyof T,
  K2 extends keyof T[K1],
  K3 extends keyof T[K1][K2],
  K4 extends keyof T[K1][K2][K3],
  K5 extends keyof T[K1][K2][K3][K4]
  >(obj: T, key1: K1, key2?: K2, key3?: K3, key4?: K4, key5?: K5):
  T[K1] |
  T[K1][K2] |
  T[K1][K2][K3] |
  T[K1][K2][K3][K4] |
  T[K1][K2][K3][K4][K5] {
    let value: any = obj && obj[key1];

    if (key2) {
      value = value && value[key2];
    }

    if (key3) {
      value = value && value[key3];
    }

    if (key4) {
      value = value && value[key4];
    }

    if (key5) {
      value = value && value[key5];
    }

    return value;
}

Example on playground.

onSaveInstanceState () and onRestoreInstanceState ()

I think this thread was quite old. I just mention another case, that onSaveInstanceState() will also be called, is when you call Activity.moveTaskToBack(boolean nonRootActivity).

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}

How to concatenate a std::string and an int?

#include <iostream>
#include <sstream>

std::ostringstream o;
o << name << age;
std::cout << o.str();

.keyCode vs. .which

I'd recommend event.key currently. MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

event.KeyCode and event.which both have nasty deprecated warnings at the top of their MDN pages:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which

For alphanumeric keys, event.key appears to be implemented identically across all browsers. For control keys (tab, enter, escape, etc), event.key has the same value across Chrome/FF/Safari/Opera but a different value in IE10/11/Edge (IEs apparently use an older version of the spec but match each other as of Jan 14 2018).

For alphanumeric keys a check would look something like:

event.key === 'a'

For control characters you'd need to do something like:

event.key === 'Esc' || event.key === 'Escape'

I used the example here to test on multiple browsers (I had to open in codepen and edit to get it to work with IE10): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

event.code is mentioned in a different answer as a possibility, but IE10/11/Edge don't implement it, so it's out if you want IE support.

T-SQL: How to Select Values in Value List that are NOT IN the Table?

Use this : -- SQL Server 2008 or later

SELECT U.* 
FROM USERS AS U
Inner Join (
  SELECT   
    EMail, [Status]
  FROM
    (
      Values
        ('email1', 'Exist'),
        ('email2', 'Exist'),
        ('email3', 'Not Exist'),
        ('email4', 'Exist')
    )AS TempTableName (EMail, [Status])
  Where TempTableName.EMail IN ('email1','email2','email3')
) As TMP ON U.EMail = TMP.EMail

JUnit Testing private variables?

Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.

remove legend title in ggplot

Since you may have more than one legends in a plot, a way to selectively remove just one of the titles without leaving an empty space is to set the name argument of the scale_ function to NULL, i.e.

scale_fill_discrete(name = NULL)

(kudos to @pascal for a comment on another thread)

How do I get a specific range of numbers from rand()?

Just to add some extra detail to the existing answers.

The mod % operation will always perform a complete division and therefore yield a remainder less than the divisor.

x % y = x - (y * floor((x/y)))

An example of a random range finding function with comments:

uint32_t rand_range(uint32_t n, uint32_t m) {
    // size of range, inclusive
    const uint32_t length_of_range = m - n + 1;

    // add n so that we don't return a number below our range
    return (uint32_t)(rand() % length_of_range + n);
}

Another interesting property as per the above:

x % y = x, if x < y

const uint32_t value = rand_range(1, RAND_MAX); // results in rand() % RAND_MAX + 1
// TRUE for all x = RAND_MAX, where x is the result of rand()
assert(value == RAND_MAX);
result of rand()

Operand type clash: uniqueidentifier is incompatible with int

If you're accessing this via a View then try sp_recompile or refreshing views.

sp_recompile:

Causes stored procedures, triggers, and user-defined functions to be recompiled the next time that they are run. It does this by dropping the existing plan from the procedure cache forcing a new plan to be created the next time that the procedure or trigger is run. In a SQL Server Profiler collection, the event SP:CacheInsert is logged instead of the event SP:Recompile.

Arguments

[ @objname= ] 'object'

The qualified or unqualified name of a stored procedure, trigger, table, view, or user-defined function in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure, trigger, or user-defined function, the stored procedure, trigger, or function will be recompiled the next time that it is run. If object is the name of a table or view, all the stored procedures, triggers, or user-defined functions that reference the table or view will be recompiled the next time that they are run.

Return Code Values

0 (success) or a nonzero number (failure)

Remarks

sp_recompile looks for an object in the current database only.

The queries used by stored procedures, or triggers, and user-defined functions are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures, triggers, and user-defined functions may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.

How to securely save username/password (local)?

I have used this before and I think in order to make sure credential persist and in a best secure way is

  1. you can write them to the app config file using the ConfigurationManager class
  2. securing the password using the SecureString class
  3. then encrypting it using tools in the Cryptography namespace.

This link will be of great help I hope : Click here

What is the best way to find the users home directory in Java?

Alternative would be to use Apache CommonsIO FileUtils.getUserDirectory() instead of System.getProperty("user.home"). It will get you the same result and there is no chance to introduce a typo when specifying system property.

There is a big chance you already have Apache CommonsIO library in your project. Don't introduce it if you plan to use it only for getting user home directory.

Serialize Class containing Dictionary member

Dictionaries and Hashtables are not serializable with XmlSerializer. Therefore you cannot use them directly. A workaround would be to use the XmlIgnore attribute to hide those properties from the serializer and expose them via a list of serializable key-value pairs.

PS: constructing an XmlSerializer is very expensive, so always cache it if there is a chance of being able to re-use it.

How to add an image to a JPanel?

JPanel is almost always the wrong class to subclass. Why wouldn't you subclass JComponent?

There is a slight problem with ImageIcon in that the constructor blocks reading the image. Not really a problem when loading from the application jar, but maybe if you're potentially reading over a network connection. There's plenty of AWT-era examples of using MediaTracker, ImageObserver and friends, even in the JDK demos.

Jquery - How to get the style display attribute "none / block"

My answer

/**
 * Display form to reply comment
 */
function displayReplyForm(commentId) {
    var replyForm = $('#reply-form-' + commentId);
    if (replyForm.css('display') == 'block') { // Current display
        replyForm.css('display', 'none');
    } else { // Hide reply form
        replyForm.css('display', 'block');
    }
}

How does the compilation/linking process work?

The compilation of a C++ program involves three steps:

  1. Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.

  2. Compilation: the compiler takes the pre-processor's output and produces an object file from it.

  3. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.

Preprocessing

The preprocessor handles the preprocessor directives, like #include and #define. It is agnostic of the syntax of C++, which is why it must be used with care.

It works on one C++ source file at a time by replacing #include directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define), and selecting different portions of text depending of #if, #ifdef and #ifndef directives.

The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as replacing tokens with other tokens (the operator ## enables merging two tokens when it makes sense).

After all this, the preprocessor produces a single output that is a stream of tokens resulting from the transformations described above. It also adds some special markers that tell the compiler where each line came from so that it can use those to produce sensible error messages.

Some errors can be produced at this stage with clever use of the #if and #error directives.

Compilation

The compilation step is performed on each output of the preprocessor. The compiler parses the pure C++ source code (now without any preprocessor directives) and converts it into assembly code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.

Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily produce the object file as long as the source code is well-formed.

Compilers usually let you stop compilation at this point. This is very useful because with it you can compile each source code file separately. The advantage this provides is that you don't need to recompile everything if you only change a single file.

The produced object files can be put in special archives called static libraries, for easier reusing later on.

It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution errors, are reported.

Linking

The linker is what produces the final compilation output from the object files the compiler produced. This output can be either a shared (or dynamic) library (and while the name is similar, they haven't got much in common with static libraries mentioned earlier) or an executable.

It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.

At this stage the most common errors are missing definitions or duplicate definitions. The former means that either the definitions don't exist (i.e. they are not written), or that the object files or libraries where they reside were not given to the linker. The latter is obvious: the same symbol was defined in two different object files or libraries.

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

HTML form action and onsubmit issues

Try:

onsubmit="checkRegistration(event.preventDefault())"

How to compare times in Python?

Inspired by Roger Pate:

import datetime
def todayAt (hr, min=0, sec=0, micros=0):
   now = datetime.datetime.now()
   return now.replace(hour=hr, minute=min, second=sec, microsecond=micros)    

# Usage demo1:
print todayAt (17), todayAt (17, 15)

# Usage demo2:    
timeNow = datetime.datetime.now()
if timeNow < todayAt (13):
   print "Too Early"

Download a file from HTTPS using download.file()

Had exactly the same problem as UseR (original question), I'm also using windows 7. I tried all proposed solutions and they didn't work.

I resolved the problem doing as follows:

  1. Using RStudio instead of R console.

  2. Actualising the version of R (from 3.1.0 to 3.1.1) so that the library RCurl runs OK on it. (I'm using now R3.1.1 32bit although my system is 64bit).

  3. I typed the URL address as https (secure connection) and with / instead of backslashes \\.

  4. Setting method = "auto".

It works for me now. You should see the message:

Content type 'text/csv; charset=utf-8' length 9294 bytes
opened URL
downloaded 9294 by

Java Array Sort descending?

You could use this to sort all kind of Objects

sort(T[] a, Comparator<? super T> c) 

Arrays.sort(a, Collections.reverseOrder());

Arrays.sort() cannot be used directly to sort primitive arrays in descending order. If you try to call the Arrays.sort() method by passing reverse Comparator defined by Collections.reverseOrder() , it will throw the error

no suitable method found for sort(int[],comparator)

That will work fine with 'Array of Objects' such as Integer array but will not work with a primitive array such as int array.

The only way to sort a primitive array in descending order is, first sort the array in ascending order and then reverse the array in place. This is also true for two-dimensional primitive arrays.

Linux Command History with date and time

In case you are using zsh you can use for example the -E or -i switch:

history -E

If you do a man zshoptions or man zshbuiltins you can find out more information about these switches as well as other info related to history:

Also when listing,
 -d     prints timestamps for each event
 -f     prints full time-date stamps in the US `MM/DD/YY hh:mm' format
 -E     prints full time-date stamps in the European `dd.mm.yyyy hh:mm' format
 -i     prints full time-date stamps in ISO8601 `yyyy-mm-dd hh:mm' format
 -t fmt prints time and date stamps in the given format; fmt is formatted with the strftime function with the zsh extensions  described  for  the  %D{string} prompt format in the section EXPANSION OF PROMPT SEQUENCES in zshmisc(1).  The resulting formatted string must be no more than 256 characters or will not be printed
 -D     prints elapsed times; may be combined with one of the options above

Writing string to a file on a new line every time

Just a note, file isn't supported in Python 3 and was removed. You can do the same with the open built-in function.

f = open('test.txt', 'w')
f.write('test\n')

Order by multiple columns with Doctrine

You have to add the order direction right after the column name:

$qb->orderBy('column1 ASC, column2 DESC');

As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:

$qb->addOrderBy('column1', 'ASC')
   ->addOrderBy('column2', 'DESC');

Can inner classes access private variables?

Anything that is part of Outer should have access to all of Outer's members, public or private.

Edit: your compiler is correct, var is not a member of Inner. But if you have a reference or pointer to an instance of Outer, it could access that.

How to debug a bash script?

I think you can try this Bash debugger: http://bashdb.sourceforge.net/.

cannot find zip-align when publishing app

i solved by RUN as Administrator @ your SDK Manager.exe in directory C:\Program Files\Android SDK

after that u'll get updated build tools an any repository

I keep getting "Uncaught SyntaxError: Unexpected token o"

The problem is very simple

jQuery.get('wokab.json', function(data) {
    var glacier = JSON.parse(data);
});

You're parsing it twice. get uses the dataType='json', so data is already in json format. Use $.ajax({ dataType: 'json' ... to specifically set the returned data type!

What is meant with "const" at end of function declaration?

Bar is guaranteed not to change the object it is being invoked on. See the section about const correctness in the C++ FAQ, for example.

How can I generate a unique ID in Python?

Maybe this work for u

str(uuid.uuid4().fields[-1])[:5]

ToggleClass animate jQuery?

You should look at the toggle function found on jQuery. This will allow you to specify an easing method to define how the toggle works.

slideToggle will only slide up and down, not left/right if that's what you are looking for.

If you need the class to be toggled as well you can deifine that in the toggle function with a:

$(this).closest('article').toggle('slow', function() {
    $(this).toggleClass('expanded');
});

C# Reflection: How to get class reference from string?

You will want to use the Type.GetType method.

Here is a very simple example:

using System;
using System.Reflection;

class Program
{
    static void Main()
    {
        Type t = Type.GetType("Foo");
        MethodInfo method 
             = t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);

        method.Invoke(null, null);
    }
}

class Foo
{
    public static void Bar()
    {
        Console.WriteLine("Bar");
    }
}

I say simple because it is very easy to find a type this way that is internal to the same assembly. Please see Jon's answer for a more thorough explanation as to what you will need to know about that. Once you have retrieved the type my example shows you how to invoke the method.

How to import set of icons into Android Studio project

just like Gregory Seront said here:

Actually if you downloaded the icons pack from the android web site, you will see that you have one folder per resolution named drawable-mdpi etc. Copy all folders into the res (not the drawable) folder in Android Studio. This will automatically make all the different resolution of the icon available.

but if your not getting the images from a generator site (maybe your UX team provides them), just make sure your folders are named drawable-hdpi, drawable-mdpi, etc. then in mac select all folders by holding shift and then copy them (DO NOT DRAG). Paste the folders into the res folder. android will take care of the rest and copy all drawables into the correct folder.

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • How do I add a newline to a windows-forms TextBox?

    Quickie test code for WinForms in VB:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        Dim Newline As String
        Newline = System.Environment.NewLine
    
        TextBox1.Text = "This is a test"
        TextBox1.Text = TextBox1.Text & Newline & "This is line 2"
    
    End Sub
    

    Using ExcelDataReader to read Excel data starting from a particular cell

    For ExcelDataReader v3.6.0 and above. I struggled a bit to iterate over the Rows. So here's a little more to the above code. Hope it helps for few atleast.

    using (var stream = System.IO.File.Open(copyPath, FileMode.Open, FileAccess.Read))
                        {
    
                            IExcelDataReader excelDataReader = ExcelDataReader.ExcelReaderFactory.CreateReader(stream);
    
                            var conf = new ExcelDataSetConfiguration()
                            {
                                ConfigureDataTable = a => new ExcelDataTableConfiguration
                                {
                                    UseHeaderRow = true
                                }
                            };
    
                            DataSet dataSet = excelDataReader.AsDataSet(conf);
                            //DataTable dataTable = dataSet.Tables["Sheet1"];
                            DataRowCollection row = dataSet.Tables["Sheet1"].Rows;
                            //DataColumnCollection col = dataSet.Tables["Sheet1"].Columns;
    
                            List<object> rowDataList = null;
                            List<object> allRowsList = new List<object>();
                            foreach (DataRow item in row)
                            {
                                rowDataList = item.ItemArray.ToList(); //list of each rows
                                allRowsList.Add(rowDataList); //adding the above list of each row to another list
                            }
    
                        }
    

    How to define static property in TypeScript interface

    Static modifiers cannot appear on a type member (TypeScript error TS1070). That's why I recommend to use an abstract class to solve the mission:

    Example

    // Interface definition
    abstract class MyInterface {
      static MyName: string;
      abstract getText(): string;
    }
    
    // Interface implementation
    class MyClass extends MyInterface {
      static MyName = 'TestName';
      getText(): string {
        return `This is my name static name "${MyClass.MyName}".`;
      }
    }
    
    // Test run
    const test: MyInterface = new MyClass();
    console.log(test.getText());
    

    pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

    One solution (for Windows) is to create a file called pip.ini on the %AppData%\pip\ folder (create the folder if it doesn't exist) and insert the following details:

    [global]
    cert = C:/certs/python_root.pem
    proxy = http://my_user@my_company.com:my_password@proxy_ip:proxy_port
    

    ...and then we can execute the install instruction:

    pip3 install PyQt5
    

    Another option is to install the package using arguments for the proxy and certificate...

    $ pip3 install --proxy http://my_user@my_company.com:my_password@proxy_ip:proxy_port \
       --cert C:/certs/python_root.pem PyQt5
    

    To convert the certificate *.cer files to the required *.pem format execute the following instruction:

    $ openssl x509 -inform der -in python_root.cer -out python_root.pem
    

    Hope this helps someone!

    check if a file is open in Python

    If all you care about is the current process, an easy way is to use the file object attribute "closed"

    f = open('file.py')
    if f.closed:
      print 'file is closed'
    

    This will not detect if the file is open by other processes!

    source: http://docs.python.org/2.4/lib/bltin-file-objects.html

    What's the difference between Thread start() and Runnable run()

    First example: No multiple threads. Both execute in single (existing) thread. No thread creation.

    R1 r1 = new R1();
    R2 r2 = new R2();
    

    r1 and r2 are just two different objects of classes that implement the Runnable interface and thus implement the run() method. When you call r1.run() you are executing it in the current thread.

    Second example: Two separate threads.

    Thread t1 = new Thread(r1);
    Thread t2 = new Thread(r2);
    

    t1 and t2 are objects of the class Thread. When you call t1.start(), it starts a new thread and calls the run() method of r1 internally to execute it within that new thread.

    What are the correct version numbers for C#?

    The biggest problem when dealing with C#'s version numbers is the fact that it is not tied to a version of the .NET Framework, which it appears to be due to the synchronized releases between Visual Studio and the .NET Framework.

    The version of C# is actually bound to the compiler, not the framework. For instance, in Visual Studio 2008 you can write C# 3.0 and target .NET Framework 2.0, 3.0 and 3.5. The C# 3.0 nomenclature describes the version of the code syntax and supported features in the same way that ANSI C89, C90, C99 describe the code syntax/features for C.

    Take a look at Mono, and you will see that Mono 2.0 (mostly implemented version 2.0 of the .NET Framework from the ECMA specifications) supports the C# 3.0 syntax and features.

    How do I trim whitespace from a string?

    I could not find a solution to what I was looking for so I created some custom functions. You can try them out.

    def cleansed(s: str):
        """:param s: String to be cleansed"""
        assert s is not (None or "")
        # return trimmed(s.replace('"', '').replace("'", ""))
        return trimmed(s)
    
    
    def trimmed(s: str):
        """:param s: String to be cleansed"""
        assert s is not (None or "")
        ss = trim_start_and_end(s).replace('  ', ' ')
        while '  ' in ss:
            ss = ss.replace('  ', ' ')
        return ss
    
    
    def trim_start_and_end(s: str):
        """:param s: String to be cleansed"""
        assert s is not (None or "")
        return trim_start(trim_end(s))
    
    
    def trim_start(s: str):
        """:param s: String to be cleansed"""
        assert s is not (None or "")
        chars = []
        for c in s:
            if c is not ' ' or len(chars) > 0:
                chars.append(c)
        return "".join(chars).lower()
    
    
    def trim_end(s: str):
        """:param s: String to be cleansed"""
        assert s is not (None or "")
        chars = []
        for c in reversed(s):
            if c is not ' ' or len(chars) > 0:
                chars.append(c)
        return "".join(reversed(chars)).lower()
    
    
    s1 = '  b Beer '
    s2 = 'Beer  b    '
    s3 = '      Beer  b    '
    s4 = '  bread butter    Beer  b    '
    
    cdd = trim_start(s1)
    cddd = trim_end(s2)
    clean1 = cleansed(s3)
    clean2 = cleansed(s4)
    
    print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s1, len(s1), cdd, len(cdd)))
    print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s2, len(s2), cddd, len(cddd)))
    print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s3, len(s3), clean1, len(clean1)))
    print("\nStr: {0} Len: {1} Cleansed: {2} Len: {3}".format(s4, len(s4), clean2, len(clean2)))
    

    How to finish current activity in Android

    If you are doing a loading screen, just set the parameter to not keep it in activity stack. In your manifest.xml, where you define your activity do:

    <activity android:name=".LoadingScreen" android:noHistory="true" ... />
    

    And in your code there is no need to call .finish() anymore. Just do startActivity(i);

    There is also no need to keep a instance of your current activity in a separate field. You can always access it like LoadingScreen.this.doSomething() instead of private LoadingScreen loadingScreen;

    Android Studio - debug keystore

    On Mac, you will find it here: /Users/$username/.android

    Sublime 3 - Set Key map for function Goto Definition

    If you want to see how to do a proper definition go into Sublime Text->Preferences->Key Bindings - Default and search for the command you want to override.

    { "keys": ["f12"], "command": "goto_definition" },
    { "keys": ["super+alt+down"], "command": "goto_definition" }
    

    Those are two that show in my Default.

    On Mac I copied the second to override.

    in Sublime Text -> Preferences -> Key Bindings - User I added this

    /* Beginning of File */
    
    [
        {
            "keys": ["super+shift+i"], "command": "goto_definition" 
        }
    ]
    
    /* End of File */
    

    This binds it to the Command + Shift + 1 combination on mac.

    Matplotlib scatter plot with different text at each data point

    This might be useful when you need individually annotate in different time (I mean, not in a single for loop)

    ax = plt.gca()
    ax.annotate('your_lable', (x,y)) 
    

    where x and y are the your target coordinate and type is float/int.

    How to access to a child method from the parent in vue.js

    You can use ref.

    import ChildForm from './components/ChildForm'
    
    new Vue({
      el: '#app',
      data: {
        item: {}
      },
      template: `
      <div>
         <ChildForm :item="item" ref="form" />
         <button type="submit" @click.prevent="submit">Post</button>
      </div>
      `,
      methods: {
        submit() {
          this.$refs.form.submit()
        }
      },
      components: { ChildForm },
    })
    

    If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.

    import ChildForm from './components/ChildForm'
    
    new Vue({
      el: '#app',
      data: {
        item: {},
        bus: new Vue(),
      },
      template: `
      <div>
         <ChildForm :item="item" :bus="bus" ref="form" />
         <button type="submit" @click.prevent="submit">Post</button>
      </div>
      `,
      methods: {
        submit() {
          this.bus.$emit('submit')
        }
      },
      components: { ChildForm },
    })
    

    Code of component.

    <template>
     ...
    </template>
    
    <script>
    export default {
      name: 'NowForm',
      props: ['item', 'bus'],
      methods: {
        submit() {
            ...
        }
      },
      mounted() {
        this.bus.$on('submit', this.submit)
      },  
    }
    </script>
    

    https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/

    EnterKey to press button in VBA Userform

    This one worked for me

    Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
            If KeyCode = 13 Then
                 Button1_Click
            End If
    End Sub
    

    How to dynamically add a class to manual class names?

    try this using hooks:

    const [dynamicClasses, setDynamicClasses] = React.useState([
        "dynamicClass1", "dynamicClass2"
    ]);
    

    and add this in className attribute :

    <div className=`wrapper searchDiv ${[...dynamicClasses]}`>
    ...
    </div>
    

    to add class :

        const addClass = newClass => {
           setDynamicClasses([...dynamicClasses, newClass])
        }
    

    to delete class :

            const deleteClass= classToDelete => {
    
               setDynamicClasses(dynamicClasses.filter(class = > {
                 class !== classToDelete
               }));
    
            }
    

    Google Maps API: open url by clicking on marker

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
      return function() {
        window.location.href = marker.url;
      }
    })(marker, i));
    

    How to find the parent element using javascript

    Use the change event of the select:

    $('#my_select').change(function()
    {
       $(this).parents('td').css('background', '#000000');
    });
    

    Notepad++ change text color?

    You can Change it from:

    Menu Settings -> Style Configurator

    See on screenshot:

    enter image description here

    How to sort strings in JavaScript

    In your operation in your initial question, you are performing the following operation:

    item1.attr - item2.attr
    

    So, assuming those are numbers (i.e. item1.attr = "1", item2.attr = "2") You still may use the "===" operator (or other strict evaluators) provided that you ensure type. The following should work:

    return parseInt(item1.attr) - parseInt(item2.attr);
    

    If they are alphaNumeric, then do use localCompare().

    Codeigniter $this->input->post() empty while $_POST is working correctly

    Try This, change

    $config['base_url'] = 'http://mywebsite.cl/';
    

    to

    $config['base_url'] = 'http://www.mywebsite.cl/';
    

    Some provider auto add www , https , etc to your url, most of the times, this causes this issue

    Checking for a null int value from a Java ResultSet

    Another solution:

    public class DaoTools {
        static public Integer getInteger(ResultSet rs, String strColName) throws SQLException {
            int nValue = rs.getInt(strColName);
            return rs.wasNull() ? null : nValue;
        }
    }
    

    How to right-align and justify-align in Markdown?

    In a generic Markdown document, use:

    <style>body {text-align: right}</style>

    or

    <style>body {text-align: justify}</style>

    Does not seem to work with Jupyter though.

    Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

    My problem was that for some hiccups with my OS any command on my local repository ended with "fatal: Not a git repository (or any of the parent directories): .git", with fsck command included.

    The problem was empty HEAD file.

    I was able to find actual branch name I've worked on in .git/refs/heads and then I did this:

    echo 'ref: refs/heads/ML_#94_FILTER_TYPES_AND_SPECIAL_CHARS' > .git/HEAD
    

    It worked.

    How do I compare two strings in python?

    You can use simple loops to check two strings are equal. .But ideally you can use something like return s1==s2

    s1 = 'hello'
    s2 = 'hello'
    
    a = []
    for ele in s1:
        a.append(ele)
    for i in range(len(s2)):
        if a[i]==s2[i]:
            a.pop()
    if len(a)>0:
        return False
    else:
        return True
    

    How do you share code between projects/solutions in Visual Studio?

    It is a good idea to create a dll class library that contain all common functionality. Each solution can reference this dll indepently regardless of other solutions.

    Infact , this is how our sources are organized in my work (and I believe in many other places).

    By the way , Solution can't explicitly depend on another solution.

    node.js + mysql connection pooling

    i always use connection.relase(); after pool.getconnetion like

    pool.getConnection(function (err, connection) {
          connection.release();
            if (!err)
            {
                console.log('*** Mysql Connection established with ', config.database, ' and connected as id ' + connection.threadId);
                //CHECKING USERNAME EXISTENCE
                email = receivedValues.email
                connection.query('SELECT * FROM users WHERE email = ?', [email],
                    function (err, rows) {
                        if (!err)
                        {
                            if (rows.length == 1)
                            {
                                if (bcrypt.compareSync(req.body.password, rows[0].password))
                                {
                                    var alldata = rows;
                                    var userid = rows[0].id;
                                    var tokendata = (receivedValues, userid);
                                    var token = jwt.sign(receivedValues, config.secret, {
                                        expiresIn: 1440 * 60 * 30 // expires in 1440 minutes
                                    });
                                    console.log("*** Authorised User");
                                    res.json({
                                        "code": 200,
                                        "status": "Success",
                                        "token": token,
                                        "userData": alldata,
                                        "message": "Authorised User!"
                                    });
                                    logger.info('url=', URL.url, 'Responce=', 'User Signin, username', req.body.email, 'User Id=', rows[0].id);
                                    return;
                                }
                                else
                                {
                                    console.log("*** Redirecting: Unauthorised User");
                                    res.json({"code": 200, "status": "Fail", "message": "Unauthorised User!"});
                                    logger.error('*** Redirecting: Unauthorised User');
                                    return;
                                }
                            }
                            else
                            {
                                console.error("*** Redirecting: No User found with provided name");
                                res.json({
                                    "code": 200,
                                    "status": "Error",
                                    "message": "No User found with provided name"
                                });
                                logger.error('url=', URL.url, 'No User found with provided name');
                                return;
                            }
                        }
                        else
                        {
                            console.log("*** Redirecting: Error for selecting user");
                            res.json({"code": 200, "status": "Error", "message": "Error for selecting user"});
                            logger.error('url=', URL.url, 'Error for selecting user', req.body.email);
                            return;
                        }
                    });
                connection.on('error', function (err) {
                    console.log('*** Redirecting: Error Creating User...');
                    res.json({"code": 200, "status": "Error", "message": "Error Checking Username Duplicate"});
                    return;
                });
            }
            else
            {
                Errors.Connection_Error(res);
            }
        });
    

    Force an Android activity to always use landscape mode

    A quick and simple solution is for the AndroidManifest.xml file, add the following for each activity that you wish to force to landscape mode:

    android:screenOrientation="landscape"
    

    Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

    Let's say you have an array of data:

    n = [1    2   3   4   6   12  18  51  69  81  ]
    

    then you can 'foreach' it like this:

    for i = n, i, end
    

    This will echo every element in n (but replacing the i with more interesting stuff is also possible of course!)

    jQuery - Fancybox: But I don't want scrollbars!

    Using fancybox version: 2.1.5 and tried all of the different options suggest here and none of them worked still showing the scrollbar.

    $('.foo').click(function(e){            
        $.fancybox({
            href: $(this).data('href'),
            type: 'iframe',
            scrolling: 'no',
            iframe : {
                scrolling : 'no'
            }
        });
        e.preventDefault();
    });
    

    So did some debugging in the code until I found this, so its overwriting all options I set and no way to overwrite this using the many options.

    if (type === 'iframe' && isTouch) {
       coming.scrolling = 'scroll';
    }
    

    In the end the solutions was to use CSS !important hack.

    .fancybox-inner {
       overflow: hidden !important;
    }
    

    The line of code responsible is:

    current.inner.css('overflow', scrolling === 'yes' ? 'scroll' : (scrolling === 'no' ? 'hidden' : scrolling));
    

    Fancybox used to be a reliable working solution now I am finding nothing but inconsistencies. Actually debating about downgrading now even after purchasing a developers license. More info here if you didn't realize you needed one for commercial project: https://stackoverflow.com/a/8837258/560287

    How can I inspect element in chrome when right click is disabled?

    Sure, you can open the devtools with Ctrl+Shift+I, and then click the inspect element button (square with the arrow)

    How to check if a value exists in a dictionary (python)

    Different types to check the values exists

    d = {"key1":"value1", "key2":"value2"}
    "value10" in d.values() 
    >> False
    

    What if list of values

    test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6']}
    "value4" in [x for v in test.values() for x in v]
    >>True
    

    What if list of values with string values

    test = {'key1': ['value4', 'value5', 'value6'], 'key2': ['value9'], 'key3': ['value6'], 'key5':'value10'}
    values = test.values()
    "value10" in [x for v in test.values() for x in v] or 'value10' in values
    >>True
    

    How to produce an csv output file from stored procedure in SQL Server

    This script exports rows from specified tables to the CSV format in the output window for any tables structure. Hope, the script will be helpful for you -

    DECLARE 
          @TableName SYSNAME
        , @ObjectID INT
    
    DECLARE [tables] CURSOR READ_ONLY FAST_FORWARD LOCAL FOR 
        SELECT 
              '[' + s.name + '].[' + t.name + ']'
            , t.[object_id]
        FROM (
            SELECT DISTINCT
                  t.[schema_id]
                , t.[object_id]
                , t.name
            FROM sys.objects t WITH (NOWAIT)
            JOIN sys.partitions p WITH (NOWAIT) ON p.[object_id] = t.[object_id]
            WHERE p.[rows] > 0
                AND t.[type] = 'U'
        ) t
        JOIN sys.schemas s WITH (NOWAIT) ON t.[schema_id] = s.[schema_id]
        WHERE t.name IN ('<your table name>')
    
    OPEN [tables]
    
    FETCH NEXT FROM [tables] INTO 
          @TableName
        , @ObjectID
    
    DECLARE 
          @SQLInsert NVARCHAR(MAX)
        , @SQLColumns NVARCHAR(MAX)
        , @SQLTinyColumns NVARCHAR(MAX)
    
    WHILE @@FETCH_STATUS = 0 BEGIN
    
        SELECT 
              @SQLInsert = ''
            , @SQLColumns = ''
            , @SQLTinyColumns = ''
    
        ;WITH cols AS 
        (
            SELECT 
                  c.name
                , datetype = t.name
                , c.column_id
            FROM sys.columns c WITH (NOWAIT)
            JOIN sys.types t WITH (NOWAIT) ON c.system_type_id = t.system_type_id AND c.user_type_id = t.user_type_id
            WHERE c.[object_id] = @ObjectID
                AND c.is_computed = 0
                AND t.name NOT IN ('xml', 'geography', 'geometry', 'hierarchyid')
        )
        SELECT 
              @SQLTinyColumns = STUFF((
                SELECT ', [' + c.name + ']'
                FROM cols c
                ORDER BY c.column_id
                FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 2, '')
            , @SQLColumns = STUFF((SELECT CHAR(13) +
                CASE 
                    WHEN c.datetype = 'uniqueidentifier' 
                        THEN ' + '';'' + ISNULL('''' + CAST([' + c.name + '] AS VARCHAR(MAX)) + '''', ''NULL'')' 
                    WHEN c.datetype IN ('nvarchar', 'varchar', 'nchar', 'char', 'varbinary', 'binary') 
                        THEN ' + '';'' + ISNULL('''' + CAST(REPLACE([' + c.name + '], '''', '''''''') AS NVARCHAR(MAX)) + '''', ''NULL'')' 
                    WHEN c.datetype = 'datetime'
                        THEN ' + '';'' + ISNULL('''' + CONVERT(VARCHAR, [' + c.name + '], 120) + '''', ''NULL'')' 
                    ELSE 
                    ' + '';'' + ISNULL(CAST([' + c.name + '] AS NVARCHAR(MAX)), ''NULL'')'
                END
                FROM cols c
                ORDER BY c.column_id
                FOR XML PATH, TYPE, ROOT).value('.', 'NVARCHAR(MAX)'), 1, 10, 'CHAR(13) + '''' +')
    
        DECLARE @SQL NVARCHAR(MAX) = '    
        SET NOCOUNT ON;
        DECLARE 
              @SQL NVARCHAR(MAX) = ''''
            , @x INT = 1
            , @count INT = (SELECT COUNT(1) FROM ' + @TableName + ')
    
        IF EXISTS(
            SELECT 1
            FROM tempdb.dbo.sysobjects
            WHERE ID = OBJECT_ID(''tempdb..#import'')
        )
            DROP TABLE #import;
    
        SELECT ' + @SQLTinyColumns + ', ''RowNumber'' = ROW_NUMBER() OVER (ORDER BY ' + @SQLTinyColumns + ')
        INTO #import
        FROM ' + @TableName + ' 
    
        WHILE @x < @count BEGIN
    
            SELECT @SQL = STUFF((
            SELECT ' + @SQLColumns + ' + ''''' + '
            FROM #import 
            WHERE RowNumber BETWEEN @x AND @x + 9
            FOR XML PATH, TYPE, ROOT).value(''.'', ''NVARCHAR(MAX)''), 1, 1, '''')
    
            PRINT(@SQL)
    
            SELECT @x = @x + 10
    
        END'
    
        EXEC sys.sp_executesql @SQL
    
        FETCH NEXT FROM [tables] INTO 
              @TableName
            , @ObjectID
    
    END
    
    CLOSE [tables]
    DEALLOCATE [tables]
    

    In the output window you'll get something like this (AdventureWorks.Person.Person):

    1;EM;0;NULL;Ken;J;Sánchez;NULL;0;92C4279F-1207-48A3-8448-4636514EB7E2;2003-02-08 00:00:00
    2;EM;0;NULL;Terri;Lee;Duffy;NULL;1;D8763459-8AA8-47CC-AFF7-C9079AF79033;2002-02-24 00:00:00
    3;EM;0;NULL;Roberto;NULL;Tamburello;NULL;0;E1A2555E-0828-434B-A33B-6F38136A37DE;2001-12-05 00:00:00
    4;EM;0;NULL;Rob;NULL;Walters;NULL;0;F2D7CE06-38B3-4357-805B-F4B6B71C01FF;2001-12-29 00:00:00
    5;EM;0;Ms.;Gail;A;Erickson;NULL;0;F3A3F6B4-AE3B-430C-A754-9F2231BA6FEF;2002-01-30 00:00:00
    6;EM;0;Mr.;Jossef;H;Goldberg;NULL;0;0DEA28FD-EFFE-482A-AFD3-B7E8F199D56F;2002-02-17 00:00:00
    

    How to install a Notepad++ plugin offline?

    Here are my steps tried with NPP 7.8.2:

    (1)Download the plugins zip (refer plugin-full-list json):

    https://github.com/notepad-plus-plus/nppPluginList/blob/master/src/pl.x64.json

    (2)Extract the files (normally .dll lib files) from zip to npp's plugins sub-folder

    E.g., extract NppFTP-x64.zip into C:\Program Files\Notepad++\plugins\NppFTP

    Keep in mind:

      (i)Must create sub-folder for each plugin
     (ii)The sub-folder's name must be EXACTLY SAME as the main .dll filename (e.g., NppFTP.dll)
    

    (3)Restart npp, those plugin will be automatically loaded.

    [Note-1]: I didn't do setting->import->plugin, it seems this is not required [Note-2]: You may need start npp with "run as administrator" option if you want to do import plugin.

    Is it possible to have a default parameter for a mysql stored procedure?

    We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB.

    CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40))
    BEGIN
      IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF;
    
      ...your code here...
    END
    

    Update TextView Every Second

    Add following code in your onCreate() method:

    Thread thread = new Thread() {
    
      @Override
      public void run() {
        try {
          while (!thread.isInterrupted()) {
            Thread.sleep(1000);
            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                // update TextView here!
              }
            });
          }
        } catch (InterruptedException e) {
        }
      }
    };
    
    thread.start();
    

    This code starts an thread which sleeps 1000 milliseconds every round.

    How to convert an NSTimeInterval (seconds) into minutes

    Remember that the original question is about a string output, not pseudo-code or individual string components.

    I want to convert it into the following string: "5:26"

    Many answers are missing the internationalization issues, and most doing the math computations by hand. All just so 20th century...

    Do not do the Math yourself (Swift 4)

    let timeInterval: TimeInterval = 326.4
    let dateComponentsFormatter = DateComponentsFormatter()
    dateComponentsFormatter.unitsStyle = .positional
    if let formatted = dateComponentsFormatter.string(from: timeInterval) {
        print(formatted)
    }
    

    5:26


    Leverage on libraries

    If you really want individual components, and pleasantly readable code, check out SwiftDate:

    import SwiftDate
    ...
    if let minutes = Int(timeInterval).seconds.in(.minute) {
        print("\(minutes)")
    }
    

    5


    Credits to @mickmaccallum and @polarwar for adequate usage of DateComponentsFormatter

    How to create an 2D ArrayList in java?

    1st of all, when you declare a variable in java, you should declare it using Interfaces even if you specify the implementation when instantiating it

    ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
    

    should be written

    List<List<String>> listOfLists = new ArrayList<List<String>>(size); 
    

    Then you will have to instantiate all columns of your 2d array

        for(int i = 0; i < size; i++)  {
            listOfLists.add(new ArrayList<String>());
        }
    

    And you will use it like this :

    listOfLists.get(0).add("foobar");
    

    But if you really want to "create a 2D array that each cell is an ArrayList!"

    Then you must go the dijkstra way.

    How do I edit SSIS package files?

    Adding to what b_levitt said, you can get the SSDT-BI plugin for Visual Studio 2013 here: http://www.microsoft.com/en-us/download/details.aspx?id=42313

    jquery (or pure js) simulate enter key pressed for testing

    For those who want to do this in pure javascript, look at:

    Using standard KeyboardEvent

    As Joe comment it, KeyboardEvent is now the standard.

    Same example to fire an enter (keyCode 13):

    const ke = new KeyboardEvent('keydown', {
        bubbles: true, cancelable: true, keyCode: 13
    });
    document.body.dispatchEvent(ke);
    

    You can use this page help you to find the right keyboard event.


    Outdated answer:

    You can do something like (here for Firefox)

    var ev = document.createEvent('KeyboardEvent');
    // Send key '13' (= enter)
    ev.initKeyEvent(
        'keydown', true, true, window, false, false, false, false, 13, 0);
    document.body.dispatchEvent(ev);
    

    how to merge 200 csv files in Python

    If you are working on linux/mac you can do this.

    from subprocess import call
    script="cat *.csv>merge.csv"
    call(script,shell=True)
    

    Get key and value of object in JavaScript?

    $.each(top_brands, function() {
      var key = Object.keys(this)[0];
      var value = this[key];
      brand_options.append($("<option />").val(key).text(key + " "  + value));
    });
    

    How to get ASCII value of string in C#

    If you want the charcode for each character in the string, you could do something like this:

    char[] chars = "9quali52ty3".ToCharArray();
    

    How should I tackle --secure-file-priv in MySQL?

    Here is what worked for me in Windows 7 to disable secure-file-priv (Option #2 from vhu's answer):

    1. Stop the MySQL server service by going into services.msc.
    2. Go to C:\ProgramData\MySQL\MySQL Server 5.6 (ProgramData was a hidden folder in my case).
    3. Open the my.ini file in Notepad.
    4. Search for 'secure-file-priv'.
    5. Comment the line out by adding '#' at the start of the line. For MySQL Server 5.7.16 and above, commenting won't work. You have to set it to an empty string like this one - secure-file-priv=""
    6. Save the file.
    7. Start the MySQL server service by going into services.msc.

    How many socket connections can a web server handle?

    Note that HTTP doesn't typically keep TCP connections open for any longer than it takes to transmit the page to the client; and it usually takes much more time for the user to read a web page than it takes to download the page... while the user is viewing the page, he adds no load to the server at all.

    So the number of people that can be simultaneously viewing your web site is much larger than the number of TCP connections that it can simultaneously serve.

    dbms_lob.getlength() vs. length() to find blob size in oracle

    length and dbms_lob.getlength return the number of characters when applied to a CLOB (Character LOB). When applied to a BLOB (Binary LOB), dbms_lob.getlength will return the number of bytes, which may differ from the number of characters in a multi-byte character set.

    As the documentation doesn't specify what happens when you apply length on a BLOB, I would advise against using it in that case. If you want the number of bytes in a BLOB, use dbms_lob.getlength.

    Laravel Eloquent - Get one Row

    Simply use this:

    $user = User::whereEmail($email)->first();
    

    How to iterate over a JavaScript object?

    I finally came up with a handy utility function with a unified interface to iterate Objects, Strings, Arrays, TypedArrays, Maps, Sets, (any Iterables).

    const iterate = require('@a-z/iterate-it');
    const obj = { a: 1, b: 2, c: 3 };
    
    iterate(obj, (value, key) => console.log(key, value)); 
    // a 1
    // b 2
    // c 3
    

    https://github.com/alrik/iterate-javascript

    Convert array of indices to 1-hot encoded numpy array

    You can use the following code for converting into a one-hot vector:

    let x is the normal class vector having a single column with classes 0 to some number:

    import numpy as np
    np.eye(x.max()+1)[x]
    

    if 0 is not a class; then remove +1.

    Get HTML inside iframe using jQuery

    Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):

    $('#iframe').get(0).contentWindow.document.body.innerHTML
    

    How to stop a thread created by implementing runnable interface?

    How to stop a thread created by implementing runnable interface?

    There are many ways that you can stop a thread but all of them take specific code to do so. A typical way to stop a thread is to have a volatile boolean shutdown field that the thread checks every so often:

      // set this to true to stop the thread
      volatile boolean shutdown = false;
      ...
      public void run() {
          while (!shutdown) {
              // continue processing
          }
      }
    

    You can also interrupt the thread which causes sleep(), wait(), and some other methods to throw InterruptedException. You also should test for the thread interrupt flag with something like:

      public void run() {
          while (!Thread.currentThread().isInterrupted()) {
              // continue processing
              try {
                  Thread.sleep(1000);
              } catch (InterruptedException e) {
                  // good practice
                  Thread.currentThread().interrupt();
                  return;
              }
          }
      }
    

    Note that that interrupting a thread with interrupt() will not necessarily cause it to throw an exception immediately. Only if you are in a method that is interruptible will the InterruptedException be thrown.

    If you want to add a shutdown() method to your class which implements Runnable, you should define your own class like:

    public class MyRunnable implements Runnable {
        private volatile boolean shutdown;
        public void run() {
            while (!shutdown) {
                ...
            }
        }
        public void shutdown() {
            shutdown = true;
        }
    }
    

    How to exclude records with certain values in sql select

    You can use EXCEPT syntax, for example:

    SELECT var FROM table1
    EXCEPT
    SELECT var FROM table2
    

    Swift - How to hide back button in navigation item?

    Put it in the viewDidLoad method

    navigationItem.hidesBackButton = true 
    

    Convert Little Endian to Big Endian

    Sorry, my answer is a bit too late, but it seems nobody mentioned built-in functions to reverse byte order, which in very important in terms of performance.

    Most of the modern processors are little-endian, while all network protocols are big-endian. That is history and more on that you can find on Wikipedia. But that means our processors convert between little- and big-endian millions of times while we browse the Internet.

    That is why most architectures have a dedicated processor instructions to facilitate this task. For x86 architectures there is BSWAP instruction, and for ARMs there is REV. This is the most efficient way to reverse byte order.

    To avoid assembly in our C code, we can use built-ins instead. For GCC there is __builtin_bswap32() function and for Visual C++ there is _byteswap_ulong(). Those function will generate just one processor instruction on most architectures.

    Here is an example:

    #include <stdio.h>
    #include <inttypes.h>
    
    int main()
    {
        uint32_t le = 0x12345678;
        uint32_t be = __builtin_bswap32(le);
    
        printf("Little-endian: 0x%" PRIx32 "\n", le);
        printf("Big-endian:    0x%" PRIx32 "\n", be);
    
        return 0;
    }
    

    Here is the output it produces:

    Little-endian: 0x12345678
    Big-endian:    0x78563412
    

    And here is the disassembly (without optimization, i.e. -O0):

            uint32_t be = __builtin_bswap32(le);
       0x0000000000400535 <+15>:    mov    -0x8(%rbp),%eax
       0x0000000000400538 <+18>:    bswap  %eax
       0x000000000040053a <+20>:    mov    %eax,-0x4(%rbp)
    

    There is just one BSWAP instruction indeed.

    So, if we do care about the performance, we should use those built-in functions instead of any other method of byte reversing. Just my 2 cents.

    How do I set path while saving a cookie value in JavaScript?

    This will help....

    function setCookie(name,value,days) {
       var expires = "";
       if (days) {
           var date = new Date();
           date.setTime(date.getTime() + (days*24*60*60*1000));
           expires = "; expires=" + date.toUTCString();
       }
        document.cookie = name + "=" + (value || "")  + expires + "; path=/";
    }
    
     function getCookie(name) {
       var nameEQ = name + "=";
       var ca = document.cookie.split(';');
       for(var i=0;i < ca.length;i++) {
           var c = ca[i];
           while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return 
            c.substring(nameEQ.length,c.length);
      }
    return null;
    }
    

    Linux: where are environment variables stored?

    Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

    Is it possible to get a list of files under a directory of a website? How?

    Any crawler or spider will read your index.htm or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm or equivalent file, it will not list all the files in such folder.

    If by mistake, the programmer never included an index.htm file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/ and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.

    Except, of course, if they can enter your FTP or access your site control panel.

    What is the functionality of setSoTimeout and how it works?

    Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?

    No, it means that if no data arrives within 2000ms a SocketTimeoutException will be thrown.

    What does it mean timeout expire?

    It means the 2000ms (in your case) elapses without any data arriving.

    What is the option which must be enabled prior to blocking operation?

    There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.

    Infinite Timeout menas that the socket does't read anymore?

    What a strange suggestion. It means that if no data ever arrives you will block in the read forever.

    How to create a numpy array of arbitrary length strings?

    You could use the object data type:

    >>> import numpy
    >>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
    >>> s[0] += 'bcdef'
    >>> s
    array([abcdef, b, dude], dtype=object)
    

    Input type DateTime - Value format?

    That one shows up correctly as HTML5-Tag for those looking for this:

    <input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />
    

    Regex for quoted string with escaping quotes

    An option that has not been touched on before is:

    1. Reverse the string.
    2. Perform the matching on the reversed string.
    3. Re-reverse the matched strings.

    This has the added bonus of being able to correctly match escaped open tags.

    Lets say you had the following string; String \"this "should" NOT match\" and "this \"should\" match" Here, \"this "should" NOT match\" should not be matched and "should" should be. On top of that this \"should\" match should be matched and \"should\" should not.

    First an example.

    // The input string.
    const myString = 'String \\"this "should" NOT match\\" and "this \\"should\\" match"';
    
    // The RegExp.
    const regExp = new RegExp(
        // Match close
        '([\'"])(?!(?:[\\\\]{2})*[\\\\](?![\\\\]))' +
        '((?:' +
            // Match escaped close quote
            '(?:\\1(?=(?:[\\\\]{2})*[\\\\](?![\\\\])))|' +
            // Match everything thats not the close quote
            '(?:(?!\\1).)' +
        '){0,})' +
        // Match open
        '(\\1)(?!(?:[\\\\]{2})*[\\\\](?![\\\\]))',
        'g'
    );
    
    // Reverse the matched strings.
    matches = myString
        // Reverse the string.
        .split('').reverse().join('')
        // '"hctam "\dluohs"\ siht" dna "\hctam TON "dluohs" siht"\ gnirtS'
    
        // Match the quoted
        .match(regExp)
        // ['"hctam "\dluohs"\ siht"', '"dluohs"']
    
        // Reverse the matches
        .map(x => x.split('').reverse().join(''))
        // ['"this \"should\" match"', '"should"']
    
        // Re order the matches
        .reverse();
        // ['"should"', '"this \"should\" match"']
    

    Okay, now to explain the RegExp. This is the regexp can be easily broken into three pieces. As follows:

    # Part 1
    (['"])         # Match a closing quotation mark " or '
    (?!            # As long as it's not followed by
      (?:[\\]{2})* # A pair of escape characters
      [\\]         # and a single escape
      (?![\\])     # As long as that's not followed by an escape
    )
    # Part 2
    ((?:          # Match inside the quotes
    (?:           # Match option 1:
      \1          # Match the closing quote
      (?=         # As long as it's followed by
        (?:\\\\)* # A pair of escape characters
        \\        # 
        (?![\\])  # As long as that's not followed by an escape
      )           # and a single escape
    )|            # OR
    (?:           # Match option 2:
      (?!\1).     # Any character that isn't the closing quote
    )
    )*)           # Match the group 0 or more times
    # Part 3
    (\1)           # Match an open quotation mark that is the same as the closing one
    (?!            # As long as it's not followed by
      (?:[\\]{2})* # A pair of escape characters
      [\\]         # and a single escape
      (?![\\])     # As long as that's not followed by an escape
    )
    

    This is probably a lot clearer in image form: generated using Jex's Regulex

    Image on github (JavaScript Regular Expression Visualizer.) Sorry, I don't have a high enough reputation to include images, so, it's just a link for now.

    Here is a gist of an example function using this concept that's a little more advanced: https://gist.github.com/scagood/bd99371c072d49a4fee29d193252f5fc#file-matchquotes-js

    Converting any object to a byte array in java

    Use serialize and deserialize methods in SerializationUtils from commons-lang.

    Run Command Line & Command From VBS

    Set oShell = CreateObject ("WScript.Shell") 
    oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "
    

    How to return data from promise

    You have to return a promise instead of a variable. So in your function just return:

    return relationsManagerResource.GetParentId(nodeId)
    

    And later resolve the returned promise. Or you can make another deferred and resolve theParentId with it.

    How to iterate through range of Dates in Java?

    Here is Java 8 code. I think this code will solve your problem.Happy Coding

        LocalDate start = LocalDate.now();
        LocalDate end = LocalDate.of(2016, 9, 1);//JAVA 9 release date
        Long duration = start.until(end, ChronoUnit.DAYS);
        System.out.println(duration);
         // Do Any stuff Here there after
        IntStream.iterate(0, i -> i + 1)
                 .limit(duration)
                 .forEach((i) -> {});
         //old way of iteration
        for (int i = 0; i < duration; i++)
         System.out.print("" + i);// Do Any stuff Here
    

    Exit while loop by user hitting ENTER key

    Here is the best and simplest answer. Use try and except calls.

    x = randint(1,9)
    guess = -1
    
    print "Guess the number below 10:"
    while guess != x:
        try:
            guess = int(raw_input("Guess: "))
    
            if guess < x:
                print "Guess higher."
            elif guess > x:
                print "Guess lower."
            else:
                print "Correct."
        except:
            print "You did not put any number."
    

    Rounding a variable to two decimal places C#

    Pay attention on fact that Round rounds.

    So (I don't know if it matters in your industry or not), but:

    float a = 12.345f;
    Math.Round(a,2);
    
    //result:12,35, and NOT 12.34 !
    

    To make it more precise for your case we can do something like this:

    int aInt = (int)(a*100);
    float aFloat= aInt /100.0f;
    //result:12,34 
    

    Strange Characters in database text: Ã, Ã, ¢, â‚ €,

    The error usually gets introduced while creation of CSV. Try using Linux for saving the CSV as a TextCSV. Libre Office in Ubuntu can enforce the encoding to be UTF-8, worked for me. I wasted a lot of time trying this on Mac OS. Linux is the key. I've tested on Ubuntu.

    Good Luck

    How do you check if a selector matches something in jQuery?

    I think most of the people replying here didn't quite understand the question, or else I might be mistaken.

    The question is "how to check whether or not a selector exists in jQuery."

    Most people have taken this for "how to check whether an element exists in the DOM using jQuery." Hardly interchangeable.

    jQuery allows you to create custom selectors, but see here what happens when you try to use on e before initializing it;

    $(':YEAH');
    "Syntax error, unrecognized expression: YEAH"
    

    After running into this, I realized it was simply a matter of checking

    if ($.expr[':']['YEAH']) {
        // Query for your :YEAH selector with ease of mind.
    }
    

    Cheers.

    What can be the reasons of connection refused errors?

    Check at the server side that it is listening at the port 2080. First try to confirm it on the server machine by issuing telnet to that port:

    telnet localhost 2080

    If it is listening, it is able to respond.

    Compare dates in MySQL

    You can try below query,

    select * from players
    where 
        us_reg_date between '2000-07-05'
    and
        DATE_ADD('2011-11-10',INTERVAL 1 DAY)
    

    When should I use mmap for file access?

    Memory mapping has a potential for a huge speed advantage compared to traditional IO. It lets the operating system read the data from the source file as the pages in the memory mapped file are touched. This works by creating faulting pages, which the OS detects and then the OS loads the corresponding data from the file automatically.

    This works the same way as the paging mechanism and is usually optimized for high speed I/O by reading data on system page boundaries and sizes (usually 4K) - a size for which most file system caches are optimized to.

    "Cannot start compilation: the output path is not specified for module..."

    You just have to go to your Module settings > Project and specify a "Project compiler output" and make your modules inherit from project. (For that go to Modules > Paths > Inherit project.

    This did the trick for me.

    How can I programmatically check whether a keyboard is present in iOS app?

    Add an extension

    extension UIApplication {
        /// Checks if view hierarchy of application contains `UIRemoteKeyboardWindow` if it does, keyboard is presented
        var isKeyboardPresented: Bool {
            if let keyboardWindowClass = NSClassFromString("UIRemoteKeyboardWindow"),
                self.windows.contains(where: { $0.isKind(of: keyboardWindowClass) }) {
                return true
            } else {
                return false
            }
        }
    }
    

    Then check if keyboard is present,

    if UIApplication.shared.isKeyboardPresented {
         print("Keyboard presented")
    } else { 
         print("Keyboard is not presented")
    }
    

    How to Update/Drop a Hive Partition?

    Alter table table_name drop partition (partition_name);
    

    PHPmailer sending HTML CODE

    or if you have still problems you can use this

    $mail->Body =  html_entity_decode($Body);
    

    How to run a Command Prompt command with Visual Basic code?

    Yes. You can use Process.Start to launch an executable, including a console application.

    If you need to read the output from the application, you may need to read from it's StandardOutput stream in order to get anything printed from the application you launch.

    How do I serialize a Python dictionary into a string, and then back to a dictionary?

    One thing json cannot do is dict indexed with numerals. The following snippet

    import json
    dictionary = dict({0:0, 1:5, 2:10})
    serialized = json.dumps(dictionary)
    unpacked   = json.loads(serialized)
    print(unpacked[0])
    

    will throw

    KeyError: 0
    

    Because keys are converted to strings. cPickle preserves the numeric type and the unpacked dict can be used right away.

    Auto-increment primary key in SQL tables

    I think there is a way to do it at definition stage like this

    create table employee( id int identity, name varchar(50), primary key(id) ).. I am trying to see if there is a way to alter an existing table and make the column as Identity which does not look possible theoretically (as the existing values might need modification)

    How to pass parameters or arguments into a gradle task

    task mathOnProperties << {
        println Integer.parseInt(a)+Integer.parseInt(b)
        println new Integer(a) * new Integer(b)
    }
    

    $ gradle -Pa=3 -Pb=4 mathOnProperties
    :mathOnProperties
    7
    12
    
    BUILD SUCCESSFUL
    

    POST string to ASP.NET Web Api application - returns null

    ([FromBody] IDictionary<string,object> data)
    

    SQL Server stored procedure Nullable parameter

    It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

    Other than that, I would suggest two things...

    First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

        ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
    

    Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

    How to reference Microsoft.Office.Interop.Excel dll?

    You have to check which version of Excel you are targeting?

    If you are targeting Excel 2010 use version 14 (as per Grant's screenshot answer), Excel 2007 use version 12 . You can not support Excel 2003 using vS2012 as they do not have the correct Interop dll installed.

    How to send Request payload to REST API in java?

    I tried with a rest client.

    Headers :

    • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
    • Host: git.eclipse.org
    • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
    • Accept: application/json
    • Accept-Language: null
    • Accept-Encoding: gzip,deflate,sdch
    • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
    • Content-Type: application/json; charset=UTF-8
    • Content-Length: 73
    • Connection: keep-alive

    it works fine. I retrieve 200 OK with a good body.

    Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

    C#: How do you edit items and subitems in a listview?

    Sorry, don't have enough rep, or would have commented on CraigTP's answer.

    I found the solution from the 1st link - C# Editable ListView, quite easy to use. The general idea is to:

    • identify the SubItem that was selected and overlay a TextBox with the SubItem's text over the SubItem
    • give this TextBox focus
    • change SubItem's text to that of TextBox's when TextBox loses focus

    What a workaround for a seemingly simple operation :-|

    Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

    It starts working because on the base.py you have all information needed in a basic settings file. You need the line:

    SECRET_KEY = '8lu*6g0lg)9z!ba+a$ehk)xt)x%rxgb$i1&amp;022shmi1jcgihb*'
    

    So it works and when you do from base import *, it imports SECRET_KEY into your development.py.

    You should always import basic settings before doing any custom settings.


    EDIT: Also, when django imports development from your package, it initializes all variables inside base since you defined from base import * inside __init__.py

    How to convert Windows end of line in Unix end of line (CR/LF to LF)

    Go back to Windows, tell Eclipse to change the encoding to UTF-8, then back to Unix and run d2u on the files.

    Checkout remote branch using git svn

    Standard Subversion layout

    Create a git clone of that includes your Subversion trunk, tags, and branches with

    git svn clone http://svn.example.com/project -T trunk -b branches -t tags

    The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

    git svn clone http://svn.example.com/project --stdlayout

    Make your git repository ignore everything the subversion repo does:

    git svn show-ignore >> .git/info/exclude

    You should now be able to see all the Subversion branches on the git side:

    git branch -r

    Say the name of the branch in Subversion is waldo. On the git side, you'd run

    git checkout -b waldo-svn remotes/waldo

    The -svn suffix is to avoid warnings of the form

    warning: refname 'waldo' is ambiguous.

    To update the git branch waldo-svn, run

    git checkout waldo-svn
    git svn rebase

    Starting from a trunk-only checkout

    To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

    [svn-remote "svn-mybranch"]
            url = http://svn.example.com/project/branches/mybranch
            fetch = :refs/remotes/mybranch

    You'll need to develop the habit of running

    git svn fetch --fetch-all

    to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

    git checkout -b mybranch-svn remotes/mybranch

    For the branches from which you intend to git svn dcommit, keep their histories linear!


    Further information

    You may also be interested in reading an answer to a related question.

    How to use comparison and ' if not' in python?

    Why think? If not confuses you, switch your if and else clauses around to avoid the negation.

    i want to make sure that ( u0 <= u < u0+step ) before do sth.

    Just write that.

    if u0 <= u < u0+step:
        "do sth" # What language is "sth"?  No vowels.  An odd-looking word.
    else:
        u0 = u0+ step
    

    Why overthink it?

    If you need an empty if -- and can't work out the logic -- use pass.

     if some-condition-that's-too-complex-for-me-to-invert:
         pass
     else: 
         do real work here
    

    Using JQuery hover with HTML image map

    I found this wonderful mapping script (mapper.js) that I have used in the past. What's different about it is you can hover over the map or a link on your page to make the map area highlight. Sadly it's written in javascript and requires a lot of in-line coding in the HTML - I would love to see this script ported over to jQuery :P

    Also, check out all the demos! I think this example could almost be made into a simple online game (without using flash) - make sure you click on the different camera angles.

    How do I find out if the GPS of an Android device is enabled

    In android, we can easily check whether GPS is enabled in device or not using LocationManager.

    Here is a simple program to Check.

    GPS Enabled or Not :- Add the below user permission line in AndroidManifest.xml to Access Location

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

    Your java class file should be

    public class ExampleApp extends Activity {
        /** Called when the activity is first created. */
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
                Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
            }else{
                showGPSDisabledAlertToUser();
            }
        }
    
        private void showGPSDisabledAlertToUser(){
            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
            alertDialogBuilder.setMessage("GPS is disabled in your device. Would you like to enable it?")
            .setCancelable(false)
            .setPositiveButton("Goto Settings Page To Enable GPS",
                    new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    Intent callGPSSettingIntent = new Intent(
                            android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(callGPSSettingIntent);
                }
            });
            alertDialogBuilder.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int id){
                    dialog.cancel();
                }
            });
            AlertDialog alert = alertDialogBuilder.create();
            alert.show();
        }
    }
    

    The output will looks like

    enter image description here

    enter image description here

    CREATE TABLE LIKE A1 as A2

    Your attempt wasn't that bad. You have to do it with LIKE, yes.

    In the manual it says:

    Use LIKE to create an empty table based on the definition of another table, including any column attributes and indexes defined in the original table.

    So you do:

    CREATE TABLE New_Users  LIKE Old_Users;
    

    Then you insert with

    INSERT INTO New_Users SELECT * FROM Old_Users GROUP BY ID;
    

    But you can not do it in one statement.

    How do I enable NuGet Package Restore in Visual Studio?

    Microsoft has dropped support for the 'Enable NuGet Package Restore' in VS2015 and you need to do some manual changes to either migrate old solutions or add the feature to new solutions. The new feature is described pretty well in NuGet Package Restore.

    There is also a migration guide for existing projects (as previously mentioned) here: NuGet Migration Guide

    When upgrading:

    1. do not delete the .nuget directory.
    2. Delete the nuget.exe and nuget.targets files.
    3. Leave the nuget.config.
    4. Purge each of the project files of any reference to the NuGet targets by hand. The Powershell script mentioned seemed to do more damage than good.

    When creating a new project:

    1. In your Visual Studio 2015 solution, create a Solution Directory called .nuget.

    2. Create an actual directory of the solution directory (where the .sln file lives) and call it .nuget (note that the solution directory is not the same as the actual file system directory even though they have the same name).

    3. Create a file in the .nuget directory called nuget.config.

    4. Add the 'nuget.config' to the solution directory created in step #2.

    5. Place the following text in the nuget.config file:

      <?xml version="1.0" encoding="utf-8"?>
       <configuration>
        <config>
          <add key="repositorypath" value="$\..\..\..\..\Packages" />
        </config>
        <solution>
          <add key="disableSourceControlIntegration" value="true" />
        </solution>
      </configuration>
      

    This configuration file will allow you to consolidate all your packages in a single place so you don't have 20 different copies of the same package floating around on your file system. The relative path will change depending on your solution directory architecture but it should point to a directory common to all your solutions.

    You need to restart visual studio after doing step 5. Nuget won't recognize the changes until you do so.

    Finally, you may have to use the 'Nuget Package Manager for Solutions' to uninstall and then re-install the packages. I don't know if this was a side-effect of the Powershell script I ran or just a method to kick NuGet back into gear. Once I did all these steps, my complicated build architecture worked flawlessly at bringing down new packages when I checked projects out of TFVC.

    error: Your local changes to the following files would be overwritten by checkout

    This error happens when the branch you are switching to, has changes that your current branch doesn't have.

    If you are seeing this error when you try to switch to a new branch, then your current branch is probably behind one or more commits. If so, run:

    git fetch
    

    You should also remove dependencies which may also conflict with the destination branch.

    For example, for iOS developers:

    pod deintegrate
    

    then try checking out a branch again.

    If the desired branch isn't new you can either cherry pick a commit and fix the conflicts or stash the changes and then fix the conflicts.

    1. Git Stash (recommended)

    git stash
    git checkout <desiredBranch>
    git stash apply
    

    2. Cherry pick (more work)

    git add <your file>
    git commit -m "Your message"
    git log
    

    Copy the sha of your commit. Then discard unwanted changes:

    git checkout .
    git checkout -- . 
    git clean -f -fd -fx
    

    Make sure your branch is up to date:

    git fetch
    

    Then checkout to the desired branch

    git checkout <desiredBranch>
    

    Then cherry pick the other commit:

    git cherry-pick <theSha>
    

    Now fix the conflict.

    1. Otherwise, your other option is to abandon your current branches changes with:
    git checkout -f branch
    

    PowerMockito mock single static method and return object

    What you want to do is a combination of part of 1 and all of 2.

    You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

    But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

    From the javadoc:

    Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

    The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

    Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

    import static org.mockito.Mockito.*;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.mockito.invocation.InvocationOnMock;
    import org.mockito.stubbing.Answer;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    class ClassWithStatics {
      public static String getString() {
        return "String";
      }
    
      public static int getInt() {
        return 1;
      }
    }
    
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(ClassWithStatics.class)
    public class StubJustOneStatic {
      @Test
      public void test() {
        PowerMockito.mockStatic(ClassWithStatics.class);
    
        when(ClassWithStatics.getString()).thenReturn("Hello!");
    
        System.out.println("String: " + ClassWithStatics.getString());
        System.out.println("Int: " + ClassWithStatics.getInt());
      }
    }
    

    The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

    Sorting object property by values

    function sortObjByValue(list){
     var sortedObj = {}
     Object.keys(list)
      .map(key => [key, list[key]])
      .sort((a,b) => a[1] > b[1] ? 1 : a[1] < b[1] ? -1 : 0)
      .forEach(data => sortedObj[data[0]] = data[1]);
     return sortedObj;
    }
    sortObjByValue(list);
    

    Github Gist Link

    Pass Arraylist as argument to function

    It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.

    If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter

    public void AnalyseArray(ArrayList<Integer> theList){}
    

    and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);

    PS: Some maybe helpful Information to Variables and parameters.

    How can I delete using INNER JOIN with SQL Server?

    This is a simple query to delete the records from two table at a time.

    DELETE table1.* ,
           table2.* 
    FROM table1 
    INNER JOIN table2 ON table1.id= table2.id where table1.id ='given_id'
    

    How to select top n rows from a datatable/dataview in ASP.NET

    public DataTable TopDataRow(DataTable dt, int count)
        {
            DataTable dtn = dt.Clone();
            int i = 0;
            foreach (DataRow row in dt.Rows)
            {
                if (i < count)
                {
                    dtn.ImportRow(row);
                    i++;
                }
                if (i > count)
                    break;
            }
            return dtn;
        }
    

    How to get the difference (only additions) between two files in linux

    All of the below is copied directly from @TomOnTime's serverfault answer here:

    Show lines that only exist in file a: (i.e. what was deleted from a)

    comm -23 a b
    

    Show lines that only exist in file b: (i.e. what was added to b)

    comm -13 a b
    

    Show lines that only exist in one file or the other: (but not both)

    comm -3 a b | sed 's/^\t//'
    

    (Warning: If file a has lines that start with TAB, it (the first TAB) will be removed from the output.)

    NOTE: Both files need to be sorted for "comm" to work properly. If they aren't already sorted, you should sort them:

    sort <a >a.sorted
    sort <b >b.sorted
    comm -12 a.sorted b.sorted
    

    If the files are extremely long, this may be quite a burden as it requires an extra copy and therefore twice as much disk space.

    Edit: note that the command can be written more concisely using process substitution (thanks to @phk for the comment):

    comm -12 <(sort < a) <(sort < b)
    

    How do I know if jQuery has an Ajax request pending?

    We have to utilize $.ajax.abort() method to abort request if the request is active. This promise object uses readyState property to check whether the request is active or not.

    HTML

    <h3>Cancel Ajax Request on Demand</h3>
    <div id="test"></div>
    <input type="button" id="btnCancel" value="Click to Cancel the Ajax Request" />
    

    JS Code

    //Initial Message
    var ajaxRequestVariable;
    $("#test").html("Please wait while request is being processed..");
    
    //Event handler for Cancel Button
    $("#btnCancel").on("click", function(){
    if (ajaxRequestVariable !== undefined)
    
    if (ajaxRequestVariable.readyState > 0 && ajaxRequestVariable.readyState < 4)
    {
      ajaxRequestVariable.abort();
      $("#test").html("Ajax Request Cancelled.");
    }
    });
    
    //Ajax Process Starts
    ajaxRequestVariable = $.ajax({
                method: "POST",
                url: '/echo/json/',
                contentType: "application/json",
                cache: false,
                dataType: "json",
                data: {
            json: JSON.encode({
             data:
                 [
                                {"prop1":"prop1Value"},
                        {"prop1":"prop2Value"}
                      ]         
            }),
            delay: 11
        },
    
                success: function (response) {
                $("#test").show();
                $("#test").html("Request is completed");           
                },
                error: function (error) {
    
                },
                complete: function () {
    
                }
            });
    

    What is the purpose of the single underscore "_" variable in Python?

    _ has 3 main conventional uses in Python:

    1. To hold the result of the last executed expression(/statement) in an interactive interpreter session (see docs). This precedent was set by the standard CPython interpreter, and other interpreters have followed suit

    2. For translation lookup in i18n (see the gettext documentation for example), as in code like

      raise forms.ValidationError(_("Please enter a correct username"))
      
    3. As a general purpose "throwaway" variable name:

      1. To indicate that part of a function result is being deliberately ignored (Conceptually, it is being discarded.), as in code like:

        label, has_label, _ = text.partition(':')
        
      2. As part of a function definition (using either def or lambda), where the signature is fixed (e.g. by a callback or parent class API), but this particular function implementation doesn't need all of the parameters, as in code like:

        def callback(_):
            return True
        

        [For a long time this answer didn't list this use case, but it came up often enough, as noted here, to be worth listing explicitly.]

      This use case can conflict with the translation lookup use case, so it is necessary to avoid using _ as a throwaway variable in any code block that also uses it for i18n translation (many folks prefer a double-underscore, __, as their throwaway variable for exactly this reason).

      Linters often recognize this use case. For example year, month, day = date() will raise a lint warning if day is not used later in the code. The fix, if day is truly not needed, is to write year, month, _ = date(). Same with lambda functions, lambda arg: 1.0 creates a function requiring one argument but not using it, which will be caught by lint. The fix is to write lambda _: 1.0. An unused variable is often hiding a bug/typo (e.g. set day but use dya in the next line).

    how to change text box value with jQuery?

    <style>
        .form-cus {
            width: 200px;
            margin: auto;
            position: relative;
        }
            .form-cus .putval, .form-cus .getval {
                width: 100%;
            }
            .form-cus .putval {
                position: absolute;
                left: 0px;
                top: 0;
                color: transparent !important;
                box-shadow: 0 0 0 0 !important;
                background-color: transparent !important;
                border: 0px;
                outline: 0 none;
            }
                .form-cus .putval::selection {
                    color: transparent;
                    background: lightblue;
                }
    </style>
    
    <link href="css/bootstrap.min.css" rel="stylesheet" />
    <script src="js/jquery.min.js"></script>
    <div class="form-group form-cus">
        <input class="putval form-control" type="text" id="input" maxlength="16" oninput="xText();">
        <input class="getval form-control" type="text" id="output" maxlength="16">
    </div>
    
    <script type="text/javascript">
        function xText() {
            var x = $("#input").val();
            var x_length = x.length;
            var a = '';
            for (var i = 0; i < x_length; i++) {
                a += "x";
            }
            $("#output").val(a);
         }
        $("#input").click(function(){
         $("#output").trigger("click");
        })
    
    </script>
    

    Undefined Symbols for architecture x86_64: Compiling problems

    There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

    Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

    void Similarity::readData(Scanner& inStream){
    }
    

    not

    void readData(Scanner& inStream){
    }
    

    etc. etc.

    The second one is a function called readData, only the first is the readData method of the Similarity class.

    To be clear about this, in Similarity.h

    void readData(Scanner& inStream);
    

    but in Similarity.cpp

    void Similarity::readData(Scanner& inStream){
    }
    

    std::cin input with spaces?

    It doesn't "fail"; it just stops reading. It sees a lexical token as a "string".

    Use std::getline:

    int main()
    {
       std::string name, title;
    
       std::cout << "Enter your name: ";
       std::getline(std::cin, name);
    
       std::cout << "Enter your favourite movie: ";
       std::getline(std::cin, title);
    
       std::cout << name << "'s favourite movie is " << title;
    }
    

    Note that this is not the same as std::istream::getline, which works with C-style char buffers rather than std::strings.

    Update

    Your edited question bears little resemblance to the original.

    You were trying to getline into an int, not a string or character buffer. The formatting operations of streams only work with operator<< and operator>>. Either use one of them (and tweak accordingly for multi-word input), or use getline and lexically convert to int after-the-fact.

    How can I quickly and easily convert spreadsheet data to JSON?

    Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

    1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

      Rory Gallagher      Guitar
      Gerry McAvoy        Bass
      Rod de'Ath          Drums
      Lou Martin          Keyboards
      Donkey Kong Sioux   Self-Appointed Semi-official Stomper
      

      Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

    2. Save the file as a CSV file.

    3. Copy the contents of the CSV file to the clipboard

    4. Go to http://www.convertcsv.com/csv-to-json.htm

    5. Verify that the "First row is column names" checkbox is checked

    6. Paste the CSV data into the content area

    7. Mash the "Convert CSV to JSON" button

      With the data shown above, you will now have:

      [
        {
          "MUSICIAN":"Rory Gallagher",
          "INSTRUMENT":"Guitar"
        },
        {
          "MUSICIAN":"Gerry McAvoy",
          "INSTRUMENT":"Bass"
        },
        {
          "MUSICIAN":"Rod D'Ath",
          "INSTRUMENT":"Drums"
        },
        {
          "MUSICIAN":"Lou Martin",
          "INSTRUMENT":"Keyboards"
        }
        {
          "MUSICIAN":"Donkey Kong Sioux",
          "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
        }
      ]
      

      With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

    8. Go here: http://jsonlint.com/

    9. Paste the JSON into the content area

    10. Pres the "Validate" button.

    If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

    React: why child component doesn't update when prop changes

    Use the setState function. So you could do

           this.setState({this.state.foo.bar:123}) 
    

    inside the handle event method.

    Once, the state is updated, it will trigger changes, and re-render will take place.

    Installing Numpy on 64bit Windows 7 with Python 2.7.3

    You may also try this, anaconda http://continuum.io/downloads

    But you need to modify your environment variable PATH, so that the anaconda folder is before the original Python folder.

    What does the term "Tuple" Mean in Relational Databases?

    It's a shortened "N-tuple" (like in quadruple, quintuple etc.)

    It's a row of a rowset taken as a whole.

    If you issue:

    SELECT  col1, col2
    FROM    mytable
    

    , whole result will be a ROWSET, and each pair of col1, col2 will be a tuple.

    Some databases can work with a tuple as a whole.

    Like, you can do this:

    SELECT  col1, col2
    FROM    mytable
    WHERE   (col1, col2) =
            (
            SELECT  col3, col4
            FROM    othertable
            )
    

    , which checks that a whole tuple from one rowset matches a whole tuple from another rowset.

    Default visibility for C# classes and members (fields, methods, etc.)?

    By default is private. Unless they're nested, classes are internal.

    How to convert unsigned long to string

    For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,

    as a reference of available options see sprintf

    #include <stdio.h>
    
        int main ()
        {
          unsigned long lval = 123;
          char buffer [50];
          sprintf (buffer, "%lu" , lval );
         }
    

    Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

    Issue: It's because either you are not stopping your application or the application is already somehow running on the same port somehow.

    Solution, Before starting it another time, the earlier application needs to be killed and the port needs to be freed up.

    Depending on your platform you can run the below commands to stop the application,

    on windows

    netstat -anp | find "your application port number"` --> find PID

    taskkill /F /PID

    on Linux,

    netstat -ntpl | grep "your application port number"

    kill pid // pid you will get from previous command

    on Mac OS

    lsof -n -iTCP:"port number"

    kill pid //pid you will get from previous command

    How do I change the font-size of an <option> element within <select>?

    One solution could be to wrap the options inside optgroup:

    _x000D_
    _x000D_
    optgroup { font-size:40px; }
    _x000D_
    <select>
      <optgroup>
        <option selected="selected" class="service-small">Service area?</option>
        <option class="service-small">Volunteering</option>
        <option class="service-small">Partnership &amp; Support</option>
        <option class="service-small">Business Services</option>
      </optgroup>
    </select>
    _x000D_
    _x000D_
    _x000D_

    How to find out what group a given user has?

    On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:

    id -Gn [user]
    

    which is equivalent to groups [user] utility which has been obsoleted on Unix.

    On OS X/Unix, the command id -p [user] is suggested for normal interactive.

    Explanation on the parameters:

    -G, --groups - print all group IDs

    -n, --name - print a name instead of a number, for -ugG

    -p - Make the output human-readable.

    Omit rows containing specific column of NA

    Omit row if either of two specific columns contain <NA>.

    DF[!is.na(DF$x)&!is.na(DF$z),]
    

    "Object doesn't support property or method 'find'" in IE

    The Array.find method support for Microsoft's browsers started with Edge.

    The W3Schools compatibility table states that the support started on version 12, while the Can I Use compatibility table says that the support was unknown between version 12 and 14, being officially supported starting at version 15.

    Convert string to datetime in vb.net

    You can try with ParseExact method

    Sample

    Dim format As String  
    format = "d" 
    Dim provider As CultureInfo = CultureInfo.InvariantCulture
    result = Date.ParseExact(DateString, format, provider)
    

    When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

    Thanks to everyone who answered the question, it really helped clarify things for me. In the end Scott Stanchfield's answer got the closest to how I ended up understanding it, but since I didn't understand him when he first wrote it, I am trying to restate the problem so that hopefully someone else will benefit.

    I'm going to restate the question in terms of List, since it has only one generic parameter and that will make it easier to understand.

    The purpose of the parametrized class (such as List<Date> or Map<K, V> as in the example) is to force a downcast and to have the compiler guarantee that this is safe (no runtime exceptions).

    Consider the case of List. The essence of my question is why a method that takes a type T and a List won't accept a List of something further down the chain of inheritance than T. Consider this contrived example:

    List<java.util.Date> dateList = new ArrayList<java.util.Date>();
    Serializable s = new String();
    addGeneric(s, dateList);
    
    ....
    private <T> void addGeneric(T element, List<T> list) {
        list.add(element);
    }
    

    This will not compile, because the list parameter is a list of dates, not a list of strings. Generics would not be very useful if this did compile.

    The same thing applies to a Map<String, Class<? extends Serializable>> It is not the same thing as a Map<String, Class<java.util.Date>>. They are not covariant, so if I wanted to take a value from the map containing date classes and put it into the map containing serializable elements, that is fine, but a method signature that says:

    private <T> void genericAdd(T value, List<T> list)
    

    Wants to be able to do both:

    T x = list.get(0);
    

    and

    list.add(value);
    

    In this case, even though the junit method doesn't actually care about these things, the method signature requires the covariance, which it is not getting, therefore it does not compile.

    On the second question,

    Matcher<? extends T>
    

    Would have the downside of really accepting anything when T is an Object, which is not the APIs intent. The intent is to statically ensure that the matcher matches the actual object, and there is no way to exclude Object from that calculation.

    The answer to the third question is that nothing would be lost, in terms of unchecked functionality (there would be no unsafe typecasting within the JUnit API if this method was not genericized), but they are trying to accomplish something else - statically ensure that the two parameters are likely to match.

    EDIT (after further contemplation and experience):

    One of the big issues with the assertThat method signature is attempts to equate a variable T with a generic parameter of T. That doesn't work, because they are not covariant. So for example you may have a T which is a List<String> but then pass a match that the compiler works out to Matcher<ArrayList<T>>. Now if it wasn't a type parameter, things would be fine, because List and ArrayList are covariant, but since Generics, as far as the compiler is concerned require ArrayList, it can't tolerate a List for reasons that I hope are clear from the above.

    VBA ADODB excel - read data from Recordset

    I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

    Set cn = CreateObject("ADODB.Connection")
    With cn
     .Provider = "Microsoft.Jet.OLEDB.4.0"
      .ConnectionString = "Data Source=D:\test.xls " & _
      ";Extended Properties=""Excel 8.0;HDR=Yes;"""
    .Open
    End With
    strQuery = "SELECT * FROM [Sheet1$E36:E38]"
    Set rs = cn.Execute(strQuery)
    Do While Not rs.EOF
      For i = 0 To rs.Fields.Count - 1
        Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
        strNaam = rs.Fields(0).Value
      Next
      rs.MoveNext
    Loop
    rs.Close
    

    There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

    How to implement a Boolean search with multiple columns in pandas

    the query() method can do that very intuitively. Express your condition in a string to be evaluated like the following example :

    df = df.query("columnNameA <= @x or columnNameB == @y")
    

    with x and y are declared variables which you can refer to with @

    Difference between setTimeout with and without quotes and parentheses

    i think the setTimeout function that you write is not being run. if you use jquery, you can make it run correctly by doing this :

        function alertMsg() {
          //your func
        }
    
        $(document).ready(function() {
           setTimeout(alertMsg,3000); 
           // the function you called by setTimeout must not be a string.
        });
    

    Removing special characters VBA Excel

    In the case that you not only want to exclude a list of special characters, but to exclude all characters that are not letters or numbers, I would suggest that you use a char type comparison approach.

    For each character in the String, I would check if the unicode character is between "A" and "Z", between "a" and "z" or between "0" and "9". This is the vba code:

    Function cleanString(text As String) As String
        Dim output As String
        Dim c 'since char type does not exist in vba, we have to use variant type.
        For i = 1 To Len(text)
            c = Mid(text, i, 1) 'Select the character at the i position
            If (c >= "a" And c <= "z") Or (c >= "0" And c <= "9") Or (c >= "A" And c <= "Z") Then
                output = output & c 'add the character to your output.
            Else
                output = output & " " 'add the replacement character (space) to your output
            End If
        Next
        cleanString = output
    End Function
    

    The Wikipedia list of Unicode characers is a good quick-start if you want to customize this function a little more.

    This solution has the advantage to be functionnal even if the user finds a way to introduce new special characters. It also faster than comparing two lists together.

    Syntax error near unexpected token 'fi'

    "Then" is a command in bash, thus it needs a ";" or a newline before it.

    #!/bin/bash
    echo "start\n"
    for f in *.jpg
    do
      fname=$(basename "$f")
      echo "fname is $fname\n"
      fname="${filename%.*}"
      echo "fname is $fname\n"
      if [$[fname%2] -eq 1 ]
      then
        echo "removing $fname\n"
        rm $f
      fi
    done
    

    How to pass a value from Vue data to href?

    You need to use v-bind: or its alias :. For example,

    <a v-bind:href="'/job/'+ r.id">
    

    or

    <a :href="'/job/' + r.id">
    

    Python memory usage of numpy arrays

    In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

    I use this code to get a listing of all of them and their size.

    Not sure if locals() or globals() is better here.

    import sys
    import numpy
    from humanize import naturalsize
    
    for size, name in sorted(
        (value.nbytes, name)
        for name, value in locals().items()
        if isinstance(value, numpy.ndarray)):
      print("{:>30}: {:>8}".format(name, naturalsize(size)))
    

    WAMP/XAMPP is responding very slow over localhost

    I had the same problem. Response times were extremly slow and refreshes worked quickly, most of the time. All suggestions made by bicycle didn't help. What seems to help best so far (no slow response times for the last 30mins) was to reset winsock as explained here: http://www.devside.net/wamp-server/wamp-is-running-very-slow

    netsh winsock reset
    netsh int ip reset C:\resetlog.txt
    

    You need to restart after this.

    What size should apple-touch-icon.png be for iPad and iPhone?

    I think this question is about web icons. I've tried giving an icon at 512x512, and on the iPhone 4 simulator it looks great (in the preview) however, when added to the home-screen it's badly pixelated.

    On the good side, if you use a larger icon on the iPad (still with my 512x512 test) it does seem to come out in better quality on the iPad. Hopefully the iPhone 4 rendering is a bug.

    I've opened a bug about this on radar.

    EDIT:

    I'm currently using a 114x114 icon in hopes that it'll look good on the iPhone 4 when it is released. If the iPhone 4 still has a bug when it comes out, I'm going to optimize the icon for the iPad (crisp and no resize at 72x72), and then let it scale down for old iPhones.

    What is the best way to redirect a page using React Router?

    You also can Redirect within the Route as follows. This is for handle invalid routes.

    <Route path='*' render={() => 
         (
           <Redirect to="/error"/>
         )
    }/>
    

    Static Block in Java

    yes, static block is used for initialize the code and it will load at the time JVM start for execution.

    static block is used in previous versions of java but in latest version it doesn't work.