Programs & Examples On #Urlaccess

Foreach in a Foreach in MVC View

You have:

foreach (var category in Model.Categories)

and then

@foreach (var product in Model)

Based on that view and model it seems that Model is of type Product if yes then the second foreach is not valid. Actually the first one could be the one that is invalid if you return a collection of Product.


You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?

I'm surprised your code compiles when you said you are returning a model of Product type. Here's how you can do it:

@foreach (var category in Model)

            @foreach (var product in category.Products)
                    put the rest of your code

That suggest that instead of returning a Product, you return a collection of Category with Products. Something like this in EF:

// I am typing it here directly 
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.

HttpContext.Current.Session is null when routing requests

Got it. Quite stupid, actually. It worked after I removed & added the SessionStateModule like so:

      <remove name="Session" />
      <add name="Session" type="System.Web.SessionState.SessionStateModule"/>

Simply adding it won't work since "Session" should have already been defined in the machine.config.

Now, I wonder if that is the usual thing to do. It surely doesn't seem so since it seems so crude...

Focus Input Box On Load

A portable way of doing this is using a custom function (to handle browser differences) like this one.

Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:

window.onload = function() {

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

What to do on TransactionTooLargeException

I got this in my syncadapter when trying to bulkInsert a large ContentValues[]. I decided to fix it as follows:

try {
    count = provider.bulkInsert(uri, contentValueses);
} catch (TransactionTooLarge e) {
    int half = contentValueses.length/2;
    count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, 0, half));
    count += provider.bulkInsert(uri, Arrays.copyOfRange(contentValueses, half, contentValueses.length));

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

  declarations: [
  imports: [

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information:

I would also suggest replacing id="priceInput-{{}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

make an html svg object also a clickable link

Just don't use <object>. Here's a solution that worked for me with <a> and <svg> tags:

<a href="<your-link>" class="mr-5 p-1 border-2 border-transparent text-gray-400 rounded-full hover:text-white focus:outline-none focus:text-white focus:bg-red-700 transition duration-150 ease-in-out" aria-label="Notifications">
    <svg xmlns="" viewBox="0 0 24 24" width="30" 
    height="30"><path class="heroicon-ui" fill="#fff" d="M17 16a3 3 0 1 1-2.83 
    2H9.83a3 3 0 1 1-5.62-.1A3 3 0 0 1 5 12V4H3a1 1 0 1 1 0-2h3a1 1 0 0 1 1 
    1v1h14a1 1 0 0 1 .9 1.45l-4 8a1 1 0 0 1-.9.55H5a1 1 0 0 0 0 2h12zM7 12h9.38l3- 
   6H7v6zm0 8a1 1 0 1 0 0-2 1 1 0 0 0 0 2zm10 0a1 1 0 1 0 0-2 1 1 0 0 0 0 2z"/>

Example use of "continue" statement in Python?

I like to use continue in loops where there are a lot of contitions to be fulfilled before you get "down to business". So instead of code like this:

for x, y in zip(a, b):
    if x > y:
        z = calculate_z(x, y)
        if y - z < x:
            y = min(y, z)
            if x ** 2 - y ** 2 > 0:

I get code like this:

for x, y in zip(a, b):
    if x <= y:
    z = calculate_z(x, y)
    if y - z >= x:
    y = min(y, z)
    if x ** 2 - y ** 2 <= 0:

By doing it this way I avoid very deeply nested code. Also, it is easy to optimize the loop by eliminating the most frequently occurring cases first, so that I only have to deal with the infrequent but important cases (e.g. divisor is 0) when there is no other showstopper.

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

Below is the sample code to read a line in Standard input using Java Scanner class.

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(;
        String s = scan.nextLine();


Hello World


Hello World

docker entrypoint running bash script gets "permission denied"

If you still get Permission denied errors when you try to run your script in the docker's entrypoint, just try DO NOT use the shell form of the entrypoint:

Instead of: ENTRYPOINT ./bin/watcher write ENTRYPOINT ["./bin/watcher"]:

enter image description here

How to create a blank/empty column with SELECT query in oracle?

I guess you will get ORA-01741: illegal zero-length identifier if you use the following

SELECT "" AS Contact  FROM Customers;

And if you use the following 2 statements, you will be getting the same null value populated in the column.

SELECT '' AS Contact FROM Customers; OR SELECT null AS Contact FROM Customers;

How do I find which process is leaking memory?

In addition to top, you can use System Monitor (System - Administration - System Monitor, then select Processes tab). Select View - All Processes, go to Edit - Preferences and enable Virtual Memory column. Sort either by this column, or by Memory column

jQuery select2 get value of select tag?

To get Select element you can use $('#first').val();

To get the text of selected value - $('#first :selected').text();

Can you please post your select2() function code

CSS Select box arrow style

Please follow the way like below:

.selectParent {_x000D_
 overflow:hidden;   _x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
<div class="selectParent">_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_

how to include js file in php?

Its more likely that the path to file.js from the page is what is wrong. as long as when you view the page, and view-source you see the tag, its working, now its time to debug whether or not your path is too relative, maybe you need a / in front of it.

How to use JNDI DataSource provided by Tomcat in Spring?

Documentation: C.2.3.1 <jee:jndi-lookup/> (simple)


<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>

You just need to find out what JNDI name your appserver has bound the datasource to. This is entirely server-specific, consult the docs on your server to find out how.

Remember to declare the jee namespace at the top of your beans file, as described in C.2.3 The jee schema.

How to convert a date string to different format

I assume I have import datetime before running each of the lines of code below

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

prints "01/25/13".

If you can't live with the leading zero, try this:

dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month,, dt.year % 100)

This prints "1/25/13".

EDIT: This may not work on every platform:

datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

How can I get device ID for Admob

Add this class to your project

import android.content.Context;
import android.provider.Settings;
import android.text.TextUtils;


public class AdsHelper {
public static AdRequest createRequest(Context context) {
    AdRequest.Builder adRequest = new AdRequest.Builder();
    if (BuildConfig.DEBUG) {
        String deviceId = MD5(getDeviceId(context));
        if (!TextUtils.isEmpty(deviceId)) {


    private static String MD5(String md5) {
        if (TextUtils.isEmpty(md5)) return null;
        try {
   md ="MD5");
            byte[] array = md.digest(md5.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte anArray : array) {
                sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
            return sb.toString();
        } catch ( ignored) {
        } catch(UnsupportedEncodingException ignored){
        return null;

    private static String getDeviceId(Context context) {
        try {
            return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        } catch (Exception e) {
            return "";



AdRequest adRequest = AdsHelper.createRequest(this);

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

As stated,


Following the convention on the other predefined variables, make sure there is no space either side of the equals sign.

Then run

sudo service mysqld stop
sudo service mysqld start


Sometimes, e.g. on Ubuntu, the MySQL daemon is named mysql as opposed to mysqld

I find that running /etc/init.d/mysqld restart doesn't always work and you may get an error like

Stopping mysqld:                                           [FAILED]
Starting mysqld:                                           [  OK  ]

To see if the variable has been set, run show variables and see if the value has been updated.

How to stop/shut down an elasticsearch node?

Answer for Elasticsearch inside Docker:

Just stop the docker container. It seems to stop gracefully because it logs:

[INFO ][o.e.n.Node               ] [elastic] stopping ...

How to set the margin or padding as percentage of height of parent container?

Here are two options to emulate the needed behavior. Not a general solution, but may help in some cases. The vertical spacing here is calculated on the basis of the size of the outer element, not its parent, but this size itself can be relative to the parent and this way the spacing will be relative too.

<div id="outer">
    <div id="inner">

First option: use pseudo-elements, here vertical and horizontal spacing are relative to the outer. Demo

#outer::before, #outer::after {
    display: block;
    content: "";
    height: 10%;
#inner {
    height: 80%;
    margin-left: 10%;
    margin-right: 10%;

Moving the horizontal spacing to the outer element makes it relative to the parent of the outer. Demo

#outer {
    padding-left: 10%;
    padding-right: 10%;

Second option: use absolute positioning. Demo

#outer {
    position: relative;
#inner {
    position: absolute;
    left: 10%;
    right: 10%;
    top: 10%;
    bottom: 10%;

How do I find out what version of WordPress is running?

In dashboard you can see running word press version at "At a Glance"

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

How to secure phpMyAdmin

The simplest approach would be to edit the webserver, most likely an Apache2 installation, configuration and give phpmyadmin a different name.

A second approach would be to limit the IP addresses from where phpmyadmin may be accessed (e.g. only local lan or localhost).

Map over object preserving keys

I know this is old, but now Underscore has a new map for objects :

_.mapObject(object, iteratee, [context]) 

You can of course build a flexible map for both arrays and objects

_.fmap = function(arrayOrObject, fn, context){
      return, fn, context);
      return _.mapObject(arrayOrObject, fn, context);

@font-face src: local - How to use the local font if the user already has it?

I haven’t actually done anything with font-face, so take this with a pinch of salt, but I don’t think there’s any way for the browser to definitively tell if a given web font installed on a user’s machine or not.

The user could, for example, have a different font with the same name installed on their machine. The only way to definitively tell would be to compare the font files to see if they’re identical. And the browser couldn’t do that without downloading your web font first.

Does Firefox download the font when you actually use it in a font declaration? (e.g. h1 { font: 'DejaVu Serif';)?

View not attached to window manager crash

This issue is because of your activity gets finished before the dismiss function gets called. Handle the exception and check your ADB log for the exact reason.

     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
    try {
         if (pDialog!=null) {
            pDialog.dismiss();   //This is line 624!    
    } catch (Exception e) {
        // do nothing

Docker is in volume in use, but there aren't any Docker containers

A one liner to give you just the needed details:

docker inspect `docker ps -aq` | jq '.[] | {Name: .Name, Mounts: .Mounts}' | less

search for the volume of complaint, you have the container name as well.

403 Forbidden error when making an ajax Post request in Django framework

You must change your folder chmod 755 and file(.php ,.html) chmod 644.

Where is the IIS Express configuration / metabase file found?

To come full circle and include all versions of Visual Studio, @Myster originally stated that;

Pre Visual Studio 2015 the paths to applicationhost.config were:

%userprofile%\my documents\iisexpress\config\applicationhost.config

Visual Studio 2015/2017 path can be found at: (credit: @Talon)


Visual Studio 2019 path can be found at: (credit: @Talon)


But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)

So, if you make a change in the applicationhost.config you also have to make sure your changes match here:


The two important settings should look like:



VWDPort = "Port#"

What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.

Having the output of a console application in Visual Studio instead of the console

Instead, you can collect the output in a test result.

You can't supply input, but you can easily provide several tests with different command line arguments, each test collecting the output.

If your goal is debugging, this is a low effort way of offering a repeatable debugging scenario.

namespace Commandline.Test
    using Microsoft.VisualStudio.TestTools.UnitTesting;

    public class CommandlineTests
        public void RunNoArguments()
            Commandline.Program.Main(new string[0]);

How to pass a parameter to Vue @click event handler

I had the same issue and here is how I manage to pass through:

In your case you have addToCount() which is called. now to pass down a param when user clicks, you can say @click="addToCount(item.contactID)"

in your function implementation you can receive the params like:

 // the paramContactID contains the value you passed into the function when you called it
 // you can do what you want to do with the paramContactID in here!


Refresh a page using JavaScript or HTML

simply use..


If false, the page will be reloaded from cache, else from the server.

How to replace spaces in file names using a bash script

This one does a little bit more. I use it to rename my downloaded torrents (no special characters (non-ASCII), spaces, multiple dots, etc.).


&rena(`find . -type d`);
&rena(`find . -type f`);

sub rena
    @t=split /\n/,$elems;

    for $e (@t)
    # remove ./ of find
    # non ascii transliterate
    tr [\200-\377][_];
    tr [\000-\40][_];
    # special characters we do not want in paths
    s/[ \-\,\;\?\+\'\"\!\[\]\(\)\@\#]/_/g;
    # multiple dots except for extension
    while (/\..*\./)
    # only one _ consecutive
    next if ($_ eq $e ) or ("./$_" eq $e);
    print "$e -> $_\n";
    rename ($e,$_);

How to stop/terminate a python script from running?

exit() will kill the Kernel if you're in Jupyter Notebook so it's not a good idea. raise command will stop the program.

What should main() return in C and C++?

Note that the C and C++ standards define two kinds of implementations: freestanding and hosted.

  • C90 hosted environment

Allowed forms 1:

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

    main (void)
    main (int argc, char *argv[])
    /*... etc, similar forms with implicit int */


The former two are explicitly stated as the allowed forms, the others are implicitly allowed because C90 allowed "implicit int" for return type and function parameters. No other form is allowed.

  • C90 freestanding environment

Any form or name of main is allowed 2.

  • C99 hosted environment

Allowed forms 3:

    int main (void)
    int main (int argc, char *argv[])
    /* or in some other implementation-defined manner. */


C99 removed "implicit int" so main() is no longer valid.

A strange, ambiguous sentence "or in some other implementation-defined manner" has been introduced. This can either be interpreted as "the parameters to int main() may vary" or as "main can have any implementation-defined form".

Some compilers have chosen to interpret the standard in the latter way. Arguably, one cannot easily state that they are not conforming by citing the standard in itself, since it is is ambiguous.

However, to allow completely wild forms of main() was probably(?) not the intention of this new sentence. The C99 rationale (not normative) implies that the sentence refers to additional parameters to int main 4.

Yet the section for hosted environment program termination then goes on arguing about the case where main does not return int 5. Although that section is not normative for how main should be declared, it definitely implies that main might be declared in a completely implementation-defined way even on hosted systems.

  • C99 freestanding environment

Any form or name of main is allowed 6.

  • C11 hosted environment

Allowed forms 7:

    int main (void)
    int main (int argc, char *argv[])
    /* or in some other implementation-defined manner. */
  • C11 freestanding environment

Any form or name of main is allowed 8.

Note that int main() was never listed as a valid form for any hosted implementation of C in any of the above versions. In C, unlike C++, () and (void) have different meanings. The former is an obsolescent feature which may be removed from the language. See C11 future language directions:

6.11.6 Function declarators

The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.

  • C++03 hosted environment

Allowed forms 9:

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


Note the empty parenthesis in the first form. C++ and C are different in this case, because in C++ this means that the function takes no parameters. But in C it means that it may take any parameter.

  • C++03 freestanding environment

The name of the function called at startup is implementation-defined. If it is named main() it must follow the stated forms 10:

    // implementation-defined name, or 
    int main ()
    int main (int argc, char *argv[])
  • C++11 hosted environment

Allowed forms 11:

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


The text of the standard has been changed but it has the same meaning.

  • C++11 freestanding environment

The name of the function called at startup is implementation-defined. If it is named main() it must follow the stated forms 12:

    // implementation-defined name, or 
    int main ()
    int main (int argc, char *argv[])


  1. ANSI X3.159-1989 Hosted environment. "Program startup"

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

    int main(int argc, char *argv[]) { /* ... */ }
  1. ANSI X3.159-1989 Freestanding environment:

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.

  1. ISO 9899:1999 Hosted environment -> Program startup

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters:

    int main(void) { /* ... */ } 

or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared):

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

or equivalent;9) or in some other implementation-defined manner.

  1. Rationale for International Standard — Programming Languages — C, Revision 5.10. Hosted environment --> Program startup

The behavior of the arguments to main, and of the interaction of exit, main and atexit (see § has been codified to curb some unwanted variety in the representation of argv strings, and in the meaning of values returned by main.

The specification of argc and argv as arguments to main recognizes extensive prior practice. argv[argc] is required to be a null pointer to provide a redundant check for the end of the list, also on the basis of common practice.

main is the only function that may portably be declared either with zero or two arguments. (The number of other functions’ arguments must match exactly between invocation and definition.) This special case simply recognizes the widespread practice of leaving off the arguments to main when the program does not access the program argument strings. While many implementations support more than two arguments to main, such practice is neither blessed nor forbidden by the Standard; a program that defines main with three arguments is not strictly conforming (see §J.5.1.).

  1. ISO 9899:1999 Hosted environment --> Program termination

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument;11) reaching the } that terminates the main function returns a value of 0. If the return type is not compatible with int, the termination status returned to the host environment is unspecified.

  1. ISO 9899:1999 Freestanding environment

In a freestanding environment (in which C program execution may take place without any benefit of an operating system), the name and type of the function called at program startup are implementation-defined.

  1. ISO 9899:2011 Hosted environment -> Program startup

This section is identical to the C99 one cited above.

  1. ISO 9899:1999 Freestanding environment

This section is identical to the C99 one cited above.

  1. ISO 14882:2003 3.6.1 Main function

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

    int main() { /* ... */ }


    int main(int argc, char* argv[]) { /* ... */ }
  1. ISO 14882:2003 3.6.1 Main function

It is implementation-defined whether a program in a freestanding environment is required to define a main function.

  1. ISO 14882:2011 3.6.1 Main function

An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both

— a function of () returning int and

— a function of (int, pointer to pointer to char) returning int

as the type of main (8.3.5).

  1. ISO 14882:2011 3.6.1 Main function

This section is identical to the C++03 one cited above.

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

This error coud be also due to your google account already having Google Wallet/Google Checkout account linked. The existing account cannot be used for example it is a merchant account. Took me 20 minutes to figure out. Add new Google Account to your device, restart. While in Google Play switch to your new account. Buy your app/book/movie.

Insert variable into Header Location PHP

header('Location:' . $your_variable);

Checking during array iteration, if the current element is the last element

I know this is old, and using SPL iterator maybe just an overkill, but anyway, another solution here:

$ary = array(1, 2, 3, 4, 'last');
$ary = new ArrayIterator($ary);
$ary = new CachingIterator($ary);
foreach ($ary as $each) {
    if (!$ary->hasNext()) { // we chain ArrayIterator and CachingIterator
                            // just to use this `hasNext()` method to see
                            // if this is the last element
       echo $each;

Getting all types that implement an interface

Even better when choosing the Assembly location. Filter most of the assemblies if you know all your implemented interfaces are within the same Assembly.DefinedTypes.

// We get the assembly through the base class
var baseAssembly = typeof(baseClass).GetTypeInfo().Assembly;

// we filter the defined classes according to the interfaces they implement
var typeList = baseAssembly.DefinedTypes.Where(type => type.ImplementedInterfaces.Any(inter => inter == typeof(IMyInterface))).ToList();

By Can Bilgin

T-SQL: Export to new Excel file

Use PowerShell:

$Server = "TestServer"
$Database = "TestDatabase"
$Query = "select * from TestTable"
$FilePath = "C:\OutputFile.csv"

# This will overwrite the file if it already exists.
Invoke-Sqlcmd -Query $Query -Database $Database -ServerInstance $Server | Export-Csv $FilePath

In my usual cases, all I really need is a CSV file that can be read by Excel. However, if you need an actual Excel file, then tack on some code to convert the CSV file to an Excel file. This answer gives a solution for this, but I've not tested it.

Use tab to indent in textarea

Modern way that both is straight-forward and does not lose the ability to undo (Ctrl+Z) the last changes.

$('#your-textarea').keydown(function (e) {
    var keyCode = e.keyCode || e.which;

    if (keyCode === $.ui.keyCode.TAB) {

        const TAB_SIZE = 4;

        // The one-liner that does the magic
        document.execCommand('insertText', false, ' '.repeat(TAB_SIZE));

More about execCommand:


As pointed out in the comment (and while this was once a "modern" solution), the feature has gone obsolete. Quoting the docs:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

Modular multiplicative inverse function in Python

Many of the links above are broken as for 1/23/2017. I found this implementation:

How to properly create composite primary keys - MYSQL

@AlexCuse I wanted to add this as comment to your answer but gave up after making multiple failed attempt to add newlines in comments.

That said, t1ID is unique in table_1 but that doesn't makes it unique in INFO table as well.

For example:

Table_1 has:
Id Field
1 A
2 B

Table_2 has:
Id Field
1 X
2 Y

INFO then can have:
t1ID t2ID field
1 1 some
1 2 data
2 1 in-each
2 2 row

So in INFO table to uniquely identify a row you need both t1ID and t2ID

How can I reorder a list?

This is what I used when I stumbled upon this problem.

def order(list_item, i): # reorder at index i
    order_at = list_item.index(i)
    ordered_list = list_item[order_at:] + list_item[:order_at]
    return ordered_list

EX: for the the lowercase letters

order(string.ascii_lowercase, 'h'):
>>> 'hijklmnopqrstuvwxyzabcdefg'

It simply just shifts the list to a specified index

Android Studio doesn't see device

I was facing the same issue. Turned out to be a faulty data cable. The device would start charging but would not show up in connected devices in Android Studio.

Trying another cable worked fine.

Try another cable first if you have been using your current one for a while.

String length in bytes in JavaScript

There is no way to do it in JavaScript natively. (See Riccardo Galli's answer for a modern approach.)

For historical reference or where TextEncoder APIs are still unavailable.

If you know the character encoding, you can calculate it yourself though.

encodeURIComponent assumes UTF-8 as the character encoding, so if you need that encoding, you can do,

function lengthInUtf8Bytes(str) {
  // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);

This should work because of the way UTF-8 encodes multi-byte sequences. The first encoded byte always starts with either a high bit of zero for a single byte sequence, or a byte whose first hex digit is C, D, E, or F. The second and subsequent bytes are the ones whose first two bits are 10. Those are the extra bytes you want to count in UTF-8.

The table in wikipedia makes it clearer

Bits        Last code point Byte 1          Byte 2          Byte 3
  7         U+007F          0xxxxxxx
 11         U+07FF          110xxxxx        10xxxxxx
 16         U+FFFF          1110xxxx        10xxxxxx        10xxxxxx

If instead you need to understand the page encoding, you can use this trick:

function lengthInPageEncoding(s) {
  var a = document.createElement('A');
  a.href = '#' + s;
  var sEncoded = a.href;
  sEncoded = sEncoded.substring(sEncoded.indexOf('#') + 1);
  var m = sEncoded.match(/%[0-9a-f]{2}/g);
  return sEncoded.length - (m ? m.length * 2 : 0);

Python: Removing spaces from list objects

Presuming that you don't want to remove internal spaces:

def normalize_space(s):
    """Return s stripped of leading/trailing whitespace
    and with internal runs of whitespace replaced by a single SPACE"""
    # This should be a str method :-(
    return ' '.join(s.split())

replacement = [normalize_space(i) for i in hello]

Where's javax.servlet?

If you've got the Java EE JDK with Glassfish, it's in glassfish3/glassfish/modules/javax.servlet-api.jar.

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '~~> Rest of the code
    driver.findElementByName("PASSWORD").SendKeys pass
    '~~> Rest of the code
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

What's the Android ADB shell "dumpsys" tool and what are its benefits?

Looking at the source code for dumpsys and service, you can get the list of services available by executing the following:

adb shell service -l

You can then supply the service name you are interested in to dumpsys to get the specific information. For example (note that not all services provide dump info):

adb shell dumpsys activity
adb shell dumpsys cpuinfo
adb shell dumpsys battery

As you can see in the code (and in K_Anas's answer), if you call dumpsys without any service name, it will dump the info on all services in one big dump:

adb shell dumpsys

Some services can receive additional arguments on what to show which normally is explained if you supplied a -h argument, for example:

adb shell dumpsys activity -h
adb shell dumpsys window -h
adb shell dumpsys meminfo -h
adb shell dumpsys package -h
adb shell dumpsys batteryinfo -h

Pythonic way to check if a list is sorted or not

This iterator form is 10-15% faster than using integer indexing:

# python2 only
if str is bytes:
    from itertools import izip as zip

def is_sorted(l):
    return all(a <= b for a, b in zip(l, l[1:]))

find vs find_by vs where

Apart from accepted answer, following is also valid

Model.find() can accept array of ids, and will return all records which matches. Model.find_by_id(123) also accept array but will only process first id value present in array


How do I check for vowels in JavaScript?

Personally, I would define it this way:

function isVowel( chr ){ return 'aeiou'.indexOf( chr[0].toLowerCase() ) !== -1 }

You could also use ['a','e','i','o','u'] and skip the length test, but then you are creating an array each time you call the function. (There are ways of mimicking this via closures, but those are a bit obscure to read)

What is context in _.each(list, iterator, [context])?

As explained in other answers, context is the this context to be used inside callback passed to each.

I'll explain this with the help of source code of relevant methods from underscore source code

The definition of _.each or _.forEach is as follows:

_.each = _.forEach = function(obj, iteratee, context) {
  iteratee = optimizeCb(iteratee, context);

  var i, length;
  if (isArrayLike(obj)) {
    for (i = 0, length = obj.length; i < length; i++) {
      iteratee(obj[i], i, obj);
  } else {
    var keys = _.keys(obj);
    for (i = 0, length = keys.length; i < length; i++) {
      iteratee(obj[keys[i]], keys[i], obj);
  return obj;

Second statement is important to note here

iteratee = optimizeCb(iteratee, context);

Here, context is passed to another method optimizeCb and the returned function from it is then assigned to iteratee which is called later.

var optimizeCb = function(func, context, argCount) {
  if (context === void 0) return func;
  switch (argCount == null ? 3 : argCount) {
    case 1:
      return function(value) {
        return, value);
    case 2:
      return function(value, other) {
        return, value, other);
    case 3:
      return function(value, index, collection) {
        return, value, index, collection);
    case 4:
      return function(accumulator, value, index, collection) {
        return, accumulator, value, index, collection);
  return function() {
    return func.apply(context, arguments);

As can be seen from the above method definition of optimizeCb, if context is not passed then func is returned as it is. If context is passed, callback function is called as, other_parameters);

func is called with call() which is used to invoke a method by setting this context of it. So, when this is used inside func, it'll refer to context.

// Without `context`_x000D_
_.each([1], function() {_x000D_
  console.log(this instanceof Window);_x000D_
// With `context` as `arr`_x000D_
var arr = [1, 2, 3];_x000D_
_.each([1], function() {_x000D_
}, arr);
<script src=""></script>

You can consider context as the last optional parameter to forEach in JavaScript.

setting JAVA_HOME & CLASSPATH in CentOS 6

It seems that you dont have any problem with the environmental variables.

Compile your file from src with

javac a/

Then, run your program as

java a.A

Plotting 4 curves in a single plot, with 3 y-axes

I know of plotyy that allows you to have two y-axes, but no "plotyyy"!

Perhaps you can normalize the y values to have the same scale (min/max normalization, zscore standardization, etc..), then you can just easily plot them using normal plot, hold sequence.

Here's an example:

%# random data
y = [randn(20,1)*1 + 0 , randn(20,1)*5 + 10 , randn(20,1)*0.3 + 50];

%# plotyy
plotyy(x,y(:,1), x,y(:,3))

%# orginial
subplot(221), plot(x,y(:,1), x,y(:,2), x,y(:,3))
title('original'), legend({'y1' 'y2' 'y3'})

%# normalize: (y-min)/(max-min) ==> [0,1]
yy = bsxfun(@times, bsxfun(@minus,y,min(y)), 1./range(y));
subplot(222), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))

%# standarize: (y - mean) / std ==> N(0,1)
yy = zscore(y);
subplot(223), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))

%# softmax normalization with logistic sigmoid ==> [0,1]
yy = 1 ./ ( 1 + exp( -zscore(y) ) );
subplot(224), plot(x,yy(:,1), x,yy(:,2), x,yy(:,3))

plotyy normalization

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

Clear listview content?

Remove your items from your custom adapter and call notifyDataSetChanged().

How to automatically add user account AND password with a Bash script?

You could also use chpasswd:

echo username:new_password | chpasswd

so, you change password for user username to new_password.

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
            <!-- The 2nd column -->
            <!-- The 3rd column -->

php resize image on upload

Building onto answer from @zeusstl, for multiple images uploaded:

function img_resize()

  $input = 'input-upload-img1'; // Name of input

  $maxDim = 400;
  foreach ($_FILES[$input]['tmp_name'] as $file_name){
    list($width, $height, $type, $attr) = getimagesize( $file_name );
    if ( $width > $maxDim || $height > $maxDim ) {
        $target_filename = $file_name;
        $ratio = $width/$height;
        if( $ratio > 1) {
            $new_width = $maxDim;
            $new_height = $maxDim/$ratio;
        } else {
            $new_width = $maxDim*$ratio;
            $new_height = $maxDim;
        $src = imagecreatefromstring( file_get_contents( $file_name ) );
        $dst = imagecreatetruecolor( $new_width, $new_height );
        imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
        imagedestroy( $src );
        imagepng( $dst, $target_filename ); // adjust format as needed
        imagedestroy( $dst );

Rewrite all requests to index.php with nginx

Flat and simple config without rewrite, can work in some cases:

location / {
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /home/webuser/site/index.php;

Android: How do I prevent the soft keyboard from pushing my view up?

For Scroll View:

if after adding android:windowSoftInputMode="stateHidden|adjustPan" in your Android Manifest and still does not work.

It may be affected because when the keyboard appears, it will be into a scroll view and if your button/any objects is not in your scroll view then the objects will follow the keyboard and move its position.

Check out your xml where your button is and make sure it is under your scroll View bracket and not out of it.

Hope this helps out. :D

How to make node.js require absolute? (instead of relative)

I have tried many of these solutions. I ended up adding this to the top of my main file (e.g. index.js):

process.env.NODE_PATH = __dirname;

This adds the project root to the NODE_PATH when the script is loaded. The allows me to require any file in my project by referencing its relative path from the project root such as var User = require('models/user'). This solution should work as long as you are running a main script in the project root before running anything else in your project.

ConcurrentHashMap vs Synchronized HashMap

The short answer:

Both maps are thread-safe implementations of the Map interface. ConcurrentHashMap is implemented for higher throughput in cases where high concurrency is expected.

Brian Goetz's article on the idea behind ConcurrentHashMap is a very good read. Highly recommended.

Create a menu Bar in WPF?

<StackPanel VerticalAlignment="Top">
    <Menu Width="Auto" Height="20">
        <MenuItem Header="_File">
            <MenuItem x:Name="AppExit" Header="E_xit" HorizontalAlignment="Left" Width="140" Click="AppExit_Click"/>
        <MenuItem Header="_Tools">
            <MenuItem x:Name="Options" Header="_Options" HorizontalAlignment="Left" Width="140"/>
        <MenuItem Header="_Help">
            <MenuItem x:Name="About" Header="&amp;About" HorizontalAlignment="Left" Width="140"/>
    <Label Content="Label"/>

How does Content Security Policy (CSP) work?

Apache 2 mod_headers

You could also enable Apache 2 mod_headers. On Fedora it's already enabled by default. If you use Ubuntu/Debian, enable it like this:

# First enable headers module for Apache 2,
# and then restart the Apache2 service
a2enmod headers
apache2 -k graceful

On Ubuntu/Debian you can configure headers in the file /etc/apache2/conf-enabled/security.conf

# Setting this header will prevent MSIE from interpreting files as something
# else than declared by the content type in the HTTP headers.
# Requires mod_headers to be enabled.
#Header set X-Content-Type-Options: "nosniff"

# Setting this header will prevent other sites from embedding pages from this
# site as frames. This defends against clickjacking attacks.
# Requires mod_headers to be enabled.
Header always set X-Frame-Options: "sameorigin"
Header always set X-Content-Type-Options nosniff
Header always set X-XSS-Protection "1; mode=block"
Header always set X-Permitted-Cross-Domain-Policies "master-only"
Header always set Cache-Control "no-cache, no-store, must-revalidate"
Header always set Pragma "no-cache"
Header always set Expires "-1"
Header always set Content-Security-Policy: "default-src 'none';"
Header always set Content-Security-Policy: "script-src 'self';"
Header always set Content-Security-Policy: "style-src 'self';"

Note: This is the bottom part of the file. Only the last three entries are CSP settings.

The first parameter is the directive, the second is the sources to be white-listed. I've added Google analytics and an adserver, which you might have. Furthermore, I found that if you have aliases, e.g, and configured in Apache 2 you should add them to the white-list as well.

Inline code is considered harmful, and you should avoid it. Copy all the JavaScript code and CSS to separate files and add them to the white-list.

While you're at it you could take a look at the other header settings and install mod_security

Further reading:

Getting vertical gridlines to appear in line plot in matplotlib

According to matplotlib documentation, The signature of the Axes class grid() method is as follows:

Axes.grid(b=None, which='major', axis='both', **kwargs)
Turn the axes grids on or off.

which can be ‘major’ (default), ‘minor’, or ‘both’ to control whether major tick grids, minor tick grids, or both are affected.

axis can be ‘both’ (default), ‘x’, or ‘y’ to control which set of gridlines are drawn.

So in order to show grid lines for both the x axis and y axis, we can use the the following code:

ax = plt.gca()
ax.grid(which='major', axis='both', linestyle='--')

This method gives us finer control over what to show for grid lines.

Changing CSS Values with Javascript

Ok, it sounds like you want to change the global CSS so which will effictively change all elements of a peticular style at once. I've recently learned how to do this myself from a Shawn Olson tutorial. You can directly reference his code here.

Here is the summary:

You can retrieve the stylesheets via document.styleSheets. This will actually return an array of all the stylesheets in your page, but you can tell which one you are on via the document.styleSheets[styleIndex].href property. Once you have found the stylesheet you want to edit, you need to get the array of rules. This is called "rules" in IE and "cssRules" in most other browsers. The way to tell what CSSRule you are on is by the selectorText property. The working code looks something like this:

var cssRuleCode = document.all ? 'rules' : 'cssRules'; //account for IE and FF
var rule = document.styleSheets[styleIndex][cssRuleCode][ruleIndex];
var selector = rule.selectorText;  //maybe '#tId'
var value = rule.value;            //both selectorText and value are settable.

Let me know how this works for ya, and please comment if you see any errors.

The order of keys in dictionaries


"The keys() method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply the sorted() function to it)."

Check if a specific value exists at a specific key in any subarray of a multidimensional array

Nothing will be faster than a simple loop. You can mix-and-match some array functions to do it, but they'll just be implemented as a loop too.

function whatever($array, $key, $val) {
    foreach ($array as $item)
        if (isset($item[$key]) && $item[$key] == $val)
            return true;
    return false;

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

It seems that when this error appears it is an indication that the selenium-java plugin for maven is out-of-date.

Changing the version in the pom.xml should fix the problem

"static const" vs "#define" vs "enum"

It depends on what you need the value for. You (and everyone else so far) omitted the third alternative:

  1. static const int var = 5;
  2. #define var 5
  3. enum { var = 5 };

Ignoring issues about the choice of name, then:

  • If you need to pass a pointer around, you must use (1).
  • Since (2) is apparently an option, you don't need to pass pointers around.
  • Both (1) and (3) have a symbol in the debugger's symbol table - that makes debugging easier. It is more likely that (2) will not have a symbol, leaving you wondering what it is.
  • (1) cannot be used as a dimension for arrays at global scope; both (2) and (3) can.
  • (1) cannot be used as a dimension for static arrays at function scope; both (2) and (3) can.
  • Under C99, all of these can be used for local arrays. Technically, using (1) would imply the use of a VLA (variable-length array), though the dimension referenced by 'var' would of course be fixed at size 5.
  • (1) cannot be used in places like switch statements; both (2) and (3) can.
  • (1) cannot be used to initialize static variables; both (2) and (3) can.
  • (2) can change code that you didn't want changed because it is used by the preprocessor; both (1) and (3) will not have unexpected side-effects like that.
  • You can detect whether (2) has been set in the preprocessor; neither (1) nor (3) allows that.

So, in most contexts, prefer the 'enum' over the alternatives. Otherwise, the first and last bullet points are likely to be the controlling factors — and you have to think harder if you need to satisfy both at once.

If you were asking about C++, then you'd use option (1) — the static const — every time.

How to specify HTTP error code?

From what I saw in Express 4.0 this works for me. This is example of authentication required middleware.

function apiDemandLoggedIn(req, res, next) {

    // if user is authenticated in the session, carry on
    console.log('isAuth', req.isAuthenticated(), req.user);
    if (req.isAuthenticated())
        return next();

    // If not return 401 response which means unauthroized.
    var err = new Error();
    err.status = 401;

Python integer incrementing with ++

Take a look at Behaviour of increment and decrement operators in Python for an explanation of why this doesn't work.

Python doesn't really have ++ and --, and I personally never felt it was such a loss.

I prefer functions with clear names to operators with non-always clear semantics (hence the classic interview question about ++x vs. x++ and the difficulties of overloading it). I've also never been a huge fan of what post-incrementation does for readability.

You could always define some wrapper class (like accumulator) with clear increment semantics, and then do something like x.increment() or x.incrementAndReturnPrev()

UTF-8: General? Bin? Unicode?

  • utf8_bin compares the bits blindly. No case folding, no accent stripping.
  • utf8_general_ci compares one byte with one byte. It does case folding and accent stripping, but no 2-character comparisions: ij is not equal ? in this collation.
  • utf8_*_ci is a set of language-specific rules, but otherwise like unicode_ci. Some special cases: Ç, C, ch, ll
  • utf8_unicode_ci follows an old Unicode standard for comparisons. ij=?, but ae != æ
  • utf8_unicode_520_ci follows an newer Unicode standard. ae = æ

See collation chart for details on what is equal to what in various utf8 collations.

utf8, as defined by MySQL is limited to the 1- to 3-byte utf8 codes. This leaves out Emoji and some of Chinese. So you should really switch to utf8mb4 if you want to go much beyond Europe.

The above points apply to utf8mb4, after suitable spelling change. Going forward, utf8mb4 and utf8mb4_unicode_520_ci are preferred.

  • utf16 and utf32 are variants on utf8; there is virtually no use for them.
  • ucs2 is closer to "Unicode" than "utf8"; there is virtually no use for it.

URL to compose a message in Gmail (with full Gmail interface and specified to, bcc, subject, etc.)

It's worth pointing out that if you have multiple Gmail accounts, you may want to use the URL approach because you can customize which account to compose from.


Or if you know the email address you are sending from, replace the numeric index with the email address:[email protected]/#inbox?compose=new

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"

Allow only numeric value in textbox using Javascript

Javascript For only numeric value in textbox ::

<input type="text" id="textBox" runat="server" class="form-control" onkeydown="return onlyNos(event)" tabindex="0" /> 

    <!--Only Numeric value in Textbox Script -->
        <script type="text/javascript">
            function onlyNos(e, t) {
                try {
                    if (window.event) {
                        var charCode = window.event.keyCode;
                    else if (e) {
                        var charCode = e.which;
                    else { return true; }
                    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
                        return false;
                    return true;
                catch (err) {
        <!--Only Numeric value in Textbox Script -->

jQuery get values of checked checkboxes into array

You need to add .toArray() to the end of your .map() function

    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();


Show loading gif after clicking form submit using jQuery

What about an onclick function:

    <form id="form">
    <input type="text" name="firstInput">
    <button type="button" name="namebutton" 
           onClick="$('#gif').css('visibility', 'visible');

Of course you can put this in a function and then trigger it with an onClick

Best practices for Storyboard login screen, handling clearing of data upon logout

I didn't like bhavya's answer because of using AppDelegate inside View Controllers and setting rootViewController has no animation. And Trevor's answer has issue with flashing view controller on iOS8.

UPD 07/18/2015

AppDelegate inside View Controllers:

Changing AppDelegate state (properties) inside view controller breaks encapsulation.

Very simple hierarchy of objects in every iOS project:

AppDelegate (owns window and rootViewController)

ViewController (owns view)

It's ok that objects from the top change objects at the bottom, because they are creating them. But it's not ok if objects on the bottom change objects on top of them (I described some basic programming/OOP principle : DIP (Dependency Inversion Principle : high level module must not depend on the low level module, but they should depend on abstractions)).

If any object will change any object in this hierarchy, sooner or later there will be a mess in the code. It might be ok on the small projects but it's no fun to dig through this mess on the bit projects =]

UPD 07/18/2015

I replicate modal controller animations using UINavigationController (tl;dr: check the project).

I'm using UINavigationController to present all controllers in my app. Initially I displayed login view controller in navigation stack with plain push/pop animation. Than I decided to change it to modal with minimal changes.

How it works:

  1. Initial view controller (or self.window.rootViewController) is UINavigationController with ProgressViewController as a rootViewController. I'm showing ProgressViewController because DataModel can take some time to initialize because it inits core data stack like in this article (I really like this approach).

  2. AppDelegate is responsible for getting login status updates.

  3. DataModel handles user login/logout and AppDelegate is observing it's userLoggedIn property via KVO. Arguably not the best method to do this but it works for me. (Why KVO is bad, you can check in this or this article (Why Not Use Notifications? part).

  4. ModalDismissAnimator and ModalPresentAnimator are used to customize default push animation.

How animators logic works:

  1. AppDelegate sets itself as a delegate of self.window.rootViewController (which is UINavigationController).

  2. AppDelegate returns one of animators in -[AppDelegate navigationController:animationControllerForOperation:fromViewController:toViewController:] if necessary.

  3. Animators implement -transitionDuration: and -animateTransition: methods. -[ModalPresentAnimator animateTransition:]:

    - (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
        UIViewController *toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
        [[transitionContext containerView] addSubview:toViewController.view];
        CGRect frame = toViewController.view.frame;
        CGRect toFrame = frame;
        frame.origin.y = CGRectGetHeight(frame);
        toViewController.view.frame = frame;
        [UIView animateWithDuration:[self transitionDuration:transitionContext]
             toViewController.view.frame = toFrame;
         } completion:^(BOOL finished)
             [transitionContext completeTransition:![transitionContext transitionWasCancelled]];

Test project is here.

Best practices when running Node.js with port 80 (Ubuntu / Linode)

Give Safe User Permission To Use Port 80

Remember, we do NOT want to run your applications as the root user, but there is a hitch: your safe user does not have permission to use the default HTTP port (80). You goal is to be able to publish a website that visitors can use by navigating to an easy to use URL like http://ip:port/

Unfortunately, unless you sign on as root, you’ll normally have to use a URL like http://ip:port - where port number > 1024.

A lot of people get stuck here, but the solution is easy. There a few options but this is the one I like. Type the following commands:

sudo apt-get install libcap2-bin
sudo setcap cap_net_bind_service=+ep `readlink -f \`which node\``

Now, when you tell a Node application that you want it to run on port 80, it will not complain.

Check this reference link

What is a raw type and why shouldn't we use it?

The compiler wants you to write this:

private static List<String> list = new ArrayList<String>();

because otherwise, you could add any type you like into list, making the instantiation as new ArrayList<String>() pointless. Java generics are a compile-time feature only, so an object created with new ArrayList<String>() will happily accept Integer or JFrame elements if assigned to a reference of the "raw type" List - the object itself knows nothing about what types it's supposed to contain, only the compiler does.

How do I make WRAP_CONTENT work on a RecyclerView

Instead of using any library, easiest solution till the new version comes out is to just open You'll easily find the best solution known to date there.

PS: worked for me

How to test if a file is a directory in a batch script?

A variation of @batchman61's approach (checking the Directory attribute).

This time I use an external 'find' command.

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

SETLOCAL EnableExtensions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
    ECHO %1 is a directory

Outputs yes on:

  • Directories.
  • Directory symbolic links or junctions.
  • Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
  • Directories which you have no read permission on (e.g. "C:\System Volume Information")

Android: I am unable to have ViewPager WRAP_CONTENT

Improved Daniel López Lacalle answer, rewritten in Kotlin:

class MyViewPager(context: Context, attrs: AttributeSet): ViewPager(context, attrs) {
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        val zeroHeight = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)

        val maxHeight = children
            .map { it.measure(widthMeasureSpec, zeroHeight); it.measuredHeight }
            .max() ?: 0

        if (maxHeight > 0) {
            val maxHeightSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.EXACTLY)
            super.onMeasure(widthMeasureSpec, maxHeightSpec)

        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

DIV height set as percentage of screen?

By using absolute positioning, you can make <body> or <form> or <div>, fit to your browser page. For example:

<body style="position: absolute; bottom: 0px; top: 0px; left: 0px; right: 0px;">

and then simply put a <div> inside it and use whatever percentage of either height or width you wish

<div id="divContainer" style="height: 100%;">

How does Google calculate my location on a desktop?

  • So Google keep records of Wifi router location by using any cellphone GPS that connected to that router when you use Google maps or location on cellphone. then google knows every device that connected to that Wifi router uses the same location.
  • when GPS off or no cellphone connected to router Google uses IP geolocation

Converting video to HTML5 ogg / ogv and mpg4

MS Expression Encoder can do mp4/h.264. not sure about ogg though.

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

Try using cURL.


curl_setopt($curl_handle, CURLOPT_URL,'http://###.##.##.##/mp/get?mpsrc= format=flv');
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Your application name');
$query = curl_exec($curl_handle);


Deleting Elements in an Array if Element is a Certain value VBA

Deleting Elements in an Array if Element is a Certain value VBA

to delete elements in an Array wih certain condition, you can code like this

For i = LBound(ArrValue, 2) To UBound(ArrValue, 2)
    If [Certain condition] Then
        ArrValue(1, i) = "-----------------------"
    End If
Next i

StrTransfer = Replace(Replace(Replace(join(Application.Index(ArrValue(), 1, 0), ","), ",-----------------------,", ",", , , vbBinaryCompare), "-----------------------,", "", , , vbBinaryCompare), ",-----------------------", "", , , vbBinaryCompare)
ResultArray = join( Strtransfer, ",")

I often manipulate 1D-Array with Join/Split but if you have to delete certain value in Multi Dimension I suggest you to change those Array into 1D-Array like this

strTransfer = Replace(Replace(Replace(Replace(Names.Add("A", MultiDimensionArray), Chr(34), ""), "={", ""), "}", ""), ";", ",")
'somecode to edit Array like 1st code on top of this comment
'then loop through this strTransfer to get right value in right dimension
'with split function.

How to parse float with two decimal places in javascript?

@sd Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.

Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options

  1. Either use data as a string or
  2. Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal

alert a variable value

If you're using greasemonkey, it's possible the page isn't ready for the javascript yet. You may need to use window.onReady.

var inputs;

function doThisWhenReady() {
    inputs = document.getElementsByTagName('input');

    //Other code here...

window.onReady = doThisWhenReady;

Unique Key constraints for multiple columns in Entity Framework

I assume you always want EntityId to be the primary key, so replacing it by a composite key is not an option (if only because composite keys are far more complicated to work with and because it is not very sensible to have primary keys that also have meaning in the business logic).

The least you should do is create a unique key on both fields in the database and specifically check for unique key violation exceptions when saving changes.

Additionally you could (should) check for unique values before saving changes. The best way to do that is by an Any() query, because it minimizes the amount of transferred data:

if (context.Entities.Any(e => e.FirstColumn == value1 
                           && e.SecondColumn == value2))
    // deal with duplicate values here.

Beware that this check alone is never enough. There is always some latency between the check and the actual commit, so you'll always need the unique constraint + exception handling.

HTML code for INR

SPAN class code. Stylesheet:

<link rel="stylesheet" type="text/css" href="">

Now use the below mentioned code to type Indian Rupee symbol,

<span class="WebRupee">Rs.</span>

Once the popular font families will be updated to Unicode 6.0.0, then you will be able to type Indian Rupee Symbol by typing ₹ in HTML editor.

Select element based on multiple classes

You can use these solutions :

CSS rules applies to all tags that have following two classes :

.left.ui-class-selector {
    /*style here*/

CSS rules applies to all tags that have <li> with following two classes :

li.left.ui-class-selector {
   /*style here*/

jQuery solution :

$("li.left.ui-class-selector").css("color", "red");

Javascript solution :

document.querySelector("li.left.ui-class-selector").style.color = "red";

Refresh Part of Page (div)

Use Ajax for this.

Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.

Relevant function:


$('#thisdiv').load(document.URL +  ' #thisdiv');

Note, load automatically replaces content. Be sure to include a space before the id selector.

Running a Python script from PHP

I recommend using passthru and handling the output buffer directly:

passthru('/usr/bin/python2.7 /srv/http/assets/py/ arg1 arg2');
$output = ob_get_clean(); 

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

I think that the usage of @Html.LabelForModel() should be explained in more detail.

The LabelForModel Method returns an HTML label element and the property name of the property that is represented by the model.

You could refer to the following code:

Code in model:

using System.ComponentModel;

public class MyModel
    [DisplayName("A property")]
    public string Test { get; set; }

Code in view:

<div class="form-group">

    @Html.LabelFor(model => model.Test, new { @class = "control-label col-md-2" })

    <div class="col-md-10">
        @Html.EditorFor(model => model.Test)
        @Html.ValidationMessageFor(model => model.Test)

The output screenshot:

enter image description here

Reference to answer on the forum

iPhone get SSID without private library

This works for me on the device (not simulator). Make sure you add the systemconfiguration framework.

#import <SystemConfiguration/CaptiveNetwork.h>

+ (NSString *)currentWifiSSID {
    // Does not work on the simulator.
    NSString *ssid = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
            ssid = info[@"SSID"];
    return ssid;

What is the inclusive range of float and double in Java?

Java's Double class has members containing the Min and Max value for the type.

2^-1074 <= x <= (2-2^-52)·2^1023 // where x is the double.

Check out the Min_VALUE and MAX_VALUE static final members of Double.

(some)People will suggest against using floating point types for things where accuracy and precision are critical because rounding errors can throw off calculations by measurable (small) amounts.

How to write a stored procedure using phpmyadmin and how to use it through php?

All the answers above are making certain assumptions. There are basic problems in 1and1 and certain other hosting providers are using phpMyAdmin versions which are very old and have an issue that defined delimiter is ; and there is no way to change it from phpMyAdmin. Following are the ways

  1. Create a new PHPMyAdmin on the hosting provider. Attached link gives you idea
  2. Go thru the complicated route of be able to access the your hosting providers mySQL from your dekstop. It is complicated but the best if you are a serious developer. here is a link to do it

Hope this helps

How to install wkhtmltopdf on a linux based (shared hosting) web server

I've managed to successfully install wkhtmltopdf-amd64 on my shared hosting account without root access.

Here's what i did:

Downloaded the relevant static binary v0.10.0 from here:

EDIT: The above has moved to here

via ssh on my shared host typed the following:

$ wget {relavant url to binary from link above}
$ tar -xvf {filename of above wget'd file}

you'll then have the binary on your host and will be able to run it regardless of if its in the /usr/bin/ folder or not. (or at least i was able to)

To test:

$ ./wkhtmltopdf-amd64 example.pdf
  • Note remember that if you're in the folder in which the executable is, you should probably preface it with ./ just to be sure.

Worked for me anyway

Add element to a list In Scala

Since you want to append elements to existing list, you can use var List[Int] and then keep on adding elements to the same list. Note -> You have to make sure that you insert an element into existing list as follows:-

var l: List[int] = List() // creates an empty list

l = 3 :: l // adds 3 to the head of the list

l = 4 :: l // makes int 4 as the head of the list

// Now when you will print l, you will see two elements in the list ( 4, 3)

Open a PDF using VBA in Excel

If it's a matter of just opening PDF to send some keys to it then why not try this

Sub Sample()
    ActiveWorkbook.FollowHyperlink "C:\MyFile.pdf"
End Sub

I am assuming that you have some pdf reader installed.

Cursor adapter and sqlite example

In Android, How to use a Cursor with a raw query in sqlite:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
           "where Age > 10 LIMIT 5", null);

if (c != null ) {
    if  (c.moveToFirst()) {
        do {
            String firstName = c.getString(c.getColumnIndex("FirstName"));
            int age = c.getInt(c.getColumnIndex("Age"));
            results.add("" + firstName + ",Age: " + age);
        }while (c.moveToNext());

In Python script, how do I set PYTHONPATH?

you can set PYTHONPATH, by os.environ['PATHPYTHON']=/some/path, then you need to call os.system('python') to restart the python shell to make the newly added path effective.

How to loop in excel without VBA or macros?

@Nat gave a good answer. But since there is no way to shorten a code, why not use contatenate to 'generate' the code you need. It works for me when I'm lazy (at typing the whole code in the cell).

So what we need is just identify the pattern > use excel to built the pattern 'structure' > add " = " and paste it in the intended cell.

For example, you want to achieve (i mean, enter in the cell) :

=IF('testsheet'!$C$1 <= 99,'testsheet'!$A$1,"") &IF('testsheet'!$C$2 <= 99,'testsheet'!$A$2,"") &IF('testsheet'!$C$3 <= 99,'testsheet'!$A$3,"") &IF('testsheet'!$C$4 <= 99,'testsheet'!$A$4,"") &IF('testsheet'!$C$5 <= 99,'testsheet'!$A$5,"") &IF('testsheet'!$C$6 <= 99,'testsheet'!$A$6,"") &IF('testsheet'!$C$7 <= 99,'testsheet'!$A$7,"") &IF('testsheet'!$C$8 <= 99,'testsheet'!$A$8,"") &IF('testsheet'!$C$9 <= 99,'testsheet'!$A$9,"") &IF('testsheet'!$C$10 <= 99,'testsheet'!$A$10,"") &IF('testsheet'!$C$11 <= 99,'testsheet'!$A$11,"") &IF('testsheet'!$C$12 <= 99,'testsheet'!$A$12,"") &IF('testsheet'!$C$13 <= 99,'testsheet'!$A$13,"") &IF('testsheet'!$C$14 <= 99,'testsheet'!$A$14,"") &IF('testsheet'!$C$15 <= 99,'testsheet'!$A$15,"") &IF('testsheet'!$C$16 <= 99,'testsheet'!$A$16,"") &IF('testsheet'!$C$17 <= 99,'testsheet'!$A$17,"") &IF('testsheet'!$C$18 <= 99,'testsheet'!$A$18,"") &IF('testsheet'!$C$19 <= 99,'testsheet'!$A$19,"") &IF('testsheet'!$C$20 <= 99,'testsheet'!$A$20,"") &IF('testsheet'!$C$21 <= 99,'testsheet'!$A$21,"") &IF('testsheet'!$C$22 <= 99,'testsheet'!$A$22,"") &IF('testsheet'!$C$23 <= 99,'testsheet'!$A$23,"") &IF('testsheet'!$C$24 <= 99,'testsheet'!$A$24,"") &IF('testsheet'!$C$25 <= 99,'testsheet'!$A$25,"") &IF('testsheet'!$C$26 <= 99,'testsheet'!$A$26,"") &IF('testsheet'!$C$27 <= 99,'testsheet'!$A$27,"") &IF('testsheet'!$C$28 <= 99,'testsheet'!$A$28,"") &IF('testsheet'!$C$29 <= 99,'testsheet'!$A$29,"") &IF('testsheet'!$C$30 <= 99,'testsheet'!$A$30,"") &IF('testsheet'!$C$31 <= 99,'testsheet'!$A$31,"") &IF('testsheet'!$C$32 <= 99,'testsheet'!$A$32,"") &IF('testsheet'!$C$33 <= 99,'testsheet'!$A$33,"") &IF('testsheet'!$C$34 <= 99,'testsheet'!$A$34,"") &IF('testsheet'!$C$35 <= 99,'testsheet'!$A$35,"") &IF('testsheet'!$C$36 <= 99,'testsheet'!$A$36,"") &IF('testsheet'!$C$37 <= 99,'testsheet'!$A$37,"") &IF('testsheet'!$C$38 <= 99,'testsheet'!$A$38,"") &IF('testsheet'!$C$39 <= 99,'testsheet'!$A$39,"") &IF('testsheet'!$C$40 <= 99,'testsheet'!$A$40,"") 

I didn't type it, I just use "&" symbol to combine arranged cell in excel (another file, not the file we are working on).

Notice that :

part1 > IF('testsheet'!$C$

part2 > 1 to 40

part3 > <= 99,'testsheet'!$A$

part4 > 1 to 40

part5 > ,"") &

  • Enter part1 to A1, part3 to C1, part to E1.
  • Enter " = A1 " in A2, " = C1 " in C2, " = E1 " in E2.
  • Enter " = B1+1 " in B2, " = D1+1 " in D2.
  • Enter " =A2&B2&C2&D2&E2 " in G2
  • Enter " =I1&G2 " in I2

Now select A2:I2 , and drag it down. Notice that the number did the increament per row added, and the generated text is combined, cell by cell and line by line.

  • Copy I41 content,
  • paste it somewhere, add " = " in front, remove the extra & and the back.

Result = code as you intended.

I've use excel/OpenOfficeCalc to help me generate code for my projects. Works for me, hope it helps for others. (:

Adding attributes to an XML node

Well id isn't really the root node: Login is.

It should just be a case of specifying the attributes (not tags, btw) using XmlElement.SetAttribute. You haven't specified how you're creating the file though - whether you're using XmlWriter, the DOM, or any other XML API.

If you could give an example of the code you've got which isn't working, that would help a lot. In the meantime, here's some code which creates the file you described:

using System;
using System.Xml;

class Test
    static void Main()
        XmlDocument doc = new XmlDocument();
        XmlElement root = doc.CreateElement("Login");
        XmlElement id = doc.CreateElement("id");
        id.SetAttribute("userName", "Tushar");
        id.SetAttribute("passWord", "Tushar");
        XmlElement name = doc.CreateElement("Name");
        name.InnerText = "Tushar";
        XmlElement age = doc.CreateElement("Age");
        age.InnerText = "24";



Exit codes in Python

Following Unix exit codes 0 - for success / OK, 1 - non success / error. You could simply use exit(0) or exit(1) call without importing sys module.

How to enable file sharing for my app?

You just have to set UIFileSharingEnabled (Application Supports iTunes file sharing) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.

In the past, it was also necessary to define CFBundleDisplayName (Bundle Display Name), if it wasn't already there. More details here.

Is it possible to ignore one single specific line with Pylint?

Checkout the files in I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:

If the message is "No name ... in module ...", use the search:

No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers

Or, to get fewer results:

"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers

GitHub will show you:

"E0611": (
    "No name %r in module %r",
    "Used when a name cannot be found in a module.",

You can then do:

from collections import Sequence # pylint: disable=no-name-in-module

PHP: How to handle <![CDATA[ with SimpleXMLElement?

You're probably not accessing it correctly. You can output it directly or cast it as a string. (in this example, the casting is superfluous, as echo automatically does it anyway)

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
echo (string) $content;

// or with parent element:

$foo = simplexml_load_string(
    '<foo><content><![CDATA[Hello, world!]]></content></foo>'
echo (string) $foo->content;

You might have better luck with LIBXML_NOCDATA:

$content = simplexml_load_string(
    '<content><![CDATA[Hello, world!]]></content>'
    , null

Does return stop a loop?

This code will exit the loop after the first iteration in a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
  if ( == 2) {
  console.log(;// 1

the below code will jump on the condition and continue on a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];

for (const iterator of objc) {
  if ( == 2) {
  console.log(; // 1  , 3

How to get the html of a div on another page with jQuery ajax?

  success: function(data){

This console log gets an array like object: [meta, title, ,], very strange

You can use JavaScript:

var doc = document.documentElement.cloneNode()
doc.innerHTML = data
$content = $(doc.querySelector('#content'))

Retrieve data from a ReadableStream object?

Note that you can only read a stream once, so in some cases, you may need to clone the response in order to repeatedly read it:

  .then( json => console.log(json))

  .then( text => console.log(text))

Converting integer to string in Python

There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.

To convert an object in string you use the str() function. It works with any object that has a method called __str__() defined. In fact


is equivalent to


The same if you want to convert something to int, float, etc.

Java string split with "." (dot)

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.

You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

Strings as Primary Keys in SQL Database

Strings are slower in joins and in real life they are very rarely really unique (even when they are supposed to be). The only advantage is that they can reduce the number of joins if you are joining to the primary table only to get the name. However, strings are also often subject to change thus creating the problem of having to fix all related records when the company name changes or the person gets married. This can be a huge performance hit and if all tables that should be related somehow are not related (this happens more often than you think), then you might have data mismatches as well. An integer that will never change through the life of the record is a far safer choice from a data integrity standpoint as well as from a performance standpoint. Natural keys are usually not so good for maintenance of the data.

I also want to point out that the best of both worlds is often to use an autoincrementing key (or in some specialized cases, a GUID) as the PK and then put a unique index on the natural key. You get the faster joins, you don;t get duplicate records, and you don't have to update a million child records because a company name changed.

How to disassemble a memory range with GDB?

This isn't the direct answer to your question, but since you seem to just want to disassemble the binary, perhaps you could just use objdump:

objdump -d program

This should give you its dissassembly. You can add -S if you want it source-annotated.

Git: How configure KDiff3 as merge tool and diff tool

These sites were very helpful, almost, mergetool and difftool. I used the global configuration, but can be used by repository without problems. You just need to execute the following commands:

git config --global merge.tool kdiff3
git config --global mergetool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global mergetool.kdiff3.trustExitCode false

git config --global diff.guitool kdiff3
git config --global difftool.kdiff3.path "C:/Program Files/KDiff3/bin/kdiff3.exe"
git config --global difftool.kdiff3.trustExitCode false

Note that the latest version kdiff3 moved the executable from the root of the application folder C:/Program Files/KDiff3 into the bin/ folder inside the application folder. If you're using an older version, remove "bin/" from the paths above.

The use of the trustExitCode option depends on what you want to do when diff tool returns. From documentation:

git-difftool invokes a diff tool individually on each file. Errors reported by the diff tool are ignored by default. Use --trust-exit-code to make git-difftool exit when an invoked diff tool returns a non-zero exit code.

Apple Cover-flow effect using jQuery or other library?

Try Jquery Interface Elements here -

Here's a sample.

I looked around for a Jquery image carousel a few months ago and didn't find a good one so I gave up. This one was the best I could find.

Command to get nth line of STDOUT

Is Perl easily available to you?

$ perl -n -e 'if ($. == 7) { print; exit(0); }'

Obviously substitute whatever number you want for 7.

List<Map<String, String>> vs List<? extends Map<String, String>>

You cannot assign expressions with types such as List<NavigableMap<String,String>> to the first.

(If you want to know why you can't assign List<String> to List<Object> see a zillion other questions on SO.)

How can a query multiply 2 cell for each row MySQL?

I'm assuming this should work. This will actually put it in the column in your database

UPDATE yourTable yt SET yt.Total = (yt.Pieces * yt.Price)

If you want to retrieve the 2 values from the database and put your multiplication in the third column of the result only, then

SELECT yt.Pieces, yt.Price, (yt.Pieces * yt.Price) as 'Total' FROM yourTable yt

will be your friend

C# Form.Close vs Form.Dispose

Not calling Close probably bypasses sending a bunch of Win32 messages which one would think are somewhat important though I couldn't specifically tell you why...

Close has the benefit of raising events (that can be cancelled) such that an outsider (to the form) could watch for FormClosing and FormClosed in order to react accordingly.

I'm not clear whether FormClosing and/or FormClosed are raised if you simply dispose the form but I'll leave that to you to experiment with.

Cannot authenticate into mongo, "auth fails"

You can also try this :-

mongo localhost:27017/admin -u admin -p SECRETPASSWORD

Found it in this post

Here obviously the localhost can be some other host and the /admin can be some other database on which authentication has been applied

How to write dynamic variable in Ansible playbook

my_var: the variable declared

VAR: the variable, whose value is to be checked

param_1, param_2: values of the variable VAR

value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

Swipe ListView item From right to left show delete button

you can use this code

holder.img_close.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

How to change the icon of an Android app in Eclipse?

Look for this on your Manifest.xml android:icon="@drawable/ic_launcher" then change the ic_launcher to the name of your icon which is on your @drawable folder.

Reset/remove CSS styles for element only

There's a brand new solution found to this problem.

Use all: revert or all: unset.

From MDN:

The revert keyword works exactly the same as unset in many cases. The only difference is for properties that have values set by the browser or by custom stylesheets created by users (set on the browser side).

You need "A css rule available that would remove any styles previously set in the stylesheet for a particular element."

So, if the element have a class name like remove-all-styles:



<div class="remove-all-styles other-classe another-class"> 
   <!-- content -->
   <p class="text-red other-some-styles"> My text </p>

With CSS:

  .remove-all-styles {
    all: revert;

Will reset all styles applied by other-class, another-class and all other inherited and applied styles to that div.

Or in your case:

/* mobile first */
.element {
   margin: 0 10;
   transform: translate3d(0, 0, 0);
   z-index: 50;
   display: block;

@media only screen and (min-width: 980px) {
  .element {
    all: revert;

Will do.

Here we used one cool CSS property with another cool CSS value.

  1. revert

Actually revert, as the name says, reverts that property to its user or user-agent style.

  1. all

And when we use revert with the all property, all CSS properties applied to that element will be reverted to user/user-agent styles.

Click here to know difference between author, user, user-agent styles.

For ex: if we want to isolate embedded widgets/components from the styles of the page that contains them, we could write:

.isolated-component {
 all: revert;

Which will reverts all author styles (ie developer CSS) to user styles (styles which a user of our website set - less likely scenario) or to user-agent styles itself if no user styles set.

More details here:

And only issue is the support: only Safari 9.1 and iOS Safari 9.3 have support for revert value at the time of writing.

So I'll say use this style and fallback to any other answers.

Can I get the name of the current controller in the view?

controller_path holds the path of the controller used to serve the current view. (ie: admin/settings).


controller_name holds the name of the controller used to serve the current view. (ie: settings).

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

convert base64 to image in javascript/jquery

One quick and easy way:

function paintSvgToCanvas(uSvg, uCanvas) {

    var pbx = document.createElement('img');  =; =;

    pbx.src = 'data:image/svg+xml;base64,' + window.btoa(uSvg.outerHTML);
    uCanvas.getContext('2d').drawImage(pbx, 0, 0);


Run batch file from Java code

Following is worked for me

File dir = new File("E:\\test");
        ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","test.bat");;
        Process p = pb.start();

Find common substring between two strings

def LongestSubString(s1,s2):
    left = 0
    right =len(s2)
        if(s2[left] not in s1):
            left = left+1
            if(s2[left:right] not in s1):
                right = right - 1

s1 = "pineapple"
s2 = "applc"

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(model => model.IsActive, new { readonly= "readonly" })

This is just fine for text box. However, if you try to do same for the checkbox then try using this if you are using it:

@Html.CheckBoxFor(model => model.IsActive, new { onclick = "return false" })

But don't use disable, because disable always sends the default value false to the server - either it was in the checked or unchecked state. And the readonly does not work for checkbox and radio button. readonly only works for text fields.

How do I set the size of an HTML text box?

If you don't want to use the class method you can use parent-child method to make changes in the text box.

For eg. I've made a form in my form div.

HTML Code:

<div class="form">
    <textarea name="message" rows="10" cols="30" >Describe your project in detail.</textarea>

Now CSS code will be like:

.form textarea {
    height: 220px;
    width: 342px;

Problem solved.

Sum of values in an array using jQuery

If you want it to be a jquery method, you can do it like this :

$.sum = function(arr) {
    var r = 0;
    $.each(arr, function(i, v) {
        r += +v;
    return r;

and call it like this :

var sum = $.sum(["20", "40", "80", "400"]);

How to move screen without moving cursor in Vim?

zEnter does exactly what this question asks for.

It works where strangely zz would not work (vim 7.4.1689 on Ubuntu 2016.04 LTS with no special .vimrc)

How to get a Color from hexadecimal Color String

Try this:


Android eclipse DDMS - Can't access data/data/ on phone to pull files

You must edit permission of data folder.

I use "Root Explorer" (see market) app on root mode.

On top select "Monunted as r/w"

then press over data folder (long click) and find Permission option

Have a somenthing like that

        read    write  execute




Make sure that "Others" have a check for read

Then go Eclpse and try again.

Sorry about my english,I hope can help you.

Volley JsonObjectRequest Post request not working

build gradle(app)

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha01'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation ''

android manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

When you use JsonObjectRequest it is mandatory to send a jsonobject and receive jsonobject otherwise you will get an error as it only accepts jsonobject.

fun peticion(){
    val jsonObject = JSONObject()
    jsonObject.put("user", "jairo")
    jsonObject.put("password", "1234")
    val queue = Volley.newRequestQueue(this)
    val url = ""
    // GET: JsonObjectRequest( url, null,
    // POST: JsonObjectRequest( url, jsonObject,
    val jsonObjectRequest = JsonObjectRequest( url, jsonObject,
        Response.Listener { response ->
            // Check if the object 'msm' does not exist
                println("Name: "+response.getString("nombre1"))
                // If the object 'msm' exists we print it
                println("msm: "+response.getString("msm"))
        Response.ErrorListener { error ->

file php get_user.php
    header("Access-Control-Allow-Origin: *");
    header("Access-Control-Allow-Headers: *");
    // we receive the parameters
    $json = file_get_contents('php://input');
    $params = json_decode($json);
    require_once 'conexion.php';

    $verifica_usuario=mysqli_query($mysqli,"SELECT * FROM usuarios WHERE usuario='$user' and clave='$password'");
        $query="SELECT * FROM usuarios WHERE usuario='$user'";
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
        $res=array('msm'=>"Incorrect user or password");
    $jsonstring = json_encode($res);
    header('Content-Type: application/json');
    echo $jsonstring;

file php conexion
    function getConex(){
        $mysqli = mysqli_connect($servidor,$usuario,$pass,$base);
        if (mysqli_connect_errno($mysqli)){
            echo "Fallo al conectar a MySQL: " . mysqli_connect_error();
        return $mysqli;

Append lines to a file using a StreamWriter

Use this instead:

new StreamWriter("c:\\file.txt", true);

With this overload of the StreamWriter constructor you choose if you append the file, or overwrite it.

C# 4 and above offers the following syntax, which some find more readable:

new StreamWriter("c:\\file.txt", append: true);

jQuery first child of "this"


Find all children and get first of them.

git pull while not in a git directory

Starting git 1.8.5 (Q4 2013), you will be able to "use a Git command, but without having to change directories".

Just like "make -C <directory>", "git -C <directory> ..." tells Git to go there before doing anything else.

See commit 44e1e4 by Nazri Ramliy:

It takes more keypresses to invoke Git command in a different directory without leaving the current directory:

  1. (cd ~/foo && git status)
    git --git-dir=~/foo/.git --work-tree=~/foo status
    GIT_DIR=~/foo/.git GIT_WORK_TREE=~/foo git status
  2. (cd ../..; git grep foo)
  3. for d in d1 d2 d3; do (cd $d && git svn rebase); done

The methods shown above are acceptable for scripting but are too cumbersome for quick command line invocations.

With this new option, the above can be done with fewer keystrokes:

  1. git -C ~/foo status
  2. git -C ../.. grep foo
  3. for d in d1 d2 d3; do git -C $d svn rebase; done

Since Git 2.3.4 (March 2015), and commit 6a536e2 by Karthik Nayak (KarthikNayak), git will treat "git -C '<path>'" as a no-op when <path> is empty.

'git -C ""' unhelpfully dies with error "Cannot change to ''", whereas the shell treats cd ""' as a no-op.
Taking the shell's behavior as a precedent, teach git to treat -C ""' as a no-op, as well.

4 years later, Git 2.23 (Q3 2019) documents that 'git -C ""' works and doesn't change directory

It's been behaving so since 6a536e2 (git: treat "git -C '<path>'" as a no-op when <path> is empty, 2015-03-06, Git v2.3.4).

That means the documentation now (finally) includes:

If '<path>' is present but empty, e.g. -C "", then the current working directory is left unchanged.

You can see git -C used with Git 2.26 (Q1 2020), as an example.

See commit b441717, commit 9291e63, commit 5236fce, commit 10812c2, commit 62d58cd, commit b87b02c, commit 9b92070, commit 3595d10, commit f511bc0, commit f6041ab, commit f46c243, commit 99c049b, commit 3738439, commit 7717242, commit b8afb90 (20 Dec 2019) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 381e8e9, 05 Feb 2020)

t1507: inline full_name()

Signed-off-by: Denton Liu

Before, we were running test_must_fail full_name. However, test_must_fail should only be used on git commands.
Inline full_name() so that we can use test_must_fail on the git command directly.

When full_name() was introduced in 28fb84382b ("Introduce <branch>@{upstream} notation", 2009-09-10, Git v1.7.0-rc0 -- merge), the git -C option wasn't available yet (since it was introduced in 44e1e4d67d ("git: run in a directory given with -C option", 2013-09-09, Git v1.8.5-rc0 -- merge listed in batch #5)).
As a result, the helper function removed the need to manually cd each time. However, since git -C is available now, we can just use that instead and inline full_name().

Linq : select value in a datatable column

If the return value is string and you need to search by Id you can use:

string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();

or using generic variable:

var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));

Sql Server trigger insert values from new row into another table

When you are in the context of a trigger you have access to the logical table INSERTED which contains all the rows that have just been inserted to the table. You can build your insert to the other table based on a select from Inserted.

Uses for the '&quot;' entity in HTML

Reason #1

There was a point where buggy/lazy implementations of HTML/XHTML renderers were more common than those that got it right. Many years ago, I regularly encountered rendering problems in mainstream browsers resulting from the use of unencoded quote chars in regular text content of HTML/XHTML documents. Though the HTML spec has never disallowed use of these chars in text content, it became fairly standard practice to encode them anyway, so that non-spec-compliant browsers and other processors would handle them more gracefully. As a result, many "old-timers" may still do this reflexively. It is not incorrect, though it is now probably unnecessary, unless you're targeting some very archaic platforms.

Reason #2

When HTML content is generated dynamically, for example, by populating an HTML template with simple string values from a database, it's necessary to encode each value before embedding it in the generated content. Some common server-side languages provided a single function for this purpose, which simply encoded all chars that might be invalid in some context within an HTML document. Notably, PHP's htmlspecialchars() function is one such example. Though there are optional arguments to htmlspecialchars() that will cause it to ignore quotes, those arguments were (and are) rarely used by authors of basic template-driven systems. The result is that all "special chars" are encoded everywhere they occur in the generated HTML, without regard for the context in which they occur. Again, this is not incorrect, it's simply unnecessary.

Call child method from parent

You can achieve this easily in this way


  1. Create a boolean variable in the state in the parent class. Update this when you want to call a function.
  2. Create a prop variable and assign the boolean variable.
  3. From the child component access that variable using props and execute the method you want by having an if condition.

    class Child extends Component {
       --Your method body--
       render() {
         return (
        //check whether the variable has been updated or not
    class Parent extends Component {
    render() {
       return (
         //update state according to your requirement
         <Child updateMethod={this.state.callMethod}></Child>

Why doesn't Dijkstra's algorithm work for negative weight edges?

Recall that in Dijkstra's algorithm, once a vertex is marked as "closed" (and out of the open set) - the algorithm found the shortest path to it, and will never have to develop this node again - it assumes the path developed to this path is the shortest.

But with negative weights - it might not be true. For example:

      / \
     /   \
    /     \
   5       2
  /         \

V={A,B,C} ; E = {(A,C,2), (A,B,5), (B,C,-10)}

Dijkstra from A will first develop C, and will later fail to find A->B->C

EDIT a bit deeper explanation:

Note that this is important, because in each relaxation step, the algorithm assumes the "cost" to the "closed" nodes is indeed minimal, and thus the node that will next be selected is also minimal.

The idea of it is: If we have a vertex in open such that its cost is minimal - by adding any positive number to any vertex - the minimality will never change.
Without the constraint on positive numbers - the above assumption is not true.

Since we do "know" each vertex which was "closed" is minimal - we can safely do the relaxation step - without "looking back". If we do need to "look back" - Bellman-Ford offers a recursive-like (DP) solution of doing so.

Convert Long into Integer

In java ,there is a rigorous way to convert a long to int

not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.

Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);

Resetting a setTimeout

var redirectionDelay;
function startRedirectionDelay(){
    redirectionDelay = setTimeout(redirect, 115000);
function resetRedirectionDelay(){

function redirect(){
    location.href = 'file.php';

// in your click >> fire those

here is an elaborated example for what's really going on

How to split a dataframe string column into two columns?

df[['fips', 'row']] = df['row'].str.split(' ', n=1, expand=True)

Apply CSS to jQuery Dialog Buttons

There is also a simple answer for defining specific styles that are only going to be applied to that specific button and you can have Jquery declare element style when declaring the dialog:

id: "button-delete",
text: "Delete",
style: "display: none;",
click: function () {}

after doing that here is what the html shows: enter image description here

doing this allows you to set it, but it is not necessarily easy to change using jquery later.

What is the difference between README and in GitHub projects? or .mkdn or .markdown denotes that the file is markdown formatted. Markdown is a markup language. With it you can easily display headers or have italic words, or bold or almost anything that can be done to text

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied


sudo pip install virtualenv

You have a permission denied error. This states your current user does not have the root permissions.So run the command as a super user.

How do I declare class-level properties in Objective-C?

properties have a specific meaning in Objective-C, but I think you mean something that's equivalent to a static variable? E.g. only one instance for all types of Foo?

To declare class functions in Objective-C you use the + prefix instead of - so your implementation would look something like:

// Foo.h
@interface Foo {

+ (NSDictionary *)dictionary;

// Foo.m
+ (NSDictionary *)dictionary {
  static NSDictionary *fooDict = nil;
  if (fooDict == nil) {
    // create dict
  return fooDict;

What is a reasonable length limit on person "Name" fields?

UK Government Data Standards Catalogue suggests 35 characters for each of Given Name and Family Name, or 70 characters for a single field to hold the Full Name.

jQuery $(document).ready and UpdatePanels?

User Control with jQuery Inside an UpdatePanel

This isn't a direct answer to the question, but I did put this solution together by reading the answers that I found here, and I thought someone might find it useful.

I was trying to use a jQuery textarea limiter inside of a User Control. This was tricky, because the User Control runs inside of an UpdatePanel, and it was losing its bindings on callback.

If this was just a page, the answers here would have applied directly. However, User Controls do not have direct access to the head tag, nor did they have direct access to the UpdatePanel as some of the answers assume.

I ended up putting this script block right into the top of my User Control's markup. For the initial bind, it uses $(document).ready, and then it uses prm.add_endRequest from there:

<script type="text/javascript">
    function BindControlEvents() {
        //jQuery is wrapped in BindEvents function so it can be re-bound after each callback.
        //Your code would replace the following line:
            $('#<%= TextProtocolDrugInstructions.ClientID %>').limit('100', '#charsLeft_Instructions');            

    //Initial bind
    $(document).ready(function () {

    //Re-bind for callbacks
    var prm = Sys.WebForms.PageRequestManager.getInstance(); 

    prm.add_endRequest(function() { 


So... Just thought someone might like to know that this works.

Duplicate keys in .NET dictionaries?

You can add same keys with different case like:


I know is dummy answer, but worked for me.

Google Maps API v3: How do I dynamically change the marker icon?

The GMaps Utility Library has a plugin called MapIconMaker that makes it easy to generate different marker styles on the fly. It uses Google Charts to draw the markers.

There's a good demo here that shows what kind of markers you can make with it.

Android, landscape only orientation?

You can try with


Call a stored procedure with another in Oracle

@Michael Lockwood - you don't need to use the keyword "CALL" anywhere. You just need to mention the procedure call directly.

That is

   proc1(input1, input2);

instead of

   call proc1(input1, input2);

Does IE9 support console.log, and is it a real function?

I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;


Why shouldn't I use mysql_* functions in PHP?

There are many reasons, but perhaps the most important one is that those functions encourage insecure programming practices because they do not support prepared statements. Prepared statements help prevent SQL injection attacks.

When using mysql_* functions, you have to remember to run user-supplied parameters through mysql_real_escape_string(). If you forget in just one place or if you happen to escape only part of the input, your database may be subject to attack.

Using prepared statements in PDO or mysqli will make it so that these sorts of programming errors are more difficult to make.

When restoring a backup, how do I disconnect all active connections?

Try this:

WHERE DB_NAME(dbid) = 'dbname'--replace the dbname with your database
OPEN UserCursor
    SET @SQLCommand = 'KILL ' + CAST(@spid AS VARCHAR)
CLOSE UserCursor

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

mysqli::query(): Couldn't fetch mysqli

Probably somewhere you have DBconnection->close(); and then some queries try to execute .

Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)

jquery change class name

I think you're looking for this:


What is the format for the PostgreSQL connection string / URL?


How to set session variable in jquery?

Use localStorage to store the fact that you opened the page :

$(document).ready(function() {
    var yetVisited = localStorage['visited'];
    if (!yetVisited) {
        // open popup
        localStorage['visited'] = "yes";

git returns http error 407 from proxy after CONNECT

Your password seems to be incorrect. Recheck your credentials.

How to replicate vector in c?

Here's my implementation. It's basicaly a struct containing pointer to the data, size (in elements), overall allocated space and a size of the type that's being stored in vector to allow use of void pointer.

WPF C# button style

   <Button x:Name="mybtnSave" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top"  Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF080505" Offset="1"/>
                <GradientStop Color="White" Offset="0.536"/>
        <StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF3ED82E" Offset="0"/>
                    <GradientStop Color="#FF3BF728" Offset="1"/>
                    <GradientStop Color="#FF212720" Offset="0.52"/>
            <Image HorizontalAlignment="Left"  Source="image/Append Or Save 3.png" Height="36" Width="203" />
            <TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
    </Button>ente[![enter image description here][1]][1]r image description here

HTML: How to limit file upload to be only images?

You can only do this securely on the server-side. Using the "accept" attribute is good, but must also be validated on the server side lest users be able to cURL to your script without that limitation.

I suggest that you: discard any non-image file, warn the user, and redisplay the form.

Knockout validation

If you don't want to use the KnockoutValidation library you can write your own. Here's an example for a Mandatory field.

Add a javascript class with all you KO extensions or extenders, and add the following:

ko.extenders.required = function (target, overrideMessage) {
    //add some sub-observables to our observable
    target.hasError = ko.observable();
    target.validationMessage = ko.observable();

    //define a function to do validation
    function validate(newValue) {
    target.hasError(newValue ? false : true);
    target.validationMessage(newValue ? "" : overrideMessage || "This field is required");

    //initial validation

    //validate whenever the value changes

    //return the original observable
    return target;

Then in your viewModel extend you observable by:

self.dateOfPayment: ko.observable().extend({ required: "" }),

There are a number of examples online for this style of validation.

Can't connect to MySQL server error 111

If you're running cPanel/WHM, make sure that IP is whitelisted in the firewall. You will als need to add that IP to the remote SQL IP list in the cPanel account you're trying to connect to.

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=' or one of its dependencies

I had a project with the same problem , I solved it with change dotnet core version from 2.2 to 2.0, If your problem has remained , Try this solution

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

What does @media screen and (max-width: 1024px) mean in CSS?

Also worth noting you can use 'em' as well as 'px' - blogs and text based sites do it because then the browser makes layout decisions more relative to the text content.

On Wordpress twentysixteen I wanted my tagline to display on mobiles as well as desktops, so I put this in my child theme style.css

@media screen and (max-width:59em){ {
        display:    block;

ArrayList vs List<> in C#

To me its all about knowing your data. If I am continuing to expand my code on the basis of efficiency, I would have to choose the List option as a way of deciphering of my data w/o the unnecessary step of always wondering about types, especially 'Custom Types'. If the machine understands the difference and can determine on it's on what type of data I'm actually dealing with then why should I get in the way and waste time going thru the gyrations of 'IF THEN ELSE' determinations? My philosophy is to let the machine work for me instead of me working on the machine? Knowing the unique differences of different object code commands goes a long way in making your code as efficient.

Tom Johnson (One Entry ... One Exit)

How to grep Git commit diffs or contents for a certain word?

To use boolean connector on regular expression:

git log --grep '[0-9]*\|[a-z]*'

This regular expression search for regular expression [0-9]* or [a-z]* on commit messages.

Close window automatically after printing dialog closes

Here's what I do....

Enable window to print and close itself based on a query parameter.

Requires jQuery. Can be done in _Layout or master page to work with all pages.

The idea is to pass a param in the URL telling the page to print and close, if the param is set then the jQuery “ready” event prints the window, and then when the page is fully loaded (after printing) the “onload” is called which closes the window. All this seemingly extra steps are to wait for the window to print before closing itself.

In the html body add and onload event that calls printAndCloseOnLoad(). In this example we are using cshtm, you could also use javascript to get param.

<body onload="sccPrintAndCloseOnLoad('@Request.QueryString["PrintAndClose"]');">

In the javascript add the function.

function printAndCloseOnLoad(printAndClose) {
    if (printAndClose) {
        // close self without prompting'', '_self', ''); window.close();

And jQuery ready event.

$(document).ready(function () {
    if ("PrintAndClose=") > 0)

Now when opening any URL, simply append the query string param “PrintAndClose=true” and it will print and close.

Why does Java have transient fields?

Serialization systems other than the native java one can also use this modifier. Hibernate, for instance, will not persist fields marked with either @Transient or the transient modifier. Terracotta as well respects this modifier.

I believe the figurative meaning of the modifier is "this field is for in-memory use only. don't persist or move it outside of this particular VM in any way. Its non-portable". i.e. you can't rely on its value in another VM memory space. Much like volatile means you can't rely on certain memory and thread semantics.

How to print a stack trace in Node.js?

With a readily available Node module, it is possible to get full-length stack traces out of Node (albeit with a minor performance penalty):

Testing if a site is vulnerable to Sql Injection

The easiest way to protect yourself is to use stored procedures instead of inline SQL statements.

Then use "least privilege" permissions and only allow access to stored procedures and not directly to tables.

Chrome DevTools Devices does not detect device when plugged in

I've worked with six different Android devices and multiple cables and I have to say that debugger works unstably. Sometimes it can see the device, sometimes it doesn't. Sometimes restarting Chrome helps. Here is a related bug, may be you can contribute with your evidence.

Extract substring using regexp in plain bash

Quick 'n dirty, regex-free, low-robustness chop-chop technique

string="US/Central - 10:26 PM (CST)"
etime="${string% [AP]M*}"
etime="${etime#* - }"

Convert Linq Query Result to Dictionary

Try the following

Dictionary<int, DateTime> existingItems = 
    (from ObjType ot in TableObj).ToDictionary(x => x.Key);

Or the fully fledged type inferenced version

var existingItems = TableObj.ToDictionary(x => x.Key);

Decreasing height of bootstrap 3.0 navbar

This is my experience

 .navbar { min-height:38px;   }
 .navbar .navbar-brand{ padding: 0 12px;font-size: 16px;line-height: 38px;height: 38px; }
 .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 38px; }
 .navbar .navbar-toggle {  margin-top: 3px; margin-bottom: 0px; padding: 8px 9px; }
 .navbar .navbar-form { margin-top: 2px; margin-bottom: 0px }
 .navbar .navbar-collapse {border-color: #A40303;}

change height of navabr to 38px

Saving an image in OpenCV

I use the following code to capture images:

CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY );
if(!capture) error((char*)"No Capture");
IplImage *img=cvQueryFrame(capture);

I know this works for sure

How to remove underline from a link in HTML?

  1. Add this to your external style sheet (preferred):

    a {text-decoration:none;}
  2. Or add this to the <head> of your HTML document:

    <style type="text/css">
     a {text-decoration:none;}
  3. Or add it to the a element itself (not recommended):

    <!-- Add [ style="text-decoration:none;"] -->
    <a href="" style="text-decoration:none;">Text</a>

How to calculate time elapsed in bash script?

Here's my bash implementation (with bits taken from other SO ;-)

function countTimeDiff() {
    timeA=$1 # 09:59:35
    timeB=$2 # 17:32:55

    # feeding variables by using read and splitting with IFS
    IFS=: read ah am as <<< "$timeA"
    IFS=: read bh bm bs <<< "$timeB"

    # Convert hours to minutes.
    # The 10# is there to avoid errors with leading zeros
    # by telling bash that we use base 10
    secondsA=$((10#$ah*60*60 + 10#$am*60 + 10#$as))
    secondsB=$((10#$bh*60*60 + 10#$bm*60 + 10#$bs))
    DIFF_SEC=$((secondsB - secondsA))
    echo "The difference is $DIFF_SEC seconds.";

    echo $TIME_DIFF;

$ countTimeDiff 2:15:55 2:55:16
The difference is 2361 seconds.

Not tested, may be buggy.

iconv - Detected an illegal character in input string

PHP 7.2

iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// "e@uu$`a"

iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"

iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@uu$`a"

PHP 7.4

iconv('UTF-8', 'ASCII//TRANSLIT', 'é@ùµ$`à');
// PHP Notice:  iconv(): Detected an illegal character

iconv('UTF-8', 'ASCII//IGNORE', 'é@ùµ$`à');
// "@$`"

iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', 'é@ùµ$`à');
// "e@u$`a"

iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', Transliterator::create('Any-Latin; NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate('é@ùµ$`à'))
// "e@uu$`a" -> same as PHP 7.2