Programs & Examples On #Argument validation

How can I split a delimited string into an array in PHP?

Use explode() or preg_split() function to split the string in php with given delimiter

// Use preg_split() function 
$string = "123,456,78,000";  
$str_arr = preg_split ("/\,/", $string);  
print_r($str_arr); 
  
// use of explode 
$string = "123,46,78,000"; 
$str_arr = explode (",", $string);  
print_r($str_arr); 

PHP error: Notice: Undefined index:

This are just php notice messages,it seems php.ini configurations are not according vtiger standards, you can disable this message by setting error reporting to E_ALL & ~E_NOTICE in php.ini For example error_reporting(E_ALL&~E_NOTICE) and then restart apache to reflect changes.

How to convert entire dataframe to numeric while preserving decimals?

df2 <- data.frame(apply(df1, 2, function(x) as.numeric(as.character(x))))

How to call window.alert("message"); from C#?

Do you mean, a message box?

MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx

How do I properly set the permgen size?

Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.

CURRENT_DATE/CURDATE() not working as default DATE value

According to this documentation, starting in MySQL 8.0.13, you will be able to specify:

CREATE TABLE INVOICE(
    INVOICEDATE DATE DEFAULT (CURRENT_DATE)
)

Unfortunately, as of today, that version is not yet released. You can check here for the latest updates.

How to connect mySQL database using C++

I had to include -lmysqlcppconn to my build in order to get it to work.

Single quotes vs. double quotes in Python

If the string you have contains one, then you should use the other. For example, "You're able to do this", or 'He said "Hi!"'. Other than that, you should simply be as consistent as you can (within a module, within a package, within a project, within an organisation).

If your code is going to be read by people who work with C/C++ (or if you switch between those languages and Python), then using '' for single-character strings, and "" for longer strings might help ease the transition. (Likewise for following other languages where they are not interchangeable).

The Python code I've seen in the wild tends to favour " over ', but only slightly. The one exception is that """these""" are much more common than '''these''', from what I have seen.

How to center a Window in Java?

From this link

If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it.

Passing structs to functions

bool data(sampleData *data)
{
}

You need to tell the method which type of struct you are using. In this case, sampleData.

Note: In this case, you will need to define the struct prior to the method for it to be recognized.

Example:

struct sampleData
{
   int N;
   int M;
   // ...
};

bool data(struct *sampleData)
{

}

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

      sampleData sd;
      data(&sd);

}

Note 2: I'm a C guy. There may be a more c++ish way to do this.

String parsing in Java with delimiter tab "\t" using split

You can use yourstring.split("\x09"); I tested it, and it works.

C# Generics and Type Checking

For everyone that says checking types and doing something based on the type is not a great idea for generics I sort of agree but I think there could be some circumstances where this perfectly makes sense.

For example if you have a class that say is implemented like so (Note: I am not showing everything that this code does for simplicity and have simply cut and pasted into here so it may not build or work as intended like the entire code does but it gets the point across. Also, Unit is an enum):

public class FoodCount<TValue> : BaseFoodCount
{
    public TValue Value { get; set; }

    public override string ToString()
    {
        if (Value is decimal)
        {
            // Code not cleaned up yet
            // Some code and values defined in base class

            mstrValue = Value.ToString();
            decimal mdecValue;
            decimal.TryParse(mstrValue, out mdecValue);

            mstrValue = decimal.Round(mdecValue).ToString();

            mstrValue = mstrValue + mstrUnitOfMeasurement;
            return mstrValue;
        }
        else
        {
            // Simply return a string
            string str = Value.ToString() + mstrUnitOfMeasurement;
            return str;
        }
    }
}

...

public class SaturatedFat : FoodCountWithDailyValue<decimal>
{
    public SaturatedFat()
    {
        mUnit = Unit.g;
    }

}

public class Fiber : FoodCount<int>
{
    public Fiber()
    {
        mUnit = Unit.g;
    }
}

public void DoSomething()
{
       nutritionFields.SaturatedFat oSatFat = new nutritionFields.SaturatedFat();

       string mstrValueToDisplayPreFormatted= oSatFat.ToString();
}

So in summary, I think there are valid reasons why you might want to check to see what type the generic is, in order to do something special.

DataGridView.Clear()

all you need to do is clear your datatable before you fill it... and then just set it as you dgv's datasource

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

Get Memory Usage in Android

Since the OP asked about CPU usage AND memory usage (accepted answer only shows technique to get cpu usage), I'd like to recommend the ActivityManager class and specifically the accepted answer from this question: How to get current memory usage in android?

Get timezone from users browser using moment(timezone).js

Using Moment library, see their website -> https://momentjs.com/timezone/docs/#/using-timezones/converting-to-zone/

i notice they also user their own library in their website, so you can have a try using the browser console before installing it

moment().tz(String);

The moment#tz mutator will change the time zone and update the offset.

moment("2013-11-18").tz("America/Toronto").format('Z'); // -05:00
moment("2013-11-18").tz("Europe/Berlin").format('Z');   // +01:00

This information is used consistently in other operations, like calculating the start of the day.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.format();                     // 2013-11-18T11:55:00-05:00
m.startOf("day").format();      // 2013-11-18T00:00:00-05:00
m.tz("Europe/Berlin").format(); // 2013-11-18T06:00:00+01:00
m.startOf("day").format();      // 2013-11-18T00:00:00+01:00

Without an argument, moment#tz returns:

    the time zone name assigned to the moment instance or
    undefined if a time zone has not been set.

var m = moment.tz("2013-11-18 11:55", "America/Toronto");
m.tz();  // America/Toronto
var m = moment.tz("2013-11-18 11:55");
m.tz() === undefined;  // true

Setting new value for an attribute using jQuery

It is working you have to check attr after assigning value

LiveDemo

$('#amount').attr( 'datamin','1000');

alert($('#amount').attr( 'datamin'));?

UTF-8, UTF-16, and UTF-32

In short:

  • UTF-8: Variable-width encoding, backwards compatible with ASCII. ASCII characters (U+0000 to U+007F) take 1 byte, code points U+0080 to U+07FF take 2 bytes, code points U+0800 to U+FFFF take 3 bytes, code points U+10000 to U+10FFFF take 4 bytes. Good for English text, not so good for Asian text.
  • UTF-16: Variable-width encoding. Code points U+0000 to U+FFFF take 2 bytes, code points U+10000 to U+10FFFF take 4 bytes. Bad for English text, good for Asian text.
  • UTF-32: Fixed-width encoding. All code points take four bytes. An enormous memory hog, but fast to operate on. Rarely used.

In long: see Wikipedia: UTF-8, UTF-16, and UTF-32.

Syntax error near unexpected token 'fi'

Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.

Use superscripts in R axis labels

It works the same way for axes: parse(text='70^o*N') will raise the o as a superscript (the *N is to make sure the N doesn't get raised too).

labelsX=parse(text=paste(abs(seq(-100, -50, 10)), "^o ", "*W", sep=""))
labelsY=parse(text=paste(seq(50,100,10), "^o ", "*N", sep=""))
plot(-100:-50, 50:100, type="n", xlab="", ylab="", axes=FALSE)
axis(1, seq(-100, -50, 10), labels=labelsX)
axis(2, seq(50, 100, 10), labels=labelsY)
box()

Adding HTML entities using CSS content

In CSS you need to use a Unicode escape sequence in place of HTML Entities. This is based on the hexadecimal value of a character.

I found that the easiest way to convert symbol to their hexadecimal equivalent is, such as from ▾ (&#9662;) to \25BE is to use the Microsoft calculator =)

Yes. Enable programmers mode, turn on the decimal system, enter 9662, then switch to hex and you'll get 25BE. Then just add a backslash \ to the beginning.

How to update a value, given a key in a hashmap?

The simplified Java 8 way:

map.put(key, map.getOrDefault(key, 0) + 1);

This uses the method of HashMap that retrieves the value for a key, but if the key can't be retrieved it returns the specified default value (in this case a '0').

This is supported within core Java: HashMap<K,V> getOrDefault(Object key, V defaultValue)

How do I execute .js files locally in my browser?

Around 1:51 in the video, notice how she puts a <script> tag in there? The way it works is like this:

Create an html file (that's just a text file with a .html ending) somewhere on your computer. In the same folder that you put index.html, put a javascript file (that's just a textfile with a .js ending - let's call it game.js). Then, in your index.html file, put some html that includes the script tag with game.js, like Mary did in the video. index.html should look something like this:

<html>
    <head>
        <script src="game.js"></script>
    </head>
</html>

Now, double click on that file in finder, and it should open it up in your browser. To open up the console to see the output of your javascript code, hit Command-alt-j (those three buttons at the same time).

Good luck on your journey, hope it's as fun for you as it has been for me so far :)

Drop multiple tables in one shot in MySQL

A lazy way of doing this if there are alot of tables to be deleted.

  1. Get table using the below

    • For sql server - SELECT CONCAT(name,',') Table_Name FROM SYS.tables;
    • For oralce - SELECT CONCAT(TABLE_NAME,',') FROM SYS.ALL_TABLES;
  2. Copy and paste the table names from the result set and paste it after the DROP command.

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

Wipe data/Factory reset through ADB

After a lot of digging around I finally ended up downloading the source code of the recovery section of Android. Turns out you can actually send commands to the recovery.

 * The arguments which may be supplied in the recovery.command file:
 *   --send_intent=anystring - write the text out to recovery.intent
 *   --update_package=path - verify install an OTA package file
 *   --wipe_data - erase user data (and cache), then reboot
 *   --wipe_cache - wipe cache (but not user data), then reboot
 *   --set_encrypted_filesystem=on|off - enables / diasables encrypted fs

Those are the commands you can use according to the one I found but that might be different for modded files. So using adb you can do this:

adb shell
recovery --wipe_data

Using --wipe_data seemed to do what I was looking for which was handy although I have not fully tested this as of yet.

EDIT:

For anyone still using this topic, these commands may change based on which recovery you are using. If you are using Clockword recovery, these commands should still work. You can find other commands in /cache/recovery/command

For more information please see here: https://github.com/CyanogenMod/android_bootable_recovery/blob/cm-10.2/recovery.c

Bootstrap css hides portion of container below navbar navbar-fixed-top

I know this thread is old, but i just got into that exactly problem and i fixed it by just using the page-header class in my page, under the nav. Also i used the <nav> tag instead of <div> but i am not sure it would present any different behavior.

Using the page-header as a container for the page, you won't need to mess with the <body>, only if you disagree with the default space that the page-header gives you.

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
   <div class="container-fluid">_x000D_
        <nav class="navbar navbar-default navbar-fixed-top">_x000D_
    _x000D_
            <div class="navbar-header">_x000D_
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
                <a class="navbar-brand" href="#">Bootstrap</a>_x000D_
            </div>_x000D_
            <div id="navbar" class="navbar-collapse collapse">_x000D_
                <ul class="nav navbar-nav">_x000D_
                    <li class="active"><a href="#">Home</a></li>_x000D_
                    <li class="dropdown">_x000D_
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>_x000D_
                            <ul class="dropdown-menu">_x000D_
                                <li><a href="#">Action</a></li>_x000D_
                                <li><a href="#">Another action</a></li>_x000D_
                                <li><a href="#">Something else here</a></li>_x000D_
                                <li role="separator" class="divider"></li>_x000D_
                                <li class="dropdown-header">Nav header</li>_x000D_
                                <li><a href="#">Separated link</a></li>_x000D_
                                <li><a href="#">One more separated link</a></li>_x000D_
                            </ul>_x000D_
                        </li>_x000D_
                </ul>_x000D_
                <div class="navbar-right">_x000D_
                </div>_x000D_
            </div>_x000D_
        </nav>_x000D_
    </div>_x000D_
    <div class="page-header">_x000D_
        <div class="clearfix">_x000D_
            <div class="col-md-12">_x000D_
                <div class="col-md-8 col-sm-6 col-xs-12">_x000D_
                    <h1>Registration form <br /><small>A Bootstrap template showing a registration form with standard fields</small></h1>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
        <div class="container">_x000D_
        <div class="row">_x000D_
            <form role="form">_x000D_
                <div class="col-lg-6">_x000D_
                    <div class="well well-sm"><strong><span class="glyphicon glyphicon-asterisk"></span>Required Field</strong></div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputName">Enter Name</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="text" class="form-control" name="InputName" id="InputName" placeholder="Enter Name" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputEmail">Enter Email</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="email" class="form-control" id="InputEmailFirst" name="InputEmail" placeholder="Enter Email" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputEmail">Confirm Email</label>_x000D_
                        <div class="input-group">_x000D_
                            <input type="email" class="form-control" id="InputEmailSecond" name="InputEmail" placeholder="Confirm Email" required>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <div class="form-group">_x000D_
                        <label for="InputMessage">Enter Message</label>_x000D_
                        <div class="input-group">_x000D_
                            <textarea name="InputMessage" id="InputMessage" class="form-control" rows="5" required></textarea>_x000D_
                            <span class="input-group-addon"><span class="glyphicon glyphicon-asterisk"></span></span>_x000D_
                        </div>_x000D_
                    </div>_x000D_
                    <input type="submit" name="submit" id="submit" value="Submit" class="btn btn-info pull-right">_x000D_
                </div>_x000D_
            </form>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

Initializing a struct to 0

The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0[Ref 1].
The second is more readable.

The choice depends on user preference or the one which your coding standard mandates.

[Ref 1] Reference C99 Standard 6.7.8.21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

Good Read:
C and C++ : Partial initialization of automatic structure

How to set a value for a span using jQuery

Syntax:

$(selector).text() returns the text content.

$(selector).text(content) sets the text content.

$(selector).text(function(index, curContent)) sets text content using a function.

kaynak: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/

Centering FontAwesome icons vertically and horizontally

I just lowered the height to 28px on the .login-icon [class*='icon-'] Here's the fiddle: http://jsfiddle.net/mZHg7/

.login-icon [class*='icon-']{
    height: 28px;
    width: 50px;
    display: inline-block;
    text-align: center;
    vertical-align: baseline;
}

How to check if an Object is a Collection Type in Java?

Have you thinked about using instanceof ? Like, say

if(myObject instanceof Collection) {
     Collection myCollection = (Collection) myObject;

Although not that pure OOP style, it is however largely used for so-called "type escalation".

Laravel redirect back to original destination after login

For laravel 5.* try these.

return redirect()->intended('/');

or

return Redirect::intended('/');

How to call function of one php file from another php file and pass parameters to it?

files directory:

Project->

-functions.php

-main.php

functions.php

function sum(a,b){
 return a+b;
}
function product(a,b){
return a*b;
}

main.php

require_once "functions.php";
echo "sum of two numbers ". sum(4,2);
echo "<br>"; //  create break line
echo "product of two numbers ".product(2,3);

The Output Is :

sum of two numbers 6 product of two numbers 6

Note: don't write public before function. Public, private, these modifiers can only use when you create class.

Is it possible to hide the cursor in a webpage using CSS or Javascript?

I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.

How can I create numbered map markers in Google Maps V3?

EASIEST SOLUTION - USE SVG

Works in: in IE9, IE10, FF, Chrome, Safari

(if you are using other browsers please "Run code snippet" and place a comment)

No external dependencies besides Google Maps API!

enter image description here

This is quite easy provided that you have your icon in .svg format. If that is the case just add appropriate text element and change its content to fit your needs with JS.

Add something like this to your .svg code (this is text "section" which will be later changed with JS):

<text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">1</text>

Example: (partially copied from @EstevãoLucas)

Important: Use correct <text> tag properties. Note text-anchor="middle" x="50%" y="28" which center longer numbers (more info: How to place and center text in an SVG rectangle)

Use encodeURIComponent() (this probably ensures compatibility with IE9 and 10)

_x000D_
_x000D_
// Most important part (use output as Google Maps icon)_x000D_
function getMarkerIcon(number) {_x000D_
  // inline your SVG image with number variable_x000D_
  var svg = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="40" height="40" viewBox="0 0 40 40"> <defs> <rect id="path-1" width="40" height="40"/> <mask id="mask-2" width="40" height="40" x="0" y="0" fill="white"> <use xlink:href="#path-1"/> </mask> </defs> <g id="Page-1" fill="none" fill-rule="evenodd"> <g id="Phone-Portrait---320" transform="translate(-209 -51)"> <g id="Group" transform="translate(209 51)"> <use id="Rectangle" fill="#FFEB3B" stroke="#F44336" stroke-width="4" mask="url(#mask-2)" xlink:href="#path-1"/> <text id="1" fill="#20539F" font-family="NunitoSans-ExtraBold, Nunito Sans" font-size="18" font-weight="600" letter-spacing=".104" text-anchor="middle" x="50%" y="28">' + number + '</text> </g> </g> </g> </svg>';_x000D_
  // use SVG without base64 see: https://css-tricks.com/probably-dont-base64-svg/_x000D_
  return 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(svg);_x000D_
}_x000D_
_x000D_
// Standard Maps API code_x000D_
var markers = [_x000D_
  [1, -14.2350040, -51.9252800],_x000D_
  [2, -34.028249, 151.157507],_x000D_
  [3, 39.0119020, -98.4842460],_x000D_
  [5, 48.8566140, 2.3522220],_x000D_
  [9, 38.7755940, -9.1353670],_x000D_
  [12, 12.0733335, 52.8234367],_x000D_
];_x000D_
_x000D_
function initializeMaps() {_x000D_
  var myLatLng = {_x000D_
    lat: -25.363,_x000D_
    lng: 131.044_x000D_
  };_x000D_
_x000D_
  var map = new google.maps.Map(document.getElementById('map_canvas'), {_x000D_
    zoom: 4,_x000D_
    center: myLatLng_x000D_
  });_x000D_
_x000D_
  var bounds = new google.maps.LatLngBounds();_x000D_
_x000D_
  markers.forEach(function(point) {_x000D_
      var pos = new google.maps.LatLng(point[1], point[2]);_x000D_
_x000D_
      new google.maps.Marker({_x000D_
        position: pos,_x000D_
        map: map,_x000D_
        icon: getMarkerIcon(point[0]),         _x000D_
      });_x000D_
_x000D_
      bounds.extend(pos);_x000D_
  });_x000D_
_x000D_
  map.fitBounds(bounds);_x000D_
}_x000D_
_x000D_
initializeMaps();
_x000D_
#map_canvas {_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link rel="stylesheet" href="style.css">_x000D_
    _x000D_
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>        _x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="map_canvas"></div>_x000D_
  </body>_x000D_
  _x000D_
  <script src="script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

More info about inline SVG in Google Maps: https://robert.katzki.de/posts/inline-svg-as-google-maps-marker

What's the best practice to "git clone" into an existing folder?

Don't clone, fetch instead. In the repo:

git init
git remote add origin $url_of_clone_source
git fetch origin
git checkout -b master --track origin/master # origin/master is clone's default

Then you can reset the tree to get the commit you want:

git reset origin/master # or whatever commit you think is proper...

and you are like you cloned.

The interesting question here (and the one without answer): How to find out which commit your naked tree was based on, hence to which position to reset to.

Limit results in jQuery UI Autocomplete

If the results come from a mysql query, it is more efficient to limit directly the mysql result:

select [...] from [...] order by [...] limit 0,10

where 10 is the max numbers of rows you want

django templates: include and extends

From Django docs:

The include tag should be considered as an implementation of "render this subtemplate and include the HTML", not as "parse this subtemplate and include its contents as if it were part of the parent". This means that there is no shared state between included templates -- each include is a completely independent rendering process.

So Django doesn't grab any blocks from your commondata.html and it doesn't know what to do with rendered html outside blocks.

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Error: macro names must be identifiers using #ifdef 0

#ifdef 0
...
#endif

#ifdef expect a macro rather than expression when using constant or expression

#if 0
...
#endif

or

#if !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

if #ifdef is used the it reports this error

#ifdef !defined(PP_CHECK) || defined(PP_CHECK_OTHER)
..
#endif

Where #ifdef expect a macro rather than macro expresssion

Batch script to delete files

Consider that the files you need to delete have an extension txt and is located in the location D:\My Folder, then you could use the below code inside the bat file.

cd "D:\My Folder"
DEL *.txt 

Sort Pandas Dataframe by Date

The data containing the date column can be read by using the below code:

data = pd.csv(file_path,parse_dates=[date_column])

Once the data is read by using the above line of code, the column containing the information about the date can be accessed using pd.date_time() like:

pd.date_time(data[date_column], format = '%d/%m/%y')

to change the format of date as per the requirement.

Maven command to determine which settings.xml file Maven is using

The M2_HOME environment variable for the global one. See Settings Reference:

The settings element in the settings.xml file contains elements used to define values which configure Maven execution in various ways, like the pom.xml, but should not be bundled to any specific project, or distributed to an audience. These include values such as the local repository location, alternate remote repository servers, and authentication information. There are two locations where a settings.xml file may live:

  • The Maven install: $M2_HOME/conf/settings.xml
  • A user's install: ${user.home}/.m2/settings.xml

Check if value is in select list with JQuery

if ($select.find('option[value=' + val + ']').length) {...}

What's the difference setting Embed Interop Types true and false in Visual Studio?

I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).

The practical difference comes when using a local branch named differently:

  • git checkout -b mybranch origin/abranch will create mybranch and track origin/abranch
  • git checkout --track origin/abranch will only create 'abranch', not a branch with a different name.

(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch)


Note: with Git 2.23 (Q3 2019), that would use the new command git switch:

git switch -c <branch> --track <remote>/<branch>

If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote configuration variable, we'll use that one for the purposes of disambiguation, even if the <branch> isn't unique across all remotes.
Set it to e.g. checkout.defaultRemote=origin to always checkout remote branches from there if <branch> is ambiguous but exists on the 'origin' remote.

Here, '-c' is the new '-b'.


First, some background: Tracking means that a local branch has its upstream set to a remote branch:

# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch

git checkout -b branch origin/branch will:

  • create/reset branch to the point referenced by origin/branch.
  • create the branch branch (with git branch) and track the remote tracking branch origin/branch.

When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote and branch.<name>.merge configuration entries) so that git pull will appropriately merge from the remote-tracking branch.
This behavior may be changed via the global branch.autosetupmerge configuration flag. That setting can be overridden by using the --track and --no-track options, and changed later using git branch --set-upstream-to.


And git checkout --track origin/branch will do the same as git branch --set-upstream-to):

 # or, since 1.7.0
 git branch --set-upstream upstream/branch branch
 # or, since 1.8.0 (October 2012)
 git branch --set-upstream-to upstream/branch branch
 # the short version remains the same:
 git branch -u upstream/branch branch

It would also set the upstream for 'branch'.

(Note: git1.8.0 will deprecate git branch --set-upstream and replace it with git branch -u|--set-upstream-to: see git1.8.0-rc1 announce)


Having an upstream branch registered for a local branch will:

  • tell git to show the relationship between the two branches in git status and git branch -v.
  • directs git pull without arguments to pull from the upstream when the new branch is checked out.

See "How do you make an existing git branch track a remote branch?" for more.

Generate Json schema from XML schema (XSD)

True, but after turning json to xml with xmlspy, you can use trang application (http://www.thaiopensource.com/relaxng/trang.html) to create an xsd from xml file(s).

How to enter a series of numbers automatically in Excel

I find it easier using this formula

=IF(B2<>"",TEXT(ROW(A1),"IR-0000"),"")

Need to paste this formula at A2, that means when you are encoding data at B cell the A cell will automatically input the serial code and when there's no data the cell will stay blank....you can change the "IR" to any first letter code you want to be placed in your row.

Hope it helps

Where does Jenkins store configuration files for the jobs it runs?

Jenkins 1.627, OS X 10.10.5 /Users/Shared/Jenkins/Home/jobs/{project_name}/config.xml

How to get POST data in WebAPI?

I found for my use case this was much more useful, hopefully it helps someone else that spent time on this answer applying it

public IDictionary<string, object> GetBodyPropsList()
        {
            var contentType = Request.Content.Headers.ContentType.MediaType;
            var requestParams = Request.Content.ReadAsStringAsync().Result;

            if (contentType == "application/json")
            {
                return Newtonsoft.Json.JsonConvert.DeserializeObject<IDictionary<string, object>>(requestParams);
            }
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

Why do I get access denied to data folder when using adb?

Starting from API level 8 (Android 2.2), for the debuggable application (the one built by Android Studio all the times unless the release build was requested), you can use the shell run-as command to run a command or executable as a specific user/application or just switch to the UID of your application so you can access its data directory.

List directory content of yourapp:

run-as com.yourapp ls -l /data/data/com.yourapp

Switch to UID of com.yourapp and run all further commands using that uid (until you call exit):

run-as com.yourapp
cd /data/data/com.yourapp
ls -l
exit

 
Note 1: there is a known issue with some HTC Desire phones. Because of a non-standard owner/permissions of the /data/data directory, run-as command fails to run on those phones.

Note 2: As pointed in the comments by @Avio: run-as has issues also with Samsung Galaxy S phones running Cyanogenmod at any version (from 7 to 10.1) because on this platform /data/data is a symlink to /datadata. One way to solve the issue is to replace the symlink with the actual directory (unfortunately this usually requires root access).

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

The error is because you have not saved the files after creating them.

Try saving all the file by clicking "Save All" on the Editor.

You can see the number of files which are not saved by looking below the "File" menu shown using blue color.

Why does C# XmlDocument.LoadXml(string) fail when an XML header is included?

This worked for me:

var xdoc = new XmlDocument { XmlResolver = null };  
xdoc.LoadXml(xmlFragment);

Clear icon inside input text

Here's a jQuery plugin (and a demo at the end).

http://jsfiddle.net/e4qhW/3/

I did it mostly to illustrate an example (and a personal challenge). Although upvotes are welcome, the other answers are well handed out on time and deserve their due recognition.

Still, in my opinion, it is over-engineered bloat (unless it makes part of a UI library).

Javascript seconds to minutes and seconds

I was thinking of a faster way to get this done and this is what i came up with

var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}

If we want to convert "time" to minutes and seconds, for example:

// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1

How to add comments into a Xaml file in WPF?

You can't insert comments inside xml tags.

Bad

<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<!-- Cool comment -->
xmlns:System="clr-namespace:System;assembly=mscorlib">

Good

<Window xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib">
<!-- Cool comment -->

In the shell, what does " 2>&1 " mean?

That construct sends the standard error stream (stderr) to the current location of standard output (stdout) - this currency issue appears to have been neglected by the other answers.

You can redirect any output handle to another by using this method but it's most often used to channel stdout and stderr streams into a single stream for processing.

Some examples are:

# Look for ERROR string in both stdout and stderr.
foo 2>&1 | grep ERROR

# Run the less pager without stderr screwing up the output.
foo 2>&1 | less

# Send stdout/err to file (with append) and terminal.
foo 2>&1 |tee /dev/tty >>outfile

# Send stderr to normal location and stdout to file.
foo >outfile1 2>&1 >outfile2

Note that that last one will not direct stderr to outfile2 - it redirects it to what stdout was when the argument was encountered (outfile1) and then redirects stdout to outfile2.

This allows some pretty sophisticated trickery.

How to increment a datetime by one day?

A short solution without libraries at all. :)

d = "8/16/18"
day_value = d[(d.find('/')+1):d.find('/18')]
tomorrow = f"{d[0:d.find('/')]}/{int(day_value)+1}{d[d.find('/18'):len(d)]}".format()
print(tomorrow)
# 8/17/18

Make sure that "string d" is actually in the form of %m/%d/%Y so that you won't have problems transitioning from one month to the next.

on change event for file input element

Give unique class and different id for file input

           $("#tab-content").on('change',class,function()
               {
                  var id=$(this).attr('id');
                      $("#"+id).trigger(your function); 
               //for name of file input  $("#"+id).attr("name");
               });

Is it better to use std::memcpy() or std::copy() in terms to performance?

I'm going to go against the general wisdom here that std::copy will have a slight, almost imperceptible performance loss. I just did a test and found that to be untrue: I did notice a performance difference. However, the winner was std::copy.

I wrote a C++ SHA-2 implementation. In my test, I hash 5 strings using all four SHA-2 versions (224, 256, 384, 512), and I loop 300 times. I measure times using Boost.timer. That 300 loop counter is enough to completely stabilize my results. I ran the test 5 times each, alternating between the memcpy version and the std::copy version. My code takes advantage of grabbing data in as large of chunks as possible (many other implementations operate with char / char *, whereas I operate with T / T * (where T is the largest type in the user's implementation that has correct overflow behavior), so fast memory access on the largest types I can is central to the performance of my algorithm. These are my results:

Time (in seconds) to complete run of SHA-2 tests

std::copy   memcpy  % increase
6.11        6.29    2.86%
6.09        6.28    3.03%
6.10        6.29    3.02%
6.08        6.27    3.03%
6.08        6.27    3.03%

Total average increase in speed of std::copy over memcpy: 2.99%

My compiler is gcc 4.6.3 on Fedora 16 x86_64. My optimization flags are -Ofast -march=native -funsafe-loop-optimizations.

Code for my SHA-2 implementations.

I decided to run a test on my MD5 implementation as well. The results were much less stable, so I decided to do 10 runs. However, after my first few attempts, I got results that varied wildly from one run to the next, so I'm guessing there was some sort of OS activity going on. I decided to start over.

Same compiler settings and flags. There is only one version of MD5, and it's faster than SHA-2, so I did 3000 loops on a similar set of 5 test strings.

These are my final 10 results:

Time (in seconds) to complete run of MD5 tests

std::copy   memcpy      % difference
5.52        5.56        +0.72%
5.56        5.55        -0.18%
5.57        5.53        -0.72%
5.57        5.52        -0.91%
5.56        5.57        +0.18%
5.56        5.57        +0.18%
5.56        5.53        -0.54%
5.53        5.57        +0.72%
5.59        5.57        -0.36%
5.57        5.56        -0.18%

Total average decrease in speed of std::copy over memcpy: 0.11%

Code for my MD5 implementation

These results suggest that there is some optimization that std::copy used in my SHA-2 tests that std::copy could not use in my MD5 tests. In the SHA-2 tests, both arrays were created in the same function that called std::copy / memcpy. In my MD5 tests, one of the arrays was passed in to the function as a function parameter.

I did a little bit more testing to see what I could do to make std::copy faster again. The answer turned out to be simple: turn on link time optimization. These are my results with LTO turned on (option -flto in gcc):

Time (in seconds) to complete run of MD5 tests with -flto

std::copy   memcpy      % difference
5.54        5.57        +0.54%
5.50        5.53        +0.54%
5.54        5.58        +0.72%
5.50        5.57        +1.26%
5.54        5.58        +0.72%
5.54        5.57        +0.54%
5.54        5.56        +0.36%
5.54        5.58        +0.72%
5.51        5.58        +1.25%
5.54        5.57        +0.54%

Total average increase in speed of std::copy over memcpy: 0.72%

In summary, there does not appear to be a performance penalty for using std::copy. In fact, there appears to be a performance gain.

Explanation of results

So why might std::copy give a performance boost?

First, I would not expect it to be slower for any implementation, as long as the optimization of inlining is turned on. All compilers inline aggressively; it is possibly the most important optimization because it enables so many other optimizations. std::copy can (and I suspect all real world implementations do) detect that the arguments are trivially copyable and that memory is laid out sequentially. This means that in the worst case, when memcpy is legal, std::copy should perform no worse. The trivial implementation of std::copy that defers to memcpy should meet your compiler's criteria of "always inline this when optimizing for speed or size".

However, std::copy also keeps more of its information. When you call std::copy, the function keeps the types intact. memcpy operates on void *, which discards almost all useful information. For instance, if I pass in an array of std::uint64_t, the compiler or library implementer may be able to take advantage of 64-bit alignment with std::copy, but it may be more difficult to do so with memcpy. Many implementations of algorithms like this work by first working on the unaligned portion at the start of the range, then the aligned portion, then the unaligned portion at the end. If it is all guaranteed to be aligned, then the code becomes simpler and faster, and easier for the branch predictor in your processor to get correct.

Premature optimization?

std::copy is in an interesting position. I expect it to never be slower than memcpy and sometimes faster with any modern optimizing compiler. Moreover, anything that you can memcpy, you can std::copy. memcpy does not allow any overlap in the buffers, whereas std::copy supports overlap in one direction (with std::copy_backward for the other direction of overlap). memcpy only works on pointers, std::copy works on any iterators (std::map, std::vector, std::deque, or my own custom type). In other words, you should just use std::copy when you need to copy chunks of data around.

How to search for a part of a word with ElasticSearch

Searching with leading and trailing wildcards is going to be extremely slow on a large index. If you want to be able to search by word prefix, remove leading wildcard. If you really need to find a substring in a middle of a word, you would be better of using ngram tokenizer.

Convert nested Python dict to object?

Here is a nested-ready version with namedtuple:

from collections import namedtuple

class Struct(object):
    def __new__(cls, data):
        if isinstance(data, dict):
            return namedtuple(
                'Struct', data.iterkeys()
            )(
                *(Struct(val) for val in data.values())
            )
        elif isinstance(data, (tuple, list, set, frozenset)):
            return type(data)(Struct(_) for _ in data)
        else:
            return data

=>

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> s = Struct(d)
>>> s.d
['hi', Struct(foo='bar')]
>>> s.d[0]
'hi'
>>> s.d[1].foo
'bar'

Flattening a shallow list in Python

Off the top of my head, you can eliminate the lambda:

reduce(list.__add__, map(list, [mi.image_set.all() for mi in list_of_menuitems]))

Or even eliminate the map, since you've already got a list-comp:

reduce(list.__add__, [list(mi.image_set.all()) for mi in list_of_menuitems])

You can also just express this as a sum of lists:

sum([list(mi.image_set.all()) for mi in list_of_menuitems], [])

Twitter Bootstrap button click to toggle expand/collapse text section above button

Based on the doc

<div class="row">
    <div class="span4 collapse-group">
        <h2>Heading</h2>
        <p class="collapse">Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui. </p>
        <p><a class="btn" href="#">View details &raquo;</a></p>
    </div>
</div>
$('.row .btn').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var $collapse = $this.closest('.collapse-group').find('.collapse');
    $collapse.collapse('toggle');
});

Working demo.

Resize HTML5 canvas to fit window

This worked for me. Pseudocode:

// screen width and height
scr = {w:document.documentElement.clientWidth,h:document.documentElement.clientHeight}
canvas.width = scr.w
canvas.height = scr.h

Also, like devyn said, you can replace "document.documentElement.client" with "inner" for both the width and height:

**document.documentElement.client**Width
**inner**Width
**document.documentElement.client**Height
**inner**Height

and it still works.

How do I align spans or divs horizontally?

You can use

.floatybox {
     display: inline-block;
     width: 123px;
}

If you only need to support browsers that have support for inline blocks. Inline blocks can have width, but are inline, like button elements.

Oh, and you might wnat to add vertical-align: top on the elements to make sure things line up

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

You shouldn't use CascadeType.ALL on @ManyToOne since entity state transitions should propagate from parent entities to child ones, not the other way around.

The @ManyToOne side is always the Child association since it maps the underlying Foreign Key column.

Therefore, you should move the CascadeType.ALL from the @ManyToOne association to the @OneToMany side, which should also use the mappedBy attribute since it's the most efficient one-to-many table relationship mapping.

How do I split a string in Rust?

There's also split_whitespace()

fn main() {
    let words: Vec<&str> = "   foo   bar\t\nbaz   ".split_whitespace().collect();
    println!("{:?}", words);
    // ["foo", "bar", "baz"] 
}

Issue with virtualenv - cannot activate

If wants to open virtual environment on Windows then just remember one thing on giving path use backwards slash not forward.

This is right:

D:\xampp\htdocs\htmldemo\python-virtual-environment>env\Scripts\activate

This is wrong:

D:\xampp\htdocs\htmldemo\python-virtual-environment>env/Scripts/activate

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

This is usually caused by your CSV having been saved along with an (unnamed) index (RangeIndex).

(The fix would actually need to be done when saving the DataFrame, but this isn't always an option.)

Workaround: read_csv with index_col=[0] argument

IMO, the simplest solution would be to read the unnamed column as the index. Specify an index_col=[0] argument to pd.read_csv, this reads in the first column as the index. (Note the square brackets).

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

# Save DataFrame to CSV.
df.to_csv('file.csv')

<!- ->

pd.read_csv('file.csv')

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

# Now try this again, with the extra argument.
pd.read_csv('file.csv', index_col=[0])

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

Note
You could have avoided this in the first place by using index=False if the output CSV was created in pandas, if your DataFrame does not have an index to begin with:

df.to_csv('file.csv', index=False)

But as mentioned above, this isn't always an option.


Stopgap Solution: Filtering with str.match

If you cannot modify the code to read/write the CSV file, you can just remove the column by filtering with str.match:

df 

   Unnamed: 0  a  b  c
0           0  x  x  x
1           1  x  x  x
2           2  x  x  x
3           3  x  x  x
4           4  x  x  x

df.columns
# Index(['Unnamed: 0', 'a', 'b', 'c'], dtype='object')

df.columns.str.match('Unnamed')
# array([ True, False, False, False])

df.loc[:, ~df.columns.str.match('Unnamed')]
 
   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

System.Net.WebException HTTP status code

Maybe something like this...

try
{
    // ...
}
catch (WebException ex)
{
    if (ex.Status == WebExceptionStatus.ProtocolError)
    {
        var response = ex.Response as HttpWebResponse;
        if (response != null)
        {
            Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
        }
        else
        {
            // no http status code available
        }
    }
    else
    {
        // no http status code available
    }
}

How does bitshifting work in Java?

You can use e.g. this API if you would like to see bitString presentation of your numbers. Uncommons Math

Example (in jruby)

bitString = org.uncommons.maths.binary.BitString.new(java.math.BigInteger.new("12").toString(2))
bitString.setBit(1, true)
bitString.toNumber => 14

edit: Changed api link and add a little example

Eclipse hangs on loading workbench

In your workspace you will find hidden folder name .metadata in which you will find another hidden folder ".mylyn" delete it and empty your trash go to task manager stop the process of Eclipse and start again Eclipse this time it will work.

Enjoy!

Display open transactions in MySQL

You can use show innodb status (or show engine innodb status for newer versions of mysql) to get a list of all the actions currently pending inside the InnoDB engine. Buried in the wall of output will be the transactions, and what internal process ID they're running under.

You won't be able to force a commit or rollback of those transactions, but you CAN kill the MySQL process running them, which does essentially boil down to a rollback. It kills the processes' connection and causes MySQL to clean up the mess its left.

Here's what you'd want to look for:

------------
TRANSACTIONS
------------
Trx id counter 0 140151
Purge done for trx's n:o < 0 134992 undo n:o < 0 0
History list length 10
LIST OF TRANSACTIONS FOR EACH SESSION:
---TRANSACTION 0 0, not started, process no 17004, OS thread id 140621902116624
MySQL thread id 10594, query id 10269885 localhost marc
show innodb status

In this case, there's just one connection to the InnoDB engine right now (my login, running the show query). If that line were an actual connection/stuck transaction you'd want to terminate, you'd then do a kill 10594.

How to remove all the punctuation in a string? (Python)

This works, but there might be better solutions.

asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking

Show a popup/message box from a Windows batch file

Here's a PowerShell variant that doesn't require loading assemblies prior to creating the window, however it runs noticeably slower (~+50%) than the PowerShell MessageBox command posted here by @npocmaka:

powershell (New-Object -ComObject Wscript.Shell).Popup("""Operation Completed""",0,"""Done""",0x0)

You can change the last parameter from "0x0" to a value below to display icons in the dialog (see Popup Method for further reference):

        Stop 0x10 Stop
        Question Mark 0x20 Question Mark
        Exclamation Mark 0x30 Exclamation Mark
        Information Mark 0x40 Information Mark

Adapted from the Microsoft TechNet article PowerTip: Use PowerShell to Display Pop-Up Window.

How can I list all the deleted files in a Git repository?

This will get you a list of all files that were deleted in all branches, sorted by their path:

git log --diff-filter=D --summary | grep "delete mode 100" | cut -c 21- | sort > deleted.txt

Works in msysgit (2.6.1.windows.1). Note we need "delete mode 100" as git files may have been commited as mode 100644 or 100755.

How to get the latest record in each group using GROUP BY?

this query return last record for every Form_id:

    SELECT m1.*
     FROM messages m1 LEFT JOIN messages m2
     ON (m1.Form_id = m2.Form_id AND m1.id < m2.id)
     WHERE m2.id IS NULL;

Best way to create enum of strings?

Either set the enum name to be the same as the string you want or, more generally,you can associate arbitrary attributes with your enum values:

enum Strings {
   STRING_ONE("ONE"), STRING_TWO("TWO");
   private final String stringValue;
   Strings(final String s) { stringValue = s; }
   public String toString() { return stringValue; }
   // further methods, attributes, etc.
}

It's important to have the constants at the top, and the methods/attributes at the bottom.

When should we call System.exit in Java

In that case, it's not needed. No extra threads will have been started up, you're not changing the exit code (which defaults to 0) - basically it's pointless.

When the docs say the method never returns normally, it means the subsequent line of code is effectively unreachable, even though the compiler doesn't know that:

System.exit(0);
System.out.println("This line will never be reached");

Either an exception will be thrown, or the VM will terminate before returning. It will never "just return".

It's very rare to be worth calling System.exit() IME. It can make sense if you're writing a command line tool, and you want to indicate an error via the exit code rather than just throwing an exception... but I can't remember the last time I used it in normal production code.

How can I send and receive WebSocket messages on the server side?

JavaScript implementation:

function encodeWebSocket(bytesRaw){
    var bytesFormatted = new Array();
    bytesFormatted[0] = 129;
    if (bytesRaw.length <= 125) {
        bytesFormatted[1] = bytesRaw.length;
    } else if (bytesRaw.length >= 126 && bytesRaw.length <= 65535) {
        bytesFormatted[1] = 126;
        bytesFormatted[2] = ( bytesRaw.length >> 8 ) & 255;
        bytesFormatted[3] = ( bytesRaw.length      ) & 255;
    } else {
        bytesFormatted[1] = 127;
        bytesFormatted[2] = ( bytesRaw.length >> 56 ) & 255;
        bytesFormatted[3] = ( bytesRaw.length >> 48 ) & 255;
        bytesFormatted[4] = ( bytesRaw.length >> 40 ) & 255;
        bytesFormatted[5] = ( bytesRaw.length >> 32 ) & 255;
        bytesFormatted[6] = ( bytesRaw.length >> 24 ) & 255;
        bytesFormatted[7] = ( bytesRaw.length >> 16 ) & 255;
        bytesFormatted[8] = ( bytesRaw.length >>  8 ) & 255;
        bytesFormatted[9] = ( bytesRaw.length       ) & 255;
    }
    for (var i = 0; i < bytesRaw.length; i++){
        bytesFormatted.push(bytesRaw.charCodeAt(i));
    }
    return bytesFormatted;
}

function decodeWebSocket (data){
    var datalength = data[1] & 127;
    var indexFirstMask = 2;
    if (datalength == 126) {
        indexFirstMask = 4;
    } else if (datalength == 127) {
        indexFirstMask = 10;
    }
    var masks = data.slice(indexFirstMask,indexFirstMask + 4);
    var i = indexFirstMask + 4;
    var index = 0;
    var output = "";
    while (i < data.length) {
        output += String.fromCharCode(data[i++] ^ masks[index++ % 4]);
    }
    return output;
}

How to decrypt Hash Password in Laravel

For compare hashed password with the plain text password string you can use the PHP password_verify

if(password_verify('1234567', $crypt_password_string)) {
    // in case if "$crypt_password_string" actually hides "1234567"
}

How to link to a <div> on another page?

Take a look at anchor tags. You can create an anchor with

<div id="anchor-name">Heading Text</div>

and refer to it later with

<a href="http://server/page.html#anchor-name">Link text</a>

Java FileWriter how to write to next Line

You can call the method newLine() provided by java, to insert the new line in to a file.

For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()

"Gradle Version 2.10 is required." Error

In my case the problem was indeed in the distributionURL in gradle-wrapper.properties file and Android Studio auto-fixed inserting

distributionUrl=https://services.gradle.org/distributions/gradle-4.0-20170417000025+0000-all.zip

But this was a wrong URL. The correct one is

distributionUrl=https://services.gradle.org/distributions-snapshots/gradle-4.0-20170417000025+0000-all.zip

Apparently the url changed in gradle's API but not in Android Studio so fixing it by hand solved the problem for me.

Node.js: Difference between req.query[] and req.params

I want to mention one important note regarding req.query , because currently I am working on pagination functionality based on req.query and I have one interesting example to demonstrate to you...

Example:

// Fetching patients from the database
exports.getPatients = (req, res, next) => {

const pageSize = +req.query.pageSize;
const currentPage = +req.query.currentPage;

const patientQuery = Patient.find();
let fetchedPatients;

// If pageSize and currentPage are not undefined (if they are both set and contain valid values)
if(pageSize && currentPage) {
    /**
     * Construct two different queries 
     * - Fetch all patients 
     * - Adjusted one to only fetch a selected slice of patients for a given page
     */
    patientQuery
        /**
         * This means I will not retrieve all patients I find, but I will skip the first "n" patients
         * For example, if I am on page 2, then I want to skip all patients that were displayed on page 1,
         * 
         * Another example: if I am displaying 7 patients per page , I want to skip 7 items because I am on page 2,
         * so I want to skip (7 * (2 - 1)) => 7 items
         */
        .skip(pageSize * (currentPage - 1))

        /**
         * Narrow dont the amound documents I retreive for the current page
         * Limits the amount of returned documents
         * 
         * For example: If I got 7 items per page, then I want to limit the query to only
         * return 7 items. 
         */
        .limit(pageSize);
}
patientQuery.then(documents => {
    res.status(200).json({
        message: 'Patients fetched successfully',
        patients: documents
    });
  });
};

You will noticed + sign in front of req.query.pageSize and req.query.currentPage

Why? If you delete + in this case, you will get an error, and that error will be thrown because we will use invalid type (with error message 'limit' field must be numeric).

Important: By default if you extracting something from these query parameters, it will always be a string, because it's coming the URL and it's treated as a text.

If we need to work with numbers, and convert query statements from text to number, we can simply add a plus sign in front of statement.

Change color of Back button in navigation bar

self.navigationController?.navigationBar.tintColor = UIColor.redColor()

This snippet does the magic. Instead of the redColor, change it to as your wish.

URL Encode a string in jQuery for an AJAX request

Try encodeURIComponent.

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example:

var encoded = encodeURIComponent(str);

PHP json_decode() returns NULL with valid JSON?

Maybe some hidden characters are messing with your json, try this:

$json = utf8_encode($yourString);
$data = json_decode($json);

Find (and kill) process locking port 3000 on Mac

This single command line is easy to remember:

npx kill-port 3000

For a more powerful tool with search:

npx fkill-cli


PS: They use third party javascript packages. npx comes built in with Node.js.

Sources: tweet | github

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

How to split long commands over multiple lines in PowerShell

Another way to break a string across multiple lines is to put an empty expression in the middle of the string, and break it across lines:

sample string:

"stackoverflow stackoverflow stackoverflow stackoverflow stackoverflow"

broken across lines:

"stackoverflow stackoverflow $(
)stackoverflow stack$(
)overflow stackoverflow"

How to calculate cumulative normal distribution?

It may be too late to answer the question but since Google still leads people here, I decide to write my solution here.

That is, since Python 2.7, the math library has integrated the error function math.erf(x)

The erf() function can be used to compute traditional statistical functions such as the cumulative standard normal distribution:

from math import *
def phi(x):
    #'Cumulative distribution function for the standard normal distribution'
    return (1.0 + erf(x / sqrt(2.0))) / 2.0

Ref:

https://docs.python.org/2/library/math.html

https://docs.python.org/3/library/math.html

How are the Error Function and Standard Normal distribution function related?

How do you access a website running on localhost from iPhone browser

If you are using mac (OSX) :

On you mac:

  1. Open Terminal
  2. run "ifconfig"
  3. Find the line with the ip adress "192.xx.x.x"

If you are testing your website with the address : "localhost:8888/mywebsite" (it depends on your MAMP configurations)

On your phone :

  1. Open your browser (e.g Safari)
  2. Enter the URL 192.xxx.x.x:8888/mywebsite

Note : you have to be connected on the same network (wifi)

DataSet panel (Report Data) in SSRS designer is gone

If you are working with SQL 2008 R2 then from View---->Report Data option at bottom

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}

Detect change to selected date with bootstrap-datepicker

All others answers are related to jQuery UI datepicker, but the question is about bootstrap-datepicker.

You can use the on changeDate event to trigger a change event on the related input, and then handle both ways of changing the date from the onChange handler:

changeDate

Fired when the date is changed.

Example:

$('#dp3').datepicker().on('changeDate', function (ev) {
    $('#date-daily').change();
});
$('#date-daily').val('0000-00-00');
$('#date-daily').change(function () {
    console.log($('#date-daily').val());
});

Here is a working fiddle: http://jsfiddle.net/IrvinDominin/frjhgpn8/

Replace last occurrence of a string in a string

Shorthand for accepted answer

function str_lreplace($search, $replace, $subject){ 
    return is_numeric($pos=strrpos($subject,$search))?
    substr_replace($subject,$replace,$pos,strlen($search)):$subject;
}

How can I do a BEFORE UPDATED trigger with sql server?

Full example:

CREATE TRIGGER [dbo].[trig_020_Original_010_010_Gamechanger]
   ON  [dbo].[T_Original]
   AFTER UPDATE
AS 
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @Old_Gamechanger int;
    DECLARE @New_Gamechanger int;

    -- Insert statements for trigger here
    SELECT @Old_Gamechanger = Gamechanger from DELETED;
    SELECT @New_Gamechanger = Gamechanger from INSERTED;

    IF @Old_Gamechanger != @New_Gamechanger

        BEGIN

            INSERT INTO [dbo].T_History(ChangeDate, Reason, Callcenter_ID, Old_Gamechanger, New_Gamechanger)
            SELECT GETDATE(), 'Time for a change', Callcenter_ID, @Old_Gamechanger, @New_Gamechanger
                FROM deleted
            ;

        END

END

How to show "if" condition on a sequence diagram?

If you paste

A.do() {
  if (condition1) {
   X.doSomething
  } else if (condition2) {
   Y.doSomethingElse
  } else {
   donotDoAnything
  }
}

onto https://www.zenuml.com. It will generate a diagram for you.If/else sequence diagram

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

How to wait till the response comes from the $http request, in angularjs?

for people new to this you can also use a callback for example:

In your service:

.factory('DataHandler',function ($http){

   var GetRandomArtists = function(data, callback){
     $http.post(URL, data).success(function (response) {
         callback(response);
      });
   } 
})

In your controller:

    DataHandler.GetRandomArtists(3, function(response){
      $scope.data.random_artists = response;
   });

How to return a class object by reference in C++?

I will show you some examples:

First example, do not return local scope object, for example:

const string &dontDoThis(const string &s)
{
    string local = s;
    return local;
}

You can't return local by reference, because local is destroyed at the end of the body of dontDoThis.

Second example, you can return by reference:

const string &shorterString(const string &s1, const string &s2)
{
    return (s1.size() < s2.size()) ? s1 : s2;
}

Here, you can return by reference both s1 and s2 because they were defined before shorterString was called.

Third example:

char &get_val(string &str, string::size_type ix)
{
    return str[ix];
}

usage code as below:

string s("123456");
cout << s << endl;
char &ch = get_val(s, 0); 
ch = 'A';
cout << s << endl; // A23456

get_val can return elements of s by reference because s still exists after the call.

Fourth example

class Student
{
public:
    string m_name;
    int age;    

    string &getName();
};

string &Student::getName()
{
    // you can return by reference
    return m_name;
}

string& Test(Student &student)
{
    // we can return `m_name` by reference here because `student` still exists after the call
    return stu.m_name;
}

usage example:

Student student;
student.m_name = 'jack';
string name = student.getName();
// or
string name2 = Test(student);

Fifth example:

class String
{
private:
    char *str_;

public:
    String &operator=(const String &str);
};

String &String::operator=(const String &str)
{
    if (this == &str)
    {
        return *this;
    }
    delete [] str_;
    int length = strlen(str.str_);
    str_ = new char[length + 1];
    strcpy(str_, str.str_);
    return *this;
}

You could then use the operator= above like this:

String a;
String b;
String c = b = a;

How to change letter spacing in a Textview?

check out android:textScaleX

Depending on how much spacing you need, this might help. That's the only thing remotely related to letter-spacing in the TextView.

Edit: please see @JerabekJakub's response below for an updated, better method to do this starting with api 21 (Lollipop)

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

Git reset single file in feature branch to be the same as in master

If you want to revert the file to its state in master:

git checkout origin/master [filename]

Check if number is decimal

function is_decimal_value( $a ) {
    $d=0; $i=0;
    $b= str_split(trim($a.""));
    foreach ( $b as $c ) {
        if ( $i==0 && strpos($c,"-") ) continue;
        $i++;
        if ( is_numeric($c) ) continue;
        if ( stripos($c,".") === 0 ) {
            $d++;
            if ( $d > 1 ) return FALSE;
            else continue;
        } else
        return FALSE;
    }
    return TRUE;
}

Known Issues with the above function:

1) Does not support "scientific notation" (1.23E-123), fiscal (leading $ or other) or "Trailing f" (C++ style floats) or "trailing currency" (USD, GBP etc)

2) False positive on string filenames that match a decimal: Please note that for example "10.0" as a filename cannot be distinguished from the decimal, so if you are attempting to detect a type from a string alone, and a filename matches a decimal name and has no path included, it will be impossible to discern.

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

PUT /testIndex
{
    "mappings": {
        "properties": {     <--ADD THIS
            "field1": {
                "type": "integer"
            },
            "field2": {  
                "type": "integer"
            },
            "field3": {
                "type": "string",
                "index": "not_analyzed"
            },
            "field4": {
                "type": "string",
                "analyzer": "autocomplete",
                "search_analyzer": "standard"
            }
        }
    },
    "settings": {
        bla
        bla
        bla
    }
}

Here's a similar command I know works:

curl -v -H "Content-Type: application/json" -H "Authorization: Basic cGC3COJ1c2Vy925hZGFJbXBvcnABCnRl" -X PUT -d '{"mappings":{"properties":{"city":{"type": "text"}}}}' https://35.80.2.21/manzanaIndex

The breakdown for the above curl command is:

PUT /manzanaIndex
{
    "mappings":{
        "properties":{
                "city":{
                    "type": "text"
                }
        }
    }
}

Tar error: Unexpected EOF in archive

I had a similar problem with truncated tar files being produced by a cron job and redirecting standard out to a file fixed the issue.

From talking to a colleague, cron creates a pipe and limits the amount of output that can be sent to standard out. I fixed mine by removing -v from my tar command, making it much less verbose and keeping the error output in the same spot as the rest of my cron jobs. If you need the verbose tar output, you'll need to redirect to a file, though.

How to change default install location for pip

According to pip documentation at

http://pip.readthedocs.org/en/stable/user_guide/#configuration

You will need to specify the default install location within a pip.ini file, which, also according to the website above is usually located as follows

On Unix and Mac OS X the configuration file is: $HOME/.pip/pip.conf

On Windows, the configuration file is: %HOME%\pip\pip.ini

The %HOME% is located in C:\Users\Bob on windows assuming your name is Bob

On linux the $HOME directory can be located by using cd ~

You may have to create the pip.ini file when you find your pip directory. Within your pip.ini or pip.config you will then need to put (assuming your on windows) something like

[global]
target=C:\Users\Bob\Desktop

Except that you would replace C:\Users\Bob\Desktop with whatever path you desire. If you are on Linux you would replace it with something like /usr/local/your/path

After saving the command would then be

pip install pandas

However, the program you install might assume it will be installed in a certain directory and might not work as a result of being installed elsewhere.

Altering a column: null to not null

In my case I had difficulties with the posted answers. I ended up using the following:

ALTER TABLE table_name CHANGE COLUMN column_name column_name VARCHAR(200) NOT NULL DEFAULT '';

Change VARCHAR(200) to your datatype, and optionally change the default value.

If you don't have a default value you're going to have a problem making this change, as default would be null creating a conflict.

ReactNative: how to center text?

Set these styles to image component: { textAlignVertical: "center", textAlign: "center" }

What is the largest TCP/IP network port number allowable for IPv4?

As I understand it, you should only use up to 49151, as from 49152 up to 65535 are reserved for Ephemeral ports

How to check currently internet connection is available or not in android

This will show an dialog error box if there is not network connectivity

    ConnectivityManager connMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected()) {
        // fetch data
    } else {
        new AlertDialog.Builder(this)
            .setTitle("Connection Failure")
            .setMessage("Please Connect to the Internet")
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .setIcon(android.R.drawable.ic_dialog_alert)
            .show();
    }

Is there an easy way to return a string repeated X number of times?

If you only intend to repeat the same character you can use the string constructor that accepts a char and the number of times to repeat it new String(char c, int count).

For example, to repeat a dash five times:

string result = new String('-', 5);
Output: -----

Calling a function of a module by using its name (a string)

For what it's worth, if you needed to pass the function (or class) name and app name as a string, then you could do this:

myFnName  = "MyFn"
myAppName = "MyApp"
app = sys.modules[myAppName]
fn  = getattr(app,myFnName)

manage.py runserver

You need to tell manage.py the local ip address and the port to bind to. Something like python manage.py runserver 192.168.23.12:8000. Then use that same ip and port from the other machine. You can read more about it here in the documentation.

git stash and git pull

When you have changes on your working copy, from command line do:

git stash 

This will stash your changes and clear your status report

git pull

This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge

git stash pop

This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.

if you need to see what is in your stash

git stash list

How do I view Android application specific cache?

Here is the code: replace package_name by your specific package name.

Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.addCategory(Intent.CATEGORY_DEFAULT);
i.setData(Uri.parse("package:package_name"));
startActivity(i);

How to programmatically empty browser cache?

There's no way a browser will let you clear its cache. It would be a huge security issue if that were possible. This could be very easily abused - the minute a browser supports such a "feature" will be the minute I uninstall it from my computer.

What you can do is to tell it not to cache your page, by sending the appropriate headers or using these meta tags:

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

You might also want to consider turning off auto-complete on form fields, although I'm afraid there's a standard way to do it (see this question).

Regardless, I would like to point out that if you are working with sensitive data you should be using SSL. If you aren't using SSL, anyone with access to the network can sniff network traffic and easily see what your user is seeing.

Using SSL also makes some browsers not use caching unless explicitly told to. See this question.

Import CSV into SQL Server (including automatic table creation)

SQL Server Management Studio provides an Import/Export wizard tool which have an option to automatically create tables.

You can access it by right clicking on the Database in Object Explorer and selecting Tasks->Import Data...

From there wizard should be self-explanatory and easy to navigate. You choose your CSV as source, desired destination, configure columns and run the package.

If you need detailed guidance, there are plenty of guides online, here is a nice one: http://www.mssqltips.com/sqlservertutorial/203/simple-way-to-import-data-into-sql-server/

How to deal with persistent storage (e.g. databases) in Docker

When using Docker Compose, simply attach a named volume, for example:

version: '2'
services:
  db:
    image: mysql:5.6
    volumes:
      - db_data:/var/lib/mysql:rw
    environment:
      MYSQL_ROOT_PASSWORD: root
volumes:
  db_data:

HTML Entity Decode

Because @Robert K and @mattcasey both have good code, I thought I'd contribute here with a CoffeeScript version, in case anyone in the future could use it:

    String::unescape = (strict = false) ->
      ###
      # Take escaped text, and return the unescaped version
      #
      # @param string str | String to be used
      # @param bool strict | Stict mode will remove all HTML
      #
      # Test it here:
      # https://jsfiddle.net/tigerhawkvok/t9pn1dn5/
      #
      # Code: https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d
      ###
      # Create a dummy element
      element = document.createElement("div")
      decodeHTMLEntities = (str) ->
        if str? and typeof str is "string"
          unless strict is true
            # escape HTML tags
            str = escape(str).replace(/%26/g,'&').replace(/%23/g,'#').replace(/%3B/g,';')
          else
            str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '')
            str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '')
          element.innerHTML = str
          if element.innerText
            # Do we support innerText?
            str = element.innerText
            element.innerText = ""
          else
            # Firefox
            str = element.textContent
            element.textContent = ""
        unescape(str)
      # Remove encoded or double-encoded tags
      fixHtmlEncodings = (string) ->
        string = string.replace(/\&amp;#/mg, '&#') # The rest, for double-encodings
        string = string.replace(/\&quot;/mg, '"')
        string = string.replace(/\&quote;/mg, '"')
        string = string.replace(/\&#95;/mg, '_')
        string = string.replace(/\&#39;/mg, "'")
        string = string.replace(/\&#34;/mg, '"')
        string = string.replace(/\&#62;/mg, '>')
        string = string.replace(/\&#60;/mg, '<')
        string
      # Run it
      tmp = fixHtmlEncodings(this)
      decodeHTMLEntities(tmp)

See https://jsfiddle.net/tigerhawkvok/t9pn1dn5/7/ or https://gist.github.com/tigerhawkvok/285b8631ed6ebef4446d (includes compiled JS, and is probably updated compared to this answer)

select unique rows based on single distinct column

Quick one in TSQL

SELECT a.*
FROM emails a
INNER JOIN 
  (SELECT email,
    MIN(id) as id
  FROM emails 
  GROUP BY email 
) AS b
  ON a.email = b.email 
  AND a.id = b.id;

Does a "Find in project..." feature exist in Eclipse IDE?

Ctrl + H is the best way! Remember to copy the string before you start searching!

Python time measure function

Elaborating on @Jonathan Ray I think this does the trick a bit better

import time
import inspect

def timed(f:callable):
    start = time.time()
    ret = f()
    elapsed = 1000*(time.time() - start)
    source_code=inspect.getsource(f).strip('\n') 
    logger.info(source_code+":  "+str(elapsed)+" seconds")
    return ret

It allows to take a regular line of code, say a = np.sin(np.pi) and transform it rather simply into

a = timed(lambda: np.sin(np.pi))

so that the timing is printed onto the logger and you can keep the same assignment of the result to a variable you might need for further work.

I suppose in Python 3.8 one could use the := but I do not have 3.8 yet

where does MySQL store database files?

Check your my.cnf file in your MySQL program directory, look for

[mysqld]
datadir=

The datadir is the location where your MySQL database is stored.

java - path to trustStore - set property doesn't work?

You have a typo - it is trustStore.

Apart from setting the variables with System.setProperty(..), you can also use

-Djavax.net.ssl.keyStore=path/to/keystore.jks

SQL Server ORDER BY date and nulls last

If your SQL doesn't support NULLS FIRST or NULLS LAST, the simplest way to do this is to use the value IS NULL expression:

ORDER BY Next_Contact_Date IS NULL, Next_Contact_Date

to put the nulls at the end (NULLS LAST) or

ORDER BY Next_Contact_Date IS NOT NULL, Next_Contact_Date

to put the nulls at the front. This doesn't require knowing the type of the column and is easier to read than the CASE expression.

EDIT: Alas, while this works in other SQL implementations like PostgreSQL and MySQL, it doesn't work in MS SQL Server. I didn't have a SQL Server to test against and relied on Microsoft's documentation and testing with other SQL implementations. According to Microsoft, value IS NULL is an expression that should be usable just like any other expression. And ORDER BY is supposed to take expressions just like any other statement that takes an expression. But it doesn't actually work.

The best solution for SQL Server therefore appears to be the CASE expression.

How to install SQL Server Management Studio 2008 component only

If you have the SQL Server 2008 Installation media, you can install just the Client/Workstation Components. You don't have to install the database engine to install the workstation tools, but if you plan to do Integration Services development, you do need to install the Integration Services Engine on the workstation for BIDS to be able to be used for development. Keep in mind that Visual Studio 2010 does not have BI development support currently, so you have to install BIDS from the SQL Installation media and use the Visual Studio 2008 BI Development Studio that installs under the SQL Server 2008 folder in Program Files if you need to do any SSIS, SSRS, or SSAS development from the workstation.

As mentioned in the comments you can download Management Studio Express free from Microsoft, but if you already have the installation media for SQL Server Standard/Enterprise/Developer edition, you'd be better off using what you have.

Download SSMS 2008 Express

Extracting date from a string in Python

You could also try the dateparser module, which may be slower than datefinder on free text but which should cover more potential cases and date formats, as well as a significant number of languages.

Java, Check if integer is multiple of a number

//More Efficiently
public class Multiples {
    public static void main(String[]args) {

        int j = 5;

        System.out.println(j % 4 == 0);

    }
}

How to use wget in php?

lots of methods available in php to read a file like exec, file_get_contents, curl and fopen but it depend on your requirement and file permission

Visit this file_get_contents vs cUrl

Basically file_get_contents for for you

$data = file_get_contents($file_url);

Undefined index with $_POST

Try this:

I use this everywhere where there is a $_POST request.

$username=isset($_POST['username']) ? $_POST['username'] : "";

This is just a short hand boolean, if isset it will set it to $_POST['username'], if not then it will set it to an empty string.

Usage example:

if($username===""){ echo "Field is blank" } else { echo "Success" };

What are the differences between virtual memory and physical memory?

Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.

Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.

Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.

Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.

I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.

I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.

Why use HttpClient for Synchronous Connection

I'd re-iterate Donny V. answer and Josh's

"The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support."

(and upvote if I had the reputation.)

I can't remember the last time if ever, I was grateful of the fact HttpWebRequest threw exceptions for status codes >= 400. To get around these issues you need to catch the exceptions immediately, and map them to some non-exception response mechanisms in your code...boring, tedious and error prone in itself. Whether it be communicating with a database, or implementing a bespoke web proxy, its 'nearly' always desirable that the Http driver just tell your application code what was returned, and leave it up to you to decide how to behave.

Hence HttpClient is preferable.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

Update Fragment from ViewPager

In your PagerAdapter override getItemPosition

@Override
public int getItemPosition(Object object) {
// POSITION_NONE makes it possible to reload the PagerAdapter
return POSITION_NONE;
}

After that add viewPager.getAdapter().notifyDataSetChanged(); this code like below

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            viewPager.getAdapter().notifyDataSetChanged();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

should work.

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.

There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen variable, and thus no way of telling when user is in the minimal-ui in advance.

These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:

When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID brim-treadmill.

Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).

When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.

The end result looks like this:

Brim in iOS simulator.

For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.

Scream and orientationchangeend have been developed as part of this project.

Iterating a JavaScript object's properties using jQuery

Late, but can be done by using Object.keys like,

_x000D_
_x000D_
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
  ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
_x000D_
_x000D_

Simplest way to read json from a URL in java

I am not sure if this is efficient, but this is one of the possible ways:

Read json from url use url.openStream() and read contents into a string.

construct a JSON object with this string (more at json.org)

JSONObject(java.lang.String source)
      Construct a JSONObject from a source JSON text string.

How can I remove the top and right axis in matplotlib?

If you don't need ticks and such (e.g. for plotting qualitative illustrations) you could also use this quick workaround:

Make the axis invisible (e.g. with plt.gca().axison = False) and then draw them manually with plt.arrow.

Show percent % instead of counts in charts of categorical variables

If you want percentages on the y-axis and labeled on the bars:

library(ggplot2)
library(scales)
ggplot(mtcars, aes(x = as.factor(am))) +
  geom_bar(aes(y = (..count..)/sum(..count..))) +
  geom_text(aes(y = ((..count..)/sum(..count..)), label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
  scale_y_continuous(labels = percent) +
  labs(title = "Manual vs. Automatic Frequency", y = "Percent", x = "Automatic Transmission")

enter image description here

When adding the bar labels, you may wish to omit the y-axis for a cleaner chart, by adding to the end:

  theme(
        axis.text.y=element_blank(), axis.ticks=element_blank(),
        axis.title.y=element_blank()
  )

enter image description here

How to hide columns in HTML table?

You can also do what vs dev suggests programmatically by assigning the style with Javascript by iterating through the columns and setting the td element at a specific index to have that style.

Cannot redeclare function php

Remove the function and check the output of:

var_dump(function_exists('parseDate'));

In which case, change the name of the function.

If you get false, you're including the file with that function twice, replace :

include

by

include_once

And replace :

require

by

require_once

EDIT : I'm just a little too late, post before beat me to it !

Is it possible to start activity through adb shell?

adb shell am broadcast -a android.intent.action.xxx

Mention xxx as the action that you mentioned in the manifest file.

What are the differences between WCF and ASMX web services?

WCF completely replaces ASMX web services. ASMX is the old way to do web services and WCF is the current way to do web services. All new SOAP web service development, on the client or the server, should be done using WCF.

What exactly do "u" and "r" string flags do, and what are raw string literals?

Unicode string literals

Unicode string literals (string literals prefixed by u) are no longer used in Python 3. They are still valid but just for compatibility purposes with Python 2.

Raw string literals

If you want to create a string literal consisting of only easily typable characters like english letters or numbers, you can simply type them: 'hello world'. But if you want to include also some more exotic characters, you'll have to use some workaround. One of the workarounds are Escape sequences. This way you can for example represent a new line in your string simply by adding two easily typable characters \n to your string literal. So when you print the 'hello\nworld' string, the words will be printed on separate lines. That's very handy!

On the other hand, there are some situations when you want to create a string literal that contains escape sequences but you don't want them to be interpreted by Python. You want them to be raw. Look at these examples:

'New updates are ready in c:\windows\updates\new'
'In this lesson we will learn what the \n escape sequence does.'

In such situations you can just prefix the string literal with the r character like this: r'hello\nworld' and no escape sequences will be interpreted by Python. The string will be printed exactly as you created it.

Raw string literals are not completely "raw"?

Many people expect the raw string literals to be raw in a sense that "anything placed between the quotes is ignored by Python". That is not true. Python still recognizes all the escape sequences, it just does not interpret them - it leaves them unchanged instead. It means that raw string literals still have to be valid string literals.

From the lexical definition of a string literal:

string     ::=  "'" stringitem* "'"
stringitem ::=  stringchar | escapeseq
stringchar ::=  <any source character except "\" or newline or the quote>
escapeseq  ::=  "\" <any source character>

It is clear that string literals (raw or not) containing a bare quote character: 'hello'world' or ending with a backslash: 'hello world\' are not valid.

Removing padding gutter from grid columns in Bootstrap 4

You should use built-in bootstrap4 spacing classes for customizing the spacing of elements, that's more convenient method .

Bootstrap 3 select input form inline

I think I've accidentally found a solution. The only thing to do is inserting an empty <span class="input-group-addon"></span> between the <input> and the <select>.

Additionally you can make it "invisible" by reducing its width, horizontal padding and borders:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <span class="input-group-addon" title="* Price" id="priceLabel">Price</span>_x000D_
    <input type="number" id="searchbygenerals_priceFrom" name="searchbygenerals[priceFrom]" required="required" class="form-control" value="0">_x000D_
    <span class="input-group-addon">-</span>_x000D_
    <input type="number" id="searchbygenerals_priceTo" name="searchbygenerals[priceTo]" required="required" class="form-control" value="0">_x000D_
  _x000D_
    <!-- insert this line -->_x000D_
    <span class="input-group-addon" style="width:0px; padding-left:0px; padding-right:0px; border:none;"></span>_x000D_
  _x000D_
    <select id="searchbygenerals_currency" name="searchbygenerals[currency]" class="form-control">_x000D_
        <option value="1">HUF</option>_x000D_
        <option value="2">EUR</option>_x000D_
    </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tested on Chrome and FireFox.

Get characters after last / in url

You can use substr and strrchr:

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567

How do I revert all local changes in Git managed project to previous state?

Note: You may also want to run

git clean -fd

as

git reset --hard

will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under git tracking. WARNING - BE CAREFUL WITH THIS! It is helpful to run a dry-run with git-clean first, to see what it will delete.

This is also especially useful when you get the error message

~"performing this command will cause an un-tracked file to be overwritten"

Which can occur when doing several things, one being updating a working copy when you and your friend have both added a new file of the same name, but he's committed it into source control first, and you don't care about deleting your untracked copy.

In this situation, doing a dry run will also help show you a list of files that would be overwritten.

How to convert DateTime to VarChar

You did not say which database, but with mysql here is an easy way to get a date from a timestamp (and the varchar type conversion should happen automatically):

mysql> select date(now());
+-------------+
| date(now()) |
+-------------+
| 2008-09-16  | 
+-------------+
1 row in set (0.00 sec)

Rails 3 execute custom sql query without a model

You could also use find_by_sql

# A simple SQL query spanning multiple tables
Post.find_by_sql "SELECT p.title, c.author FROM posts p, comments c WHERE p.id = c.post_id"
> [#<Post:0x36bff9c @attributes={"title"=>"Ruby Meetup", "first_name"=>"Quentin"}>, ...]

SQL Server: Invalid Column Name

Could also happen if putting string in double quotes instead of single.

Mutex example / tutorial?

You are supposed to check the mutex variable before using the area protected by the mutex. So your pthread_mutex_lock() could (depending on implementation) wait until mutex1 is released or return a value indicating that the lock could not be obtained if someone else has already locked it.

Mutex is really just a simplified semaphore. If you read about them and understand them, you understand mutexes. There are several questions regarding mutexes and semaphores in SO. Difference between binary semaphore and mutex, When should we use mutex and when should we use semaphore and so on. The toilet example in the first link is about as good an example as one can think of. All code does is to check if the key is available and if it is, reserves it. Notice that you don't really reserve the toilet itself, but the key.

How to get a list of sub-folders and their files, ordered by folder-names

How about using sort?

dir /b /s | sort

Here's an example I tested with:


dir /s /b /o:gn

d:\root0
d:\root0\root1
d:\root0\root1\folderA
d:\root0\root1\folderB
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt

dir /s /b | sort

d:\root0
d:\root0\root1
d:\root0\root1\file00.txt
d:\root0\root1\file01.txt
d:\root0\root1\folderA
d:\root0\root1\folderA\fileA00.txt
d:\root0\root1\folderA\fileA01.txt
d:\root0\root1\folderB
d:\root0\root1\folderB\fileB00.txt
d:\root0\root1\folderB\fileB01.txt

To just get directories, use the /A:D parameter:

dir /a:d /s /b | sort

Python math module

You can also import as

from math import *

Then you can use any mathematical function without prefixing math. e.g.

sqrt(4)

Redirect stdout to a file in Python?

import sys
sys.stdout = open('stdout.txt', 'w')

How to declare a variable in SQL Server and use it in the same Stored Procedure

What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?

I can see the following issues with that SP, which may or may not relate to your problem:

  • You have an extraneous ) after @BrandName in your SELECT (at the end)
  • You're not setting @CategoryID or @BrandName to anything anywhere (they're local variables, but you don't assign values to them)

Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:

CREATE PROCEDURE AddBrand
   @BrandName nvarchar(50),
   @CategoryID int
AS
BEGIN
   DECLARE @BrandID int

   SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName

   INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END

You would then call this like this:

EXEC AddBrand 'Gucci', 23

...assuming the brand name was 'Gucci' and category ID was 23.

iOS Swift - Get the Current Local Time and Date Timestamp

If you just want the unix timestamp, create an extension:

extension Date {
    func currentTimeMillis() -> Int64 {
        return Int64(self.timeIntervalSince1970 * 1000)
    }
}

Then you can use it just like in other programming languages:

let timestamp = Date().currentTimeMillis()

How can I rename a project folder from within Visual Studio?

For those using Visual Studio + Git and wanting to keep the file history (works renaming both projects and/or solutions):

  1. Close Visual Studio

  2. In the .gitignore file, duplicate all ignore paths of the project you want to rename with renamed versions of those paths.

  3. Use the Git move command like this:

    git mv <old_folder_name> <new_folder_name>
    

    See documentation for additional options: https://git-scm.com/docs/git-mv

  4. In your .sln file: Find the line defining your project and change the folder name in path. The line should look something like:

    Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "<Project name>", "<path-to-project>\<project>.csproj"
    
  5. Open Visual Studio, and right click on project → Rename

  6. Afterwards, rename the namespaces.

    I read that ReSharper has some options for this. But simple find/replace did the job for me.

  7. Remove old .gitignore paths.

Can a unit test project load the target application's app.config file?

This is very easy.

  • Right click on your test project
  • Add-->Existing item
  • You can see a small arrow just beside the Add button
  • Select the config file click on "Add As Link"

How to get value of Radio Buttons?

I found that using the Common Event described above works well and you could have the common event set up like this:

private void checkChanged(object sender, EventArgs e)
    {
        foreach (RadioButton r in yourPanel.Controls)
        {
            if (r.Checked)
                textBox.Text = r.Text;
        }
    }

Of course, then you can't have other controls in your panel that you use, but it's useful if you just have a separate panel for all your radio buttons (such as using a sub panel inside a group box or however you prefer to organize your controls)

How can I save a base64-encoded image to disk?

I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.

var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");

require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
  console.log(err);
});

new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.

Update

As mentioned in the comments, req.rawBody is no longer a thing. If you are using express/connect then you should use the bodyParser() middleware and use req.body, and if you are doing this using standard Node then you need to aggregate the incoming data event Buffer objects and do this image data parsing in the end callback.

Check if a variable is of function type

I think you can just define a flag on the Function prototype and check if the instance you want to test inherited that

define a flag:

Function.prototype.isFunction = true; 

and then check if it exist

var foo = function(){};
foo.isFunction; // will return true

The downside is that another prototype can define the same flag and then it's worthless, but if you have full control over the included modules it is the easiest way

Creating a comma separated list from IList<string> or IEnumerable<string>

To create a comma separated list from an IList<string> or IEnumerable<string>, besides using string.Join() you can use the StringBuilder.AppendJoin method:

new StringBuilder().AppendJoin(", ", itemList).ToString();

or

$"{new StringBuilder().AppendJoin(", ", itemList)}";

Set the default value in dropdownlist using jQuery

if your wanting to use jQuery for this, try the following code.

$('select option[value="1"]').attr("selected",true);

Updated:

Following a comment from Vivek, correctly pointed out steven spielberg wanted to select the option via its Text value.

Here below is the updated code.

$('select option:contains("it\'s me")').prop('selected',true);

You need to use the :contains(text) selector to find via the containing text.

Also jQuery prop offeres better support for Internet Explorer when getting and setting attributes.

A working example on JSFiddle

Deleting rows from parent and child tables

If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.

e.g.

CREATE TABLE supplier 
( supplier_id numeric(10) not null, 
 supplier_name varchar2(50) not null, 
 contact_name varchar2(50),  
 CONSTRAINT supplier_pk PRIMARY KEY (supplier_id) 
); 



CREATE TABLE products 
( product_id numeric(10) not null, 
 supplier_id numeric(10) not null, 
 CONSTRAINT fk_supplier 
   FOREIGN KEY (supplier_id) 
  REFERENCES supplier(supplier_id) 
  ON DELETE CASCADE 
); 

Delete the supplier, and it will delate all products for that supplier

Order data frame rows according to vector with specific order

Try match:

df <- data.frame(name=letters[1:4], value=c(rep(TRUE, 2), rep(FALSE, 2)))
target <- c("b", "c", "a", "d")
df[match(target, df$name),]

  name value
2    b  TRUE
3    c FALSE
1    a  TRUE
4    d FALSE

It will work as long as your target contains exactly the same elements as df$name, and neither contain duplicate values.

From ?match:

match returns a vector of the positions of (first) matches of its first argument 
in its second.

Therefore match finds the row numbers that matches target's elements, and then we return df in that order.

How do I rename a local Git branch?

A simple way to do it:

git branch -m old_branch new_branch         # Rename branch locally
git push origin :old_branch                 # Delete the old branch
git push --set-upstream origin new_branch   # Push the new branch, set local branch to track the new remote

For more, see this.

Set adb vendor keys

If you have an AVD, this might help.

Open the AVD Manager from Android Studio. Choose the dropdown in the right most of your device row. Then do Wipe Data. Restart your virtual device, and ADB will work.

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

You can call helper class in any controller

//view 
 @Html.ActionLink("Export to Excel", "Excel")

//controller Action
public void Excel()
{
    var model = db.GetModel()

    Export export = new Export();
    export.ToExcel(Response, model);
}

//helper class
public class Export
{        public void ToExcel(HttpResponseBase Response, object clientsList)
    {
        var grid = new System.Web.UI.WebControls.GridView();
        grid.DataSource = clientsList;
        grid.DataBind();
        Response.ClearContent();
        Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
        Response.ContentType = "application/excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
}

Get cart item name, quantity all details woocommerce

Note on product price

The price of the product in the cart may be different from that of the product.

This can happen when you use some plugins that change the price of the product when it is added to the cart or if you have added a custom function in the functions.php of your active theme.

If you want to be sure you get the price of the product added to the cart you will have to get it like this:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

}

Instead of:

foreach ( WC()->cart->get_cart() as $cart_item ) {
    // gets the product object
    $product            = $cart_item['data'];
    // gets the product prices
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
}

Other data you can get:

foreach ( WC()->cart->get_cart() as $cart_item ) {

    // get the data of the cart item
    $product_id         = $cart_item['product_id'];
    $variation_id       = $cart_item['variation_id'];

    // gets the cart item quantity
    $quantity           = $cart_item['quantity'];
    // gets the cart item subtotal
    $line_subtotal      = $cart_item['line_subtotal']; 
    $line_subtotal_tax  = $cart_item['line_subtotal_tax'];
    // gets the cart item total
    $line_total         = $cart_item['line_total'];
    $line_tax           = $cart_item['line_tax'];
    // unit price of the product
    $item_price         = $line_subtotal / $quantity;
    $item_tax           = $line_subtotal_tax / $quantity;

    // gets the product object
    $product            = $cart_item['data'];
    // get the data of the product
    $sku                = $product->get_sku();
    $name               = $product->get_name();
    $regular_price      = $product->get_regular_price();
    $sale_price         = $product->get_sale_price();
    $price              = $product->get_price();
    $stock_qty          = $product->get_stock_quantity();
    // attributes
    $attributes         = $product->get_attributes();
    $attribute          = $product->get_attribute( 'pa_attribute-name' ); // // specific attribute eg. "pa_color"
    // custom meta
    $custom_meta        = $product->get_meta( '_custom_meta_key', true );
    // product categories
    $categories         = wc_get_product_category_list(  $product->get_id() ); // returns a string with all product categories separated by a comma
}

How can I put an icon inside a TextInput in React Native?

You can wrap your TextInput in View.

_x000D_
_x000D_
<View>_x000D_
  <TextInput/>_x000D_
  <Icon/>_x000D_
<View>
_x000D_
_x000D_
_x000D_

and dynamically calculate width, if you want add an icon,

iconWidth = 0.05*viewWidth 
textInputWidth = 0.95*viewWidth

otherwise textInputwWidth = viewWidth.

View and TextInput background color are both white. (Small hack)

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

How to select first parent DIV using jQuery?

two of the best options are

$(this).parent("div:first")

$(this).parent().closest('div')

and of course you can find the class attr by

$(this).parent("div:first").attr("class")

$(this).parent().closest('div').attr("class")

Can I have multiple Xcode versions installed?

Yes, you can install multiple versions of Xcode. They will install into separate directories. I've found that the best practice is to install the version that came with your Mac first and then install downloaded versions, but it probably doesn't make a big difference. See http://developer.apple.com/documentation/Xcode/Conceptual/XcodeCoexistence/Contents/Resources/en.lproj/Details/Details.html this Apple Developer Connection page for lots of details. <- Page does not exist anymore!

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

Executing Javascript code "on the spot" in Chrome?

Have you tried something like this? Put it in the head for it to work properly.

<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(){
         //using DOMContentLoaded is good as it relies on the DOM being ready for
         //manipulation, rather than the windows being fully loaded. Just like
         //how jQuery's $(document).ready() does it.

         //loop through your inputs and set their values here
    }, false);
</script>

Undo a git stash

This will also restore the staging directory:

git stash apply --index

New features in java 7

In addition to what John Skeet said, here's an overview of the Java 7 project. It includes a list and description of the features.

Note: JDK 7 was released on July 28, 2011, so you should now go to the official java SE site.

How do you upload a file to a document library in sharepoint?

As an alternative to the webservices, you can use the put document call from the FrontPage RPC API. This has the additional benefit of enabling you to provide meta-data (columns) in the same request as the file data. The obvious drawback is that the protocol is a bit more obscure (compared to the very well documented webservices).

For a reference application that explains the use of Frontpage RPC, see the SharePad project on CodePlex.

SQL Error: ORA-00913: too many values

If you are having 112 columns in one single table and you would like to insert data from source table, you could do as

create table employees as select * from source_employees where employee_id=100;

Or from sqlplus do as

copy from source_schema/password insert employees using select * from 
source_employees where employee_id=100;

How do I exit a WPF application programmatically?

Another way you can do this:

System.Diagnostics.Process.GetCurrentProcess().Kill();

This will force kill your application. It always works, even in a multi-threaded application.

Note: Just be careful not to lose unsaved data in another thread.

How do you stop MySQL on a Mac OS install?

If you installed the MySQL 5 package with MacPorts:

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql.plist 

Or

sudo launchctl  unload -w /Library/LaunchDaemons/org.macports.mysql5-devel.plist 

if you installed the mysql5-devel package.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

My problem occurs when I try to open https. I don't use SSL.

It's Tomcat bug.

Today 12/02/2017 newest official version from Debian repositories is Tomcat 8.0.14

Solution is to download from official site and install newest package of Tomcat 8, 8.5, 9 or upgrade to newest version(8.5.x) from jessie-backports

Debian 8

Add to /etc/apt/sources.list

deb http://ftp.debian.org/debian jessie-backports main

Then update and install Tomcat from jessie-backports

sudo apt-get update && sudo apt-get -t jessie-backports install tomcat8

Convert time span value to format "hh:mm Am/Pm" using C#

Parse timespan to DateTime and then use Format ("hh:mm:tt"). For example.

TimeSpan ts = new TimeSpan(16, 00, 00);
DateTime dtTemp = DateTime.ParseExact(ts.ToString(), "HH:mm:ss", CultureInfo.InvariantCulture);
string str = dtTemp.ToString("hh:mm tt");

str will be:

str = "04:00 PM"

Dump Mongo Collection into JSON format

If you want to dump all collections, run this command:

mongodump -d {DB_NAME}   -o /tmp 

It will generate all collections data in json and bson extensions into /tmp/{DB_NAME} directory

How to install JSON.NET using NuGet?

You can do this a couple of ways.

Via the "Solution Explorer"

  1. Simply right-click the "References" folder and select "Manage NuGet Packages..."
  2. Once that window comes up click on the option labeled "Online" in the left most part of the dialog.
  3. Then in the search bar in the upper right type "json.net"
  4. Click "Install" and you're done.

Via the "Package Manager Console"

  1. Open the console. "View" > "Other Windows" > "Package Manager Console"
  2. Then type the following:
    Install-Package Newtonsoft.Json

For more info on how to use the "Package Manager Console" check out the nuget docs.

How to get device make and model on iOS?

A category for going getting away from the NSString description

In general, it is desirable to avoid arbitrary string comparisons throughout your code. It is better to update the strings in one place and hide the magic string from your app. I provide a category on UIDevice for that purpose.

For my specific needs I need to know which device I am using without the need to know specifics about networking capability that can be easily retrieved in other ways. So you will find a coarser grained enum than the ever growing list of devices.

Updating is a matter of adding the device to the enum and the lookup table.

UIDevice+NTNUExtensions.h

typedef NS_ENUM(NSUInteger, NTNUDeviceType) {
    DeviceAppleUnknown,
    DeviceAppleSimulator,
    DeviceAppleiPhone,
    DeviceAppleiPhone3G,
    DeviceAppleiPhone3GS,
    DeviceAppleiPhone4,
    DeviceAppleiPhone4S,
    DeviceAppleiPhone5,
    DeviceAppleiPhone5C,
    DeviceAppleiPhone5S,
    DeviceAppleiPhone6,
    DeviceAppleiPhone6_Plus,
    DeviceAppleiPhone6S,
    DeviceAppleiPhone6S_Plus,
    DeviceAppleiPhoneSE,
    DeviceAppleiPhone7,
    DeviceAppleiPhone7_Plus,
    DeviceAppleiPodTouch,
    DeviceAppleiPodTouch2G,
    DeviceAppleiPodTouch3G,
    DeviceAppleiPodTouch4G,
    DeviceAppleiPad,
    DeviceAppleiPad2,
    DeviceAppleiPad3G,
    DeviceAppleiPad4G,
    DeviceAppleiPad5G_Air,
    DeviceAppleiPadMini,
    DeviceAppleiPadMini2G,
    DeviceAppleiPadPro12,
    DeviceAppleiPadPro9
};



@interface UIDevice (NTNUExtensions)

- (NSString *)ntnu_deviceDescription;
- (NTNUDeviceType)ntnu_deviceType;

@end

UIDevice+NTNUExtensions.m

#import <sys/utsname.h>
#import "UIDevice+NTNUExtensions.h"

@implementation UIDevice (NTNUExtensions)

- (NSString *)ntnu_deviceDescription
{
    struct utsname systemInfo;
    uname(&systemInfo);

    return [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
}

- (NTNUDeviceType)ntnu_deviceType
{
    NSNumber *deviceType = [[self ntnu_deviceTypeLookupTable] objectForKey:[self ntnu_deviceDescription]];
    return [deviceType unsignedIntegerValue];
}

- (NSDictionary *)ntnu_deviceTypeLookupTable
{
    return @{
             @"i386": @(DeviceAppleSimulator),
             @"x86_64": @(DeviceAppleSimulator),
             @"iPod1,1": @(DeviceAppleiPodTouch),
             @"iPod2,1": @(DeviceAppleiPodTouch2G),
             @"iPod3,1": @(DeviceAppleiPodTouch3G),
             @"iPod4,1": @(DeviceAppleiPodTouch4G),
             @"iPhone1,1": @(DeviceAppleiPhone),
             @"iPhone1,2": @(DeviceAppleiPhone3G),
             @"iPhone2,1": @(DeviceAppleiPhone3GS),
             @"iPhone3,1": @(DeviceAppleiPhone4),
             @"iPhone3,3": @(DeviceAppleiPhone4),
             @"iPhone4,1": @(DeviceAppleiPhone4S),
             @"iPhone5,1": @(DeviceAppleiPhone5),
             @"iPhone5,2": @(DeviceAppleiPhone5),
             @"iPhone5,3": @(DeviceAppleiPhone5C),
             @"iPhone5,4": @(DeviceAppleiPhone5C),
             @"iPhone6,1": @(DeviceAppleiPhone5S),
             @"iPhone6,2": @(DeviceAppleiPhone5S),
             @"iPhone7,1": @(DeviceAppleiPhone6_Plus),
             @"iPhone7,2": @(DeviceAppleiPhone6),
             @"iPhone8,1" :@(DeviceAppleiPhone6S),
             @"iPhone8,2" :@(DeviceAppleiPhone6S_Plus),
             @"iPhone8,4" :@(DeviceAppleiPhoneSE),
             @"iPhone9,1" :@(DeviceAppleiPhone7),
             @"iPhone9,3" :@(DeviceAppleiPhone7),
             @"iPhone9,2" :@(DeviceAppleiPhone7_Plus),
             @"iPhone9,4" :@(DeviceAppleiPhone7_Plus),
             @"iPad1,1": @(DeviceAppleiPad),
             @"iPad2,1": @(DeviceAppleiPad2),
             @"iPad3,1": @(DeviceAppleiPad3G),
             @"iPad3,4": @(DeviceAppleiPad4G),
             @"iPad2,5": @(DeviceAppleiPadMini),
             @"iPad4,1": @(DeviceAppleiPad5G_Air),
             @"iPad4,2": @(DeviceAppleiPad5G_Air),
             @"iPad4,4": @(DeviceAppleiPadMini2G),
             @"iPad4,5": @(DeviceAppleiPadMini2G),
             @"iPad4,7":@(DeviceAppleiPadMini),
             @"iPad6,7":@(DeviceAppleiPadPro12),
             @"iPad6,8":@(DeviceAppleiPadPro12),
             @"iPad6,3":@(DeviceAppleiPadPro9),
             @"iPad6,4":@(DeviceAppleiPadPro9)
             };
}

@end

How to add a search box with icon to the navbar in Bootstrap 3?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
_x000D_
    <meta charset="utf-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <meta name="description" content="">_x000D_
    <meta name="author" content="">_x000D_
_x000D_
    <title>3 Col Portfolio - Start Bootstrap Template</title>_x000D_
_x000D_
    <!-- Bootstrap Core CSS -->_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->_x000D_
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->_x000D_
    <!--[if lt IE 9]>_x000D_
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>_x000D_
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>_x000D_
    <![endif]-->_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
    <!-- Navigation -->_x000D_
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
        <div class="container">_x000D_
            <!-- Brand and toggle get grouped for better mobile display -->_x000D_
            <div class="navbar-header">_x000D_
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
                <a class="navbar-brand" href="#">Start Bootstrap</a>_x000D_
            </div>_x000D_
            <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">_x000D_
                <ul class="nav navbar-nav">_x000D_
                    <li>_x000D_
                        <a href="#">About</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Services</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">Contact</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
                <form class="navbar-form navbar-right">_x000D_
                    <div class="input-group">_x000D_
                        <input type="text" name="keyword" placeholder="search..." class="form-control">_x000D_
                        <span class="input-group-btn">_x000D_
                            <button class="btn btn-default">Go</button>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </form>_x000D_
            </div>_x000D_
            <!-- /.navbar-collapse -->_x000D_
        </div>_x000D_
        <!-- /.container -->_x000D_
    </nav>_x000D_
_x000D_
    <!-- Page Content -->_x000D_
    <div class="container">_x000D_
_x000D_
        <!-- Page Header -->_x000D_
        <div class="row">_x000D_
            <div class="col-lg-12">_x000D_
                <h1 class="page-header">Page Heading_x000D_
                    <small>Secondary Text</small>_x000D_
                </h1>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <!-- Projects Row -->_x000D_
        <div class="row">_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
            <div class="col-md-3 portfolio-item">_x000D_
                <a href="#">_x000D_
                    <img class="img-responsive" src="http://placehold.it/700x400" alt="">_x000D_
                </a>_x000D_
                <h3>_x000D_
                    <a href="#">Project Name</a>_x000D_
                </h3>_x000D_
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam viverra euismod odio, gravida pellentesque urna varius vitae.</p>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
_x000D_
        <hr>_x000D_
_x000D_
        <!-- Pagination -->_x000D_
        <div class="row text-center">_x000D_
            <div class="col-lg-12">_x000D_
                <ul class="pagination">_x000D_
                    <li>_x000D_
                        <a href="#">&laquo;</a>_x000D_
                    </li>_x000D_
                    <li class="active">_x000D_
                        <a href="#">1</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">2</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">3</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">4</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">5</a>_x000D_
                    </li>_x000D_
                    <li>_x000D_
                        <a href="#">&raquo;</a>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </div>_x000D_
    <!-- Footer -->_x000D_
    <footer>_x000D_
        <div class="container">_x000D_
            <div class="row">_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>About</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-home"></i> Your company address here_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-earphone"></i> 0982.808.065_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-envelope"></i> [email protected]_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-flag"></i> <a href="#">Fan page</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <i class="glyphicon glyphicon-time"></i> 08:00-18:00 Monday to Friday_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Support</h3>_x000D_
                    <ul>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Terms of Service</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Privacy policy</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Warranty commitment</a>_x000D_
                        </li>_x000D_
                        <li>_x000D_
                            <a href="#" class="link">Site map</a>_x000D_
                        </li>_x000D_
                    </ul>_x000D_
                </div>_x000D_
                <div class="col-lg-4 col-md-4 col-sm-4">_x000D_
                    <h3>Other</h3>_x000D_
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod_x000D_
                    tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,_x000D_
                    quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo_x000D_
                    consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse_x000D_
                    cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non_x000D_
                    proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
        <!-- /.row -->_x000D_
    </footer>_x000D_
_x000D_
    <!-- /.container -->_x000D_
_x000D_
    <!-- jQuery -->_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
    <!-- Bootstrap Core JavaScript -->_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to list only top level directories in Python?

Just to add that using os.listdir() does not "take a lot of processing vs very simple os.walk().next()[1]". This is because os.walk() uses os.listdir() internally. In fact if you test them together:

>>>> import timeit
>>>> timeit.timeit("os.walk('.').next()[1]", "import os", number=10000)
1.1215229034423828
>>>> timeit.timeit("[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]", "import os", number=10000)
1.0592019557952881

The filtering of os.listdir() is very slightly faster.

how to call a function from another function in Jquery

I think in this case you want something like this:

$(window).resize(resize=function resize(){ some code...}

Now u can call resize() within some other nested functions:

$(window).scroll(function(){ resize();}

Anaconda vs. miniconda

Both Anaconda and miniconda use the conda package manager. The chief differece between between Anaconda and miniconda,however,is that

The Anaconda distribution comes pre-loaded with all the packages while the miniconda distribution is just the management system without any pre-loaded packages. If one uses miniconda, one has to download individual packages and libraries separately.

I personally use Anaconda distribution as I dont really have to worry much about individual package installations.

A disadvantage of miniconda is that installing each individual package can take a long amount of time. Compared to that installing and using Anaconda takes a lot less time.

However, there are some packages in anaconda (QtConsole, Glueviz,Orange3) that I have never had to use. I dont even know their purpose. So a disadvantage of anaconda is that it occupies more space than needed.

How can I unstage my files again after making a local commit?

For unstaging all the files in your last commit -

git reset HEAD~

HTML/Javascript: how to access JSON data loaded in a script tag with src set

You can't load JSON like that, sorry.

I know you're thinking "why I can't I just use src here? I've seen stuff like this...":

<script id="myJson" type="application/json">
 { 
   name: 'Foo' 
 }
</script>

<script type="text/javascript">
    $(function() {
        var x = JSON.parse($('#myJson').html());
        alert(x.name); //Foo
     });
</script>

... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.

You have a short list of options to load your JSON from a remote file:

  1. Use $.get('your.json') or some other such AJAX method.
  2. Write a file that sets a global variable to your json. (seems hokey).
  3. Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
  4. Consult a voodoo priest.

Final point:

Remote JSON Request after page loads is also not an option, in case you want to suggest that.

... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.

How do I check that multiple keys are in a dict in a single pass?

Simple benchmarking rig for 3 of the alternatives.

Put in your own values for D and Q


>>> from timeit import Timer
>>> setup='''from random import randint as R;d=dict((str(R(0,1000000)),R(0,1000000)) for i in range(D));q=dict((str(R(0,1000000)),R(0,1000000)) for i in range(Q));print("looking for %s items in %s"%(len(q),len(d)))'''

>>> Timer('set(q) <= set(d)','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632499
0.28672504425048828

#This one only works for Python3
>>> Timer('set(q) <= d.keys()','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632084
2.5987625122070312e-05

>>> Timer('all(k in d for k in q)','D=1000000;Q=100;'+setup).timeit(1)
looking for 100 items in 632219
1.1920928955078125e-05

Dataframe to Excel sheet

Or you can do like this:

your_df.to_excel( r'C:\Users\full_path\excel_name.xlsx',
                  sheet_name= 'your_sheet_name'
                )