Programs & Examples On #Cells

How can I disable editing cells in a WPF Datagrid?

If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"

<DataGrid IsReadOnly="True" CanUserAddRows="False" />

Further more you can set IsReadOnly on individual columns to disable editing.

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

configure: error: C compiler cannot create executables

In my case, I tried xcode-select --install but it says that it's not available from the store. Then, inspired by Rimian, I checked my gcc : gcc -v and then I got a message saying I did not aggreed.

From that point I just followed the agreement process from gcc -v, after I agreed it works fine for me.

How to get current SIM card number in Android?

I think sim serial Number and sim number is unique. You can try this for get sim serial number and get sim number and Don't forget to add permission in manifest file.

TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String getSimSerialNumber = telemamanger.getSimSerialNumber();
String getSimNumber = telemamanger.getLine1Number();

And add below permission into your Androidmanifest.xml file.

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

Let me know if there is any issue.

python pandas dataframe to dictionary

You need a list as a dictionary value. This code will do the trick.

from collections import defaultdict
mydict = defaultdict(list)
for k, v in zip(df.id.values,df.value.values):
    mydict[k].append(v)

How do I append text to a file?

cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter. 
^D

Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.

resize2fs: Bad magic number in super-block while trying to open

resize2fs Command will not work for all file systems.

Please confirm the file system of your instance using below command. enter image description here

Please follow the procedure to expand volume by following the steps mentioned in Amazon official document for different file systems.

https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html

Default file system in Centos is xfs, use the following command for xfs file system to increase partition size.

sudo xfs_growfs -d /

then "df -h" to check.

How can I force users to access my page over HTTPS instead of HTTP?

Ok.. Now there is tons of stuff on this now but no one really completes the "Secure" question. For me it is rediculous to use something that is insecure.

Unless you use it as bait.

$_SERVER propagation can be changed at the will of someone who knows how.

Also as Sazzad Tushar Khan and the thebigjc stated you can also use httaccess to do this and there are a lot of answers here containing it.

Just add:

RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

to the end of what you have in your .httaccess and thats that.

Still we are not as secure as we possibly can be with these 2 tools.

The rest is simple. If there are missing attributes ie...

if(empty($_SERVER["HTTPS"])){ // SOMETHING IS FISHY
}

if(strstr($_SERVER['HTTP_HOST'],"mywebsite.com") === FALSE){// Something is FISHY
}


Also say you have updated your httaccess file and you check:

if($_SERVER["HTTPS"] !== "on"){// Something is fishy
}

There are a lot more variables you can check ie..

HOST_URI (If there are static atributes about it to check)

HTTP_USER_AGENT (Same session different values)

So all Im saying is dont just settle for one or the other when the answer lies in a combination.

For more httaccess rewriting info see the docs-> http://httpd.apache.org/docs/2.0/misc/rewriteguide.html

Some Stacks here -> Force SSL/https using .htaccess and mod_rewrite
and
Getting the full URL of the current page (PHP)
to name a couple.

NodeJS w/Express Error: Cannot GET /

Where is your get method for "/"?

Also you cant serve static html directly in Express.First you need to configure it.

app.configure(function(){
  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 
  app.use(app.router);

});

Now add your get method.

app.get('/', function(req, res) {
  res.render('default.htm');
});

Ubuntu apt-get unable to fetch packages

I tried using :

sudo do-release-upgrade

and then use :

sudo apt-get update

after that you will be able to install any packages.

If this did not worked for you try to change the network conf in apt.conf

Angular cookies

I make Miquels Version Injectable as service:

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

@Injectable()
export class CookiesService {

    isConsented = false;

    constructor() {}

    /**
     * delete cookie
     * @param name
     */
    public deleteCookie(name) {
        this.setCookie(name, '', -1);
    }

    /**
     * get cookie
     * @param {string} name
     * @returns {string}
     */
    public getCookie(name: string) {
        const ca: Array<string> = decodeURIComponent(document.cookie).split(';');
        const caLen: number = ca.length;
        const cookieName = `${name}=`;
        let c: string;

        for (let i  = 0; i < caLen; i += 1) {
            c = ca[i].replace(/^\s+/g, '');
            if (c.indexOf(cookieName) === 0) {
                return c.substring(cookieName.length, c.length);
            }
        }
        return '';
    }

    /**
     * set cookie
     * @param {string} name
     * @param {string} value
     * @param {number} expireDays
     * @param {string} path
     */
    public setCookie(name: string, value: string, expireDays: number, path: string = '') {
        const d: Date = new Date();
        d.setTime(d.getTime() + expireDays * 24 * 60 * 60 * 1000);
        const expires = `expires=${d.toUTCString()}`;
        const cpath = path ? `; path=${path}` : '';
        document.cookie = `${name}=${value}; ${expires}${cpath}; SameSite=Lax`;
    }

    /**
     * consent
     * @param {boolean} isConsent
     * @param e
     * @param {string} COOKIE
     * @param {string} EXPIRE_DAYS
     * @returns {boolean}
     */
    public consent(isConsent: boolean, e: any, COOKIE: string, EXPIRE_DAYS: number) {
        if (!isConsent) {
            return this.isConsented;
        } else if (isConsent) {
            this.setCookie(COOKIE, '1', EXPIRE_DAYS);
            this.isConsented = true;
            e.preventDefault();
        }
    }

}

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

UILabel text margin

For Xamarin users (using Unified API):

class UIMarginLabel : UILabel
{
    public UIMarginLabel()
    {
    }

    public UIMarginLabel( CGRect frame ) : base( frame )
    {
    }

    public UIEdgeInsets Insets { get; set; }

    public override void DrawText( CGRect rect )
    {
        base.DrawText( Insets.InsetRect( rect ) );
    }
}

And for those using the original MonoTouch API:

public class UIMarginLabel : UILabel
{
    public UIEdgeInsets Insets { get; set; }

    public UIMarginLabel() : base()
    {
        Insets = new UIEdgeInsets(0, 0, 0, 0);
    }
    public UIMarginLabel(RectangleF frame) : base(frame)
    {
        Insets = new UIEdgeInsets(0, 0, 0, 0);
    }

    public override void DrawText(RectangleF frame)
    {
        base.DrawText(new RectangleF(
            frame.X + Insets.Left,
            frame.Y + Insets.Top,
            frame.Width - Insets.Left - Insets.Right,
            frame.Height - Insets.Top - Insets.Bottom));
    }
}

Best way to log POST data in Apache?

Use Apache's mod_dumpio. Be careful for obvious reasons.

Note that mod_dumpio stops logging binary payloads at the first null character. For example a multipart/form-data upload of a gzip'd file will probably only show the first few bytes with mod_dumpio.

Also note that Apache might not mention this module in httpd.conf even when it's present in the /modules folder. Just manually adding LoadModule will work fine.

Documentation for using JavaScript code inside a PDF file

Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"

Revised: January 27, 1999

It’s very old, but it is still useful.

Least common multiple for 3 or more numbers

Some Python code that doesn't require a function for gcd:

from sys import argv 

def lcm(x,y):
    tmp=x
    while (tmp%y)!=0:
        tmp+=x
    return tmp

def lcmm(*args):
    return reduce(lcm,args)

args=map(int,argv[1:])
print lcmm(*args)

Here's what it looks like in the terminal:

$ python lcm.py 10 15 17
510

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

How to set the title text color of UIButton?

Swift UI solution

Button(action: {}) {
            Text("Button")
        }.foregroundColor(Color(red: 1.0, green: 0.0, blue: 0.0))

Swift 3, Swift 4, Swift 5

to improve comments. This should work:

button.setTitleColor(.red, for: .normal)

ASP.NET Core Web API exception handling

Your best bet is to use middleware to achieve logging you're looking for. You want to put your exception logging in one middleware and then handle your error pages displayed to the user in a different middleware. That allows separation of logic and follows the design Microsoft has laid out with the 2 middleware components. Here's a good link to Microsoft's documentation: Error Handling in ASP.Net Core

For your specific example, you may want to use one of the extensions in the StatusCodePage middleware or roll your own like this.

You can find an example here for logging exceptions: ExceptionHandlerMiddleware.cs

public void Configure(IApplicationBuilder app)
{
    // app.UseErrorPage(ErrorPageOptions.ShowAll);
    // app.UseStatusCodePages();
    // app.UseStatusCodePages(context => context.HttpContext.Response.SendAsync("Handler, status code: " + context.HttpContext.Response.StatusCode, "text/plain"));
    // app.UseStatusCodePages("text/plain", "Response, status code: {0}");
    // app.UseStatusCodePagesWithRedirects("~/errors/{0}");
    // app.UseStatusCodePagesWithRedirects("/base/errors/{0}");
    // app.UseStatusCodePages(builder => builder.UseWelcomePage());
    app.UseStatusCodePagesWithReExecute("/Errors/{0}");  // I use this version

    // Exception handling logging below
    app.UseExceptionHandler();
}

If you don't like that specific implementation, then you can also use ELM Middleware, and here are some examples: Elm Exception Middleware

public void Configure(IApplicationBuilder app)
{
    app.UseStatusCodePagesWithReExecute("/Errors/{0}");
    // Exception handling logging below
    app.UseElmCapture();
    app.UseElmPage();
}

If that doesn't work for your needs, you can always roll your own Middleware component by looking at their implementations of the ExceptionHandlerMiddleware and the ElmMiddleware to grasp the concepts for building your own.

It's important to add the exception handling middleware below the StatusCodePages middleware but above all your other middleware components. That way your Exception middleware will capture the exception, log it, then allow the request to proceed to the StatusCodePage middleware which will display the friendly error page to the user.

How to represent matrices in python

Take a look at this answer:

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

Binding List<T> to DataGridView in WinForm

List does not implement IBindingList so the grid does not know about your new items.

Bind your DataGridView to a BindingList<T> instead.

var list = new BindingList<Person>(persons);
myGrid.DataSource = list;

But I would even go further and bind your grid to a BindingSource

var list = new List<Person>()
{
    new Person { Name = "Joe", },
    new Person { Name = "Misha", },
};
var bindingList = new BindingList<Person>(list);
var source = new BindingSource(bindingList, null);
grid.DataSource = source;

Shell script to send email

Yes it works fine and is commonly used:

$ echo "hello world" | mail -s "a subject" [email protected]

After updating Entity Framework model, Visual Studio does not see changes

Are you working in an N-Tiered project? If so, try rebuilding your Data Layer (or wherever your EDMX file is stored) before using it.

Loading DLLs at runtime in C#

It's not so difficult.

You can inspect the available functions of the loaded object, and if you find the one you're looking for by name, then snoop its expected parms, if any. If it's the call you're trying to find, then call it using the MethodInfo object's Invoke method.

Another option is to simply build your external objects to an interface, and cast the loaded object to that interface. If successful, call the function natively.

This is pretty simple stuff.

The way to check a HDFS directory's size?

Extending to Matt D and others answers, the command can be till Apache Hadoop 3.0.0

hadoop fs -du [-s] [-h] [-v] [-x] URI [URI ...]

It displays sizes of files and directories contained in the given directory or the length of a file in case it's just a file.

Options:

  • The -s option will result in an aggregate summary of file lengths being displayed, rather than the individual files. Without the -s option, the calculation is done by going 1-level deep from the given path.
  • The -h option will format file sizes in a human-readable fashion (e.g 64.0m instead of 67108864)
  • The -v option will display the names of columns as a header line.
  • The -x option will exclude snapshots from the result calculation. Without the -x option (default), the result is always calculated from all INodes, including all snapshots under the given path.

du returns three columns with the following format:

 +-------------------------------------------------------------------+ 
 | size  |  disk_space_consumed_with_all_replicas  |  full_path_name | 
 +-------------------------------------------------------------------+ 

##Example command:

hadoop fs -du /user/hadoop/dir1 \
    /user/hadoop/file1 \
    hdfs://nn.example.com/user/hadoop/dir1 

Exit Code: Returns 0 on success and -1 on error.

source: Apache doc

using href links inside <option> tag

<select name="forma" onchange="location = this.value;">
 <option value="Home.php">Home</option>
 <option value="Contact.php">Contact</option>
 <option value="Sitemap.php">Sitemap</option>
</select>

UPDATE (Nov 2015): In this day and age if you want to have a drop menu there are plenty of arguably better ways to implement one. This answer is a direct answer to a direct question, but I don't advocate this method for public facing web sites.

UPDATE (May 2020): Someone asked in the comments why I wouldn't advocate this solution. I guess it's a question of semantics. I'd rather my users navigate using <a> and kept <select> for making form selections because HTML elements have semantic meeting and they have a purpose, anchors take you places, <select> are for picking things from lists.

Consider, if you are viewing a page with a non-traditional browser (a non graphical browser or screen reader or the page is accessed programmatically, or JavaScript is disabled) what then is the "meaning" or the "intent" of this <select> you have used for navigation? It is saying "please pick a page name" and not a lot else, certainly nothing about navigating. The easy response to this is well i know that my users will be using IE or whatever so shrug but this kinda misses the point of semantic importance.

Whereas a funky drop-down UI element made of suitable layout elements (and some js) containing some regular anchors still retains it intent even if the layout element is lost, "these are a bunch of links, select one and we will navigate there".

Here is an article on the misuse and abuse of <select>.

nginx missing sites-available directory

If you'd prefer a more direct approach, one that does NOT mess with symlinking between /etc/nginx/sites-available and /etc/nginx/sites-enabled, do the following:

  1. Locate your nginx.conf file. Likely at /etc/nginx/nginx.conf
  2. Find the http block.
  3. Somewhere in the http block, write include /etc/nginx/conf.d/*.conf; This tells nginx to pull in any files in the conf.d directory that end in .conf. (I know: it's weird that a directory can have a . in it.)
  4. Create the conf.d directory if it doesn't already exist (per the path in step 3). Be sure to give it the right permissions/ownership. Likely root or www-data.
  5. Move or copy your separate config files (just like you have in /etc/nginx/sites-available) into the directory conf.d.
  6. Reload or restart nginx.
  7. Eat an ice cream cone.

Any .conf files that you put into the conf.d directory from here on out will become active as long as you reload/restart nginx after.

Note: You can use the conf.d and sites-enabled + sites-available method concurrently if you wish. I like to test on my dev box using conf.d. Feels faster than symlinking and unsymlinking.

Maintaining Session through Angular.js

Typically for a use case which involves a sequence of pages and in the final stage or page we post the data to the server. In this scenario we need to maintain the state. In the below snippet we maintain the state on the client side

As mentioned in the above post. The session is created using the factory recipe.

Client side session can be maintained using the value provider recipe as well.

Please refer to my post for the complete details. session-tracking-in-angularjs

Let's take an example of a shopping cart which we need to maintain across various pages / angularjs controller.

In typical shopping cart we buy products on various product / category pages and keep updating the cart. Here are the steps.

Here we create the custom injectable service having a cart inside using the "value provider recipe".

'use strict';
function Cart() {
    return {
        'cartId': '',
        'cartItem': []
    };
}
// custom service maintains the cart along with its behavior to clear itself , create new , delete Item or update cart 

app.value('sessionService', {
    cart: new Cart(),
    clear: function () {
        this.cart = new Cart();
        // mechanism to create the cart id 
        this.cart.cartId = 1;
    },
    save: function (session) {
        this.cart = session.cart;
    },
    updateCart: function (productId, productQty) {
        this.cart.cartItem.push({
            'productId': productId,
            'productQty': productQty
        });
    },
    //deleteItem and other cart operations function goes here...
});

How to center a WPF app on screen?

xaml

<Window ... WindowStartupLocation="CenterScreen">...

Upload artifacts to Nexus, without Maven

The calls that you need to make against Nexus are REST api calls.

The maven-nexus-plugin is a Maven plugin that you can use to make these calls. You could create a dummy pom with the necessary properties and make those calls through the Maven plugin.

Something like:

mvn -DserverAuthId=sonatype-nexus-staging -Dauto=true nexus:staging-close

Assumed things:

  1. You have defined a server in your ~/.m2/settings.xml named sonatype-nexus-staging with your sonatype user and password set up - you will probably already have done this if you are deploying snapshots. But you can find more info here.
  2. Your local settings.xml includes the nexus plugins as specified here.
  3. The pom.xml sitting in your current directory has the correct Maven coordinates in its definition. If not, you can specify the groupId, artifactId, and version on the command line.
  4. The -Dauto=true will turn off the interactive prompts so you can script this.

Ultimately, all this is doing is creating REST calls into Nexus. There is a full Nexus REST api but I have had little luck finding documentation for it that's not behind a paywall. You can turn on the debug mode for the plugin above and figure it out however by using -Dnexus.verboseDebug=true -X.

You could also theoretically go into the UI, turn on the Firebug Net panel, and watch for /service POSTs and deduce a path there as well.

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

How to determine whether a given Linux is 32 bit or 64 bit?

That system is 32bit. iX86 in uname means it is a 32-bit architecture. If it was 64 bit, it would return

Linux mars 2.6.9-67.0.15.ELsmp #1 SMP Tue Apr 22 13:50:33 EDT 2008 x86_64 i686 x86_64 x86_64 GNU/Linux

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

How to detect a loop in a linked list?

// linked list find loop function

int findLoop(struct Node* head)
{
    struct Node* slow = head, *fast = head;
    while(slow && fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
        if(slow == fast)
            return 1;
    }
 return 0;
}

Synchronous XMLHttpRequest warning and <script>

In my case this was caused by the flexie script which was part of the "CDNJS Selections" app offered by Cloudflare.

According to Cloudflare "This app is being deprecated in March 2015". I turned it off and the message disappeared instantly.

You can access the apps by visiting https://www.cloudflare.com/a/cloudflare-apps/yourdomain.com

Change div width live with jQuery

Got better solution:

$('#element').resizable({
    stop: function( event, ui ) {
        $('#element').height(ui.originalSize.height);
    }
});

What does the 'export' command do?

I guess you're coming from a windows background. So i'll contrast them (i'm kind of new to linux too). I found user's reply to my comment, to be useful in figuring things out.

In Windows, a variable can be permanent or not. The term Environment variable includes a variable set in the cmd shell with the SET command, as well as when the variable is set within the windows GUI, thus set in the registry, and becoming viewable in new cmd windows. e.g. documentation for the set command in windows https://technet.microsoft.com/en-us/library/bb490998.aspx "Displays, sets, or removes environment variables. Used without parameters, set displays the current environment settings." In Linux, set does not display environment variables, it displays shell variables which it doesn't call/refer to as environment variables. Also, Linux doesn't use set to set variables(apart from positional parameters and shell options, which I explain as a note at the end), only to display them and even then only to display shell variables. Windows uses set for setting and displaying e.g. set a=5, linux doesn't.

In Linux, I guess you could make a script that sets variables on bootup, e.g. /etc/profile or /etc/.bashrc but otherwise, they're not permanent. They're stored in RAM.

There is a distinction in Linux between shell variables, and environment variables. In Linux, shell variables are only in the current shell, and Environment variables, are in that shell and all child shells.

You can view shell variables with the set command (though note that unlike windows, variables are not set in linux with the set command).

set -o posix; set (doing that set -o posix once first, helps not display too much unnecessary stuff). So set displays shell variables.

You can view environment variables with the env command

shell variables are set with e.g. just a = 5

environment variables are set with export, export also sets the shell variable

Here you see shell variable zzz set with zzz = 5, and see it shows when running set but doesn't show as an environment variable.

Here we see yyy set with export, so it's an environment variable. And see it shows under both shell variables and environment variables

$ zzz=5

$ set | grep zzz
zzz=5

$ env | grep zzz

$ export yyy=5

$ set | grep yyy
yyy=5

$ env | grep yyy
yyy=5

$

other useful threads

https://unix.stackexchange.com/questions/176001/how-can-i-list-all-shell-variables

https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference

Note- one point which elaborates a bit and is somewhat corrective to what i've written, is that, in linux bash, 'set' can be used to set "positional parameters" and "shell options/attributes", and technically both of those are variables, though the man pages might not describe them as such. But still, as mentioned, set won't set shell variables or environment variables). If you do set asdf then it sets $1 to asdf, and if you do echo $1 you see asdf. If you do set a=5 it won't set the variable a, equal to 5. It will set the positional parameter $1 equal to the string of "a=5". So if you ever saw set a=5 in linux it's probably a mistake unless somebody actually wanted that string a=5, in $1. The other thing that linux's set can set, is shell options/attributes. If you do set -o you see a list of them. And you can do for example set -o verbose, off, to turn verbose on(btw the default happens to be off but that makes no difference to this). Or you can do set +o verbose to turn verbose off. Windows has no such usage for its set command.

How to obtain a Thread id in Python?

Similarly to @brucexin I needed to get OS-level thread identifier (which != thread.get_ident()) and use something like below not to depend on particular numbers and being amd64-only:

---- 8< ---- (xos.pyx)
"""module xos complements standard module os""" 

cdef extern from "<sys/syscall.h>":                                                             
    long syscall(long number, ...)                                                              
    const int SYS_gettid                                                                        

# gettid returns current OS thread identifier.                                                  
def gettid():                                                                                   
    return syscall(SYS_gettid)                                                                  

and

---- 8< ---- (test.py)
import pyximport; pyximport.install()
import xos

...

print 'my tid: %d' % xos.gettid()

this depends on Cython though.

How to select where ID in Array Rails ActiveRecord without exception

If it is just avoiding the exception you are worried about, the "find_all_by.." family of functions works without throwing exceptions.

Comment.find_all_by_id([2, 3, 5])

will work even if some of the ids don't exist. This works in the

user.comments.find_all_by_id(potentially_nonexistent_ids)

case as well.

Update: Rails 4

Comment.where(id: [2, 3, 5])

Setting table row height

line-height only works when it is larger then the current height of the content of <td> . So, if you have a 50x50 icon in the table, the tr line-height will not make a row smaller than 50px (+ padding).

Since you've already set the padding to 0 it must be something else,
for example a large font-size inside td that is larger than your 14px.

How to timeout a thread

In the solution given by BalusC, the main thread will stay blocked for the timeout period. If you have a thread pool with more than one thread, you will need the same number of additional thread that will be using Future.get(long timeout,TimeUnit unit) blocking call to wait and close the thread if it exceeds the timeout period.

A generic solution to this problem is to create a ThreadPoolExecutor Decorator that can add the timeout functionality. This Decorator class should create as many threads as ThreadPoolExecutor has, and all these threads should be used only to wait and close the ThreadPoolExecutor.

The generic class should be implemented like below:

import java.util.List;
import java.util.concurrent.*;

public class TimeoutThreadPoolDecorator extends ThreadPoolExecutor {


    private final ThreadPoolExecutor commandThreadpool;
    private final long timeout;
    private final TimeUnit unit;

    public TimeoutThreadPoolDecorator(ThreadPoolExecutor threadpool,
                                      long timeout,
                                      TimeUnit unit ){
        super(  threadpool.getCorePoolSize(),
                threadpool.getMaximumPoolSize(),
                threadpool.getKeepAliveTime(TimeUnit.MILLISECONDS),
                TimeUnit.MILLISECONDS,
                threadpool.getQueue());

        this.commandThreadpool = threadpool;
        this.timeout=timeout;
        this.unit=unit;
    }

    @Override
    public void execute(Runnable command) {
        super.execute(() -> {
            Future<?> future = commandThreadpool.submit(command);
            try {
                future.get(timeout, unit);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } catch (ExecutionException | TimeoutException e) {
                throw new RejectedExecutionException(e);
            } finally {
                future.cancel(true);
            }
        });
    }

    @Override
    public void setCorePoolSize(int corePoolSize) {
        super.setCorePoolSize(corePoolSize);
        commandThreadpool.setCorePoolSize(corePoolSize);
    }

    @Override
    public void setThreadFactory(ThreadFactory threadFactory) {
        super.setThreadFactory(threadFactory);
        commandThreadpool.setThreadFactory(threadFactory);
    }

    @Override
    public void setMaximumPoolSize(int maximumPoolSize) {
        super.setMaximumPoolSize(maximumPoolSize);
        commandThreadpool.setMaximumPoolSize(maximumPoolSize);
    }

    @Override
    public void setKeepAliveTime(long time, TimeUnit unit) {
        super.setKeepAliveTime(time, unit);
        commandThreadpool.setKeepAliveTime(time, unit);
    }

    @Override
    public void setRejectedExecutionHandler(RejectedExecutionHandler handler) {
        super.setRejectedExecutionHandler(handler);
        commandThreadpool.setRejectedExecutionHandler(handler);
    }

    @Override
    public List<Runnable> shutdownNow() {
        List<Runnable> taskList = super.shutdownNow();
        taskList.addAll(commandThreadpool.shutdownNow());
        return taskList;
    }

    @Override
    public void shutdown() {
        super.shutdown();
        commandThreadpool.shutdown();
    }
}

The above decorator can be used as below:

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Main {

    public static void main(String[] args){

        long timeout = 2000;

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(3, 10, 0, TimeUnit.MILLISECONDS, new SynchronousQueue<>(true));

        threadPool = new TimeoutThreadPoolDecorator( threadPool ,
                timeout,
                TimeUnit.MILLISECONDS);


        threadPool.execute(command(1000));
        threadPool.execute(command(1500));
        threadPool.execute(command(2100));
        threadPool.execute(command(2001));

        while(threadPool.getActiveCount()>0);
        threadPool.shutdown();


    }

    private static Runnable command(int i) {

        return () -> {
            System.out.println("Running Thread:"+Thread.currentThread().getName());
            System.out.println("Starting command with sleep:"+i);
            try {
                Thread.sleep(i);
            } catch (InterruptedException e) {
                System.out.println("Thread "+Thread.currentThread().getName()+" with sleep of "+i+" is Interrupted!!!");
                return;
            }
            System.out.println("Completing Thread "+Thread.currentThread().getName()+" after sleep of "+i);
        };

    }
}

How can I override Bootstrap CSS styles?

Using !important is not a good option, as you will most likely want to override your own styles in the future. That leaves us with CSS priorities.

Basically, every selector has its own numerical 'weight':

  • 100 points for IDs
  • 10 points for classes and pseudo-classes
  • 1 point for tag selectors and pseudo-elements
  • Note: If the element has inline styling that automatically wins (1000 points)

Among two selector styles browser will always choose the one with more weight. Order of your stylesheets only matters when priorities are even - that's why it is not easy to override Bootstrap.

Your option is to inspect Bootstrap sources, find out how exactly some specific style is defined, and copy that selector so your element has equal priority. But we kinda loose all Bootstrap sweetness in the process.

The easiest way to overcome this is to assign additional arbitrary ID to one of the root elements on your page, like this: <body id="bootstrap-overrides">

This way, you can just prefix any CSS selector with your ID, instantly adding 100 points of weight to the element, and overriding Bootstrap definitions:

/* Example selector defined in Bootstrap */
.jumbotron h1 { /* 10+1=11 priority scores */
  line-height: 1;
  color: inherit;
}

/* Your initial take at styling */
h1 { /* 1 priority score, not enough to override Bootstrap jumbotron definition */
  line-height: 1;
  color: inherit;
}

/* New way of prioritization */
#bootstrap-overrides h1 { /* 100+1=101 priority score, yay! */
  line-height: 1;
  color: inherit;
}

Connecting to remote URL which requires authentication using Java

Was able to set the auth using the HttpsURLConnection

           URL myUrl = new URL(httpsURL);
            HttpsURLConnection conn = (HttpsURLConnection)myUrl.openConnection();
            String userpass = username + ":" + password;
            String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
            //httpsurlconnection
            conn.setRequestProperty("Authorization", basicAuth);

few of the changes fetched from this post. and Base64 is from java.util package.

Make Error 127 when running trying to compile code

Error 127 means one of two things:

  1. file not found: the path you're using is incorrect. double check that the program is actually in your $PATH, or in this case, the relative path is correct -- remember that the current working directory for a random terminal might not be the same for the IDE you're using. it might be better to just use an absolute path instead.
  2. ldso is not found: you're using a pre-compiled binary and it wants an interpreter that isn't on your system. maybe you're using an x86_64 (64-bit) distro, but the prebuilt is for x86 (32-bit). you can determine whether this is the answer by opening a terminal and attempting to execute it directly. or by running file -L on /bin/sh (to get your default/native format) and on the compiler itself (to see what format it is).

if the problem is (2), then you can solve it in a few diff ways:

  1. get a better binary. talk to the vendor that gave you the toolchain and ask them for one that doesn't suck.
  2. see if your distro can install the multilib set of files. most x86_64 64-bit distros allow you to install x86 32-bit libraries in parallel.
  3. build your own cross-compiler using something like crosstool-ng.
  4. you could switch between an x86_64 & x86 install, but that seems a bit drastic ;).

Align an element to bottom with flexbox

Try This

_x000D_
_x000D_
.content {_x000D_
      display: flex;_x000D_
      flex-direction: column;_x000D_
      height: 250px;_x000D_
      width: 200px;_x000D_
      border: solid;_x000D_
      word-wrap: break-word;_x000D_
    }_x000D_
_x000D_
   .content h1 , .content h2 {_x000D_
     margin-bottom: 0px;_x000D_
    }_x000D_
_x000D_
   .content p {_x000D_
     flex: 1;_x000D_
    }
_x000D_
   <div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some more or less text</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to import a SQL Server .bak file into MySQL?

In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL into MySQL is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak file which is from MsSQL and convert it into .sql format which is readable to MySQL.

Additional note: This can not only convert your .bak files but also this site is for all types of Database migrations that you want.

How do I update a Python package?

Open Command prompt or terminal and use below syntax

pip install --upgrade [package]==[specific version or latest version]

For Example

pip install --upgrade numpy==1.19.1

CMake unable to determine linker language with C++

A bit unrelated answer to OP but for people like me with a somewhat similar problem.

Use Case: Ubuntu (C, Clion, Auto-completion):

I had the same error,

CMake Error: Cannot determine link language for target "hello".

set_target_properties(hello PROPERTIES LINKER_LANGUAGE C) help fixes that problem but the headers aren't included to the project and the autocompletion wont work.

This is what i had

cmake_minimum_required(VERSION 3.5)

project(hello)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES ./)

add_executable(hello ${SOURCE_FILES})

set_target_properties(hello PROPERTIES LINKER_LANGUAGE C)

No errors but not what i needed, i realized including a single file as source will get me autocompletion as well as it will set the linker to C.

cmake_minimum_required(VERSION 3.5)

project(hello)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")

set(SOURCE_FILES ./1_helloworld.c)

add_executable(hello ${SOURCE_FILES})

Real world use of JMS/message queues?

I have used it for my academic project which was online retail website similar to Amazon. JMS was used to handle following features :

  1. Update the position of the orders placed by the customers, as the shipment travels from one location to another. This was done by continuously sending messages to JMS Queue.
  2. Alerting about any unusual events like shipment getting delayed and then sending email to customer.
  3. If the delivery is reached its destination, sending a delivery event.

We had multiple also implemented remote clients connected to main Server. If connection is available, they use to access the main database or if not use their own database. In order to handle data consistency, we had implemented 2PC mechanism. For this, we used JMS for exchange the messages between these systems i.e one acting as coordinator who will initiate the process by sending message on the queue and others will respond accordingly by sending back again a message on the queue. As others have already mentioned, this was similar to pub/sub model.

What's the difference between a word and byte?

The exact length of a word varies. What I don't understand is what's the point of having a byte? Why not say 8 bits?

Even though the length of a word varies, on all modern machines and even all older architectures that I'm familiar with, the word size is still a multiple of the byte size. So there is no particular downside to using "byte" over "8 bits" in relation to the variable word size.

Beyond that, here are some reasons to use byte (or octet1) over "8 bits":

  1. Larger units are just convenient to avoid very large or very small numbers: you might as well ask "why say 3 nanoseconds when you could say 0.000000003 seconds" or "why say 1 kilogram when you could say 1,000 grams", etc.
  2. Beyond the convenience, the unit of a byte is somehow as fundamental as 1 bit since many operations typically work not at the byte level, but at the byte level: addressing memory, allocating dynamic storage, reading from a file or socket, etc.
  3. Even if you were to adopt "8 bit" as a type of unit, so you could say "two 8-bits" instead of "two bytes", it would be often be very confusing to have your new unit start with a number. For example, if someone said "one-hundred 8-bits" it could easily be interpreted as 108 bits, rather than 100 bits.

1 Although I'll consider a byte to be 8 bits for this answer, this isn't universally true: on older machines a byte may have a different size (such as 6 bits. Octet always means 8 bits, regardless of the machine (so this term is often used in defining network protocols). In modern usage, byte is overwhelmingly used as synonymous with 8 bits.

Check if table exists without using "select from"

After reading all of the above, I prefer the following statement:

SELECT EXISTS(
       SELECT * FROM information_schema.tables 
       WHERE table_schema = 'db' 
       AND table_name = 'table'
);

It indicates exactly what you want to do and it actually returns a 'boolean'.

When to use StringBuilder in Java

Some compilers may not replace any string concatenations with StringBuilder equivalents. Be sure to consider which compilers your source will use before relying on compile time optimizations.

Downloading Java JDK on Linux via wget is shown license page instead

As already posted here: https://stackoverflow.com/a/41718895/4370196

Update for JDK 8 Update 121

Since Oracle inserted some md5hash in their download links, one cannot automatically assemble a download link for command line.

So I tinkered some nasty bash command line to get the latest jdk download link, download it and directly install via rpm. For all who are interested:

wget -q http://www.oracle.com/technetwork/java/javase/downloads/index.html -O ./index.html && grep -Eoi ']+>' index.html | grep -Eoi '/technetwork/java/javase/downloads/jdk8-downloads-[0-9]+.html' | (head -n 1) | awk '{print "http://www.oracle.com"$1}' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -O index.html -q && grep -Eoi '"filepath":"[^"]+jdk-8u[0-9]+-linux-x64.rpm"' index.html | grep -Eoi 'http:[^"]+' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -q -O ./jdk8.rpm && sudo rpm -i ./jdk8.rpm

The bold part should be replaced by the package of your liking.

Hex transparency in colors

enter image description here

This might be very late answer. But this chart kills it.

All percentage values are mapped to the hexadecimal values.

http://online.sfsu.edu/chrism/hexval.html

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

I've actually just copied the first answer here and turned it into a more ux-convenient regex which needs one upper, one lower and at least 8 chars but accepts everything "in between".

This one is an example-regex which requires

  1. at least 8 characters length
  2. at least one lowercase letter
  3. at least one uppercase letter

IMPORTANT: This regex will also except all other characters e.g. numbers, special characters like $,#,! etc. - as long as the rules 1. to 3. match the input string

^(?=.*[a-z])(?=.*[A-Z]).{8,}$

Mind the "." alomst at the end of the regex. This will match almost any (and afaik any readable) character

What is the JavaScript equivalent of var_dump or print_r in PHP?

You could also try this function. Can't remember the original author, but all credits goes to him/her.

Works like a charm - 100% the same as var_dump in PHP.

Check it out.

_x000D_
_x000D_
function dump(arr,level) {_x000D_
 var dumped_text = "";_x000D_
 if(!level) level = 0;_x000D_
_x000D_
 //The padding given at the beginning of the line._x000D_
 var level_padding = "";_x000D_
 for(var j=0;j<level+1;j++) level_padding += "    ";_x000D_
_x000D_
 if(typeof(arr) == 'object') { //Array/Hashes/Objects_x000D_
  for(var item in arr) {_x000D_
   var value = arr[item];_x000D_
_x000D_
   if(typeof(value) == 'object') { //If it is an array,_x000D_
    dumped_text += level_padding + "'" + item + "' ...\n";_x000D_
    dumped_text += dump(value,level+1);_x000D_
   } else {_x000D_
    dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";_x000D_
   }_x000D_
  }_x000D_
 } else { //Stings/Chars/Numbers etc._x000D_
  dumped_text = "===>"+arr+"<===("+typeof(arr)+")";_x000D_
 }_x000D_
 return dumped_text;_x000D_
}_x000D_
_x000D_
_x000D_
// Example:_x000D_
_x000D_
var employees = [_x000D_
    { id: '1', sex: 'm', city: 'Paris' }, _x000D_
    { id: '2', sex: 'f', city: 'London' },_x000D_
    { id: '3', sex: 'f', city: 'New York' },_x000D_
    { id: '4', sex: 'm', city: 'Moscow' },_x000D_
    { id: '5', sex: 'm', city: 'Berlin' }_x000D_
]_x000D_
_x000D_
_x000D_
// Open dev console (F12) to see results:_x000D_
_x000D_
console.log(dump(employees));
_x000D_
_x000D_
_x000D_

What do numbers using 0x notation mean?

Literals that start with 0x are hexadecimal integers. (base 16)

The number 0x6400 is 25600.

6 * 16^3 + 4 * 16^2 = 25600

For an example including letters (also used in hexadecimal notation where A = 10, B = 11 ... F = 15)

The number 0x6BF0 is 27632.

6 * 16^3 + 11 * 16^2 + 15 * 16^1 = 27632
24576    + 2816      + 240       = 27632

How can I exit from a javascript function?

Use this when if satisfies

do

return true;

Display Image On Text Link Hover CSS Only

I did something like that:

HTML:

<p class='parent'>text text text</p>
<img class='child' src='idk.png'>

CSS:

.child {
    visibility: hidden;
}

.parent:hover .child {
    visibility: visible;
}

How do I tell Maven to use the latest version of a dependency?

If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.

But as a developer, I will not recommend this type of practices. WHY?

answer to why is already given by Pascal Thivent in the comment of the question

I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.

I will recommend this type of practice:

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

it is easy to maintain and easy to debug. You can update your POM in no time.

nodeJS - How to create and read session with express

Hello I am trying to add new session values in node js like

req.session.portal = false
Passport.authenticate('facebook', (req, res, next) => {
    next()
})(req, res, next)

On passport strategies I am not getting portal value in mozilla request but working fine with chrome and opera

FacebookStrategy: new PassportFacebook.Strategy({
    clientID: Configuration.SocialChannel.Facebook.AppId,
    clientSecret: Configuration.SocialChannel.Facebook.AppSecret,
    callbackURL: Configuration.SocialChannel.Facebook.CallbackURL,
    profileFields: Configuration.SocialChannel.Facebook.Fields,
    scope: Configuration.SocialChannel.Facebook.Scope,
    passReqToCallback: true
}, (req, accessToken, refreshToken, profile, done) => {
    console.log(JSON.stringify(req.session));

How to pass List from Controller to View in MVC 3

You can use the dynamic object ViewBag to pass data from Controllers to Views.

Add the following to your controller:

ViewBag.MyList = myList;

Then you can acces it from your view:

@ViewBag.MyList

// e.g.
@foreach (var item in ViewBag.MyList) { ... }

Change event on select with knockout binding, how can I know if it is a real change?

If you are working using Knockout, use the key functionality of observable functionality knockout.
Use ko.computed() method and do and trigger ajax call within that function.

Authentication plugin 'caching_sha2_password' is not supported

To have a more permanent solution without going through your code and modifying whatever needs to be modified: Per MySQL 8 documentation, easiest way to fix this is to add the following to your MySQL d file -> restart MySQL server.

This worked for me!

If your MySQL installation must serve pre-8.0 clients and you encounter compatibility issues after upgrading to MySQL 8.0 or higher, the simplest way to address those issues and restore pre-8.0 compatibility is to reconfigure the server to revert to the previous default authentication plugin (mysql_native_password). For example, use these lines in the server option file:

[mysqld]
#add the following file to your MySQLd file
    default_authentication_plugin=mysql_native_password

How to get CSS to select ID that begins with a string (not in Javascript)?

I'd do it like this:

[id^="product"] {
  ...
}

Ideally, use a class. This is what classes are for:

<div id="product176" class="product"></div>
<div id="product177" class="product"></div>
<div id="product178" class="product"></div>

And now the selector becomes:

.product {
  ...
}

how can I enable scrollbars on the WPF Datagrid?

Adding MaxHeight and VerticalScrollBarVisibility="Auto" on the DataGrid solved my problem.

How do I install Python libraries in wheel format?

You want to install a downloaded wheel (.whl) file on Python under Windows?

  1. Install pip on your Python(s) on Windows (on Python 3.4+ it is already included)
  2. Upgrade pip if necessary (on the command line)

    pip install -U pip
    
  3. Install a local wheel file using pip (on the command line)

    pip install --no-index --find-links=LocalPathToWheelFile PackageName
    

Option --no-index tells pip to not look on pypi.python.org (which would fail for many packages if you have no compiler installed), --find-links then tells pip where to look for instead. PackageName is the name of the package (numpy, scipy, .. first part or whole of wheel file name). For more informations see the install options of pip.

You can execute these commands in the command prompt when switching to your Scripts folder of your Python installation.

Example:

cd C:\Python27\Scripts
pip install -U pip
pip install --no-index --find-links=LocalPathToWheelFile PackageName

Note: It can still be that the package does not install on Windows because it may contain C/C++ source files which need to be compiled. You would need then to make sure a compiler is installed. Often searching for alternative pre-compiled distributions is the fastest way out.

For example numpy-1.9.2+mkl-cp27-none-win_amd64.whl has PackageName numpy.

Why can't I use switch statement on a String?

For years we've been using a(n open source) preprocessor for this.

//#switch(target)
case "foo": code;
//#end

Preprocessed files are named Foo.jpp and get processed into Foo.java with an ant script.

Advantage is it is processed into Java that runs on 1.0 (although typically we only supported back to 1.4). Also it was far easier to do this (lots of string switches) compared to fudging it with enums or other workarounds - code was a lot easier to read, maintain, and understand. IIRC (can't provide statistics or technical reasoning at this point) it was also faster than the natural Java equivalents.

Disadvantages are you aren't editing Java so it's a bit more workflow (edit, process, compile/test) plus an IDE will link back to the Java which is a little convoluted (the switch becomes a series of if/else logic steps) and the switch case order is not maintained.

I wouldn't recommend it for 1.7+ but it's useful if you want to program Java that targets earlier JVMs (since Joe public rarely has the latest installed).

You can get it from SVN or browse the code online. You'll need EBuild to build it as-is.

What is the difference between String.slice and String.substring?

substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.

slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.

sample code for 'slice' in string

var str="Javascript";
console.log(str.slice(-5,-1));

output: crip

sample code for 'substring' in string

var str="Javascript";
console.log(str.substring(1,5));

output: avas

[*Note: negative indexing starts at the end of the string.]

How to split a string to 2 strings in C

If you have a char array allocated you can simply put a '\0' wherever you want. Then point a new char * pointer to the location just after the newly inserted '\0'.

This will destroy your original string though depending on where you put the '\0'

How to decorate a class?

Apart from the question whether class decorators are the right solution to your problem:

In Python 2.6 and higher, there are class decorators with the @-syntax, so you can write:

@addID
class Foo:
    pass

In older versions, you can do it another way:

class Foo:
    pass

Foo = addID(Foo)

Note however that this works the same as for function decorators, and that the decorator should return the new (or modified original) class, which is not what you're doing in the example. The addID decorator would look like this:

def addID(original_class):
    orig_init = original_class.__init__
    # Make copy of original __init__, so we can call it without recursion

    def __init__(self, id, *args, **kws):
        self.__id = id
        self.getId = getId
        orig_init(self, *args, **kws) # Call the original __init__

    original_class.__init__ = __init__ # Set the class' __init__ to the new one
    return original_class

You could then use the appropriate syntax for your Python version as described above.

But I agree with others that inheritance is better suited if you want to override __init__.

Return values from the row above to the current row

To solve this problem in Excel, usually I would just type in the literal row number of the cell above, e.g., if I'm typing in Cell A7, I would use the formula =A6. Then if I copied that formula to other cells, they would also use the row of the previous cell.

Another option is to use Indirect(), which resolves the literal statement inside to be a formula. You could use something like:

=INDIRECT("A" & ROW() - 1)

The above formula will resolve to the value of the cell in column A and the row that is one less than that of the cell which contains the formula.

How to split the filename from a full path in batch?

@echo off
Set filename="C:\Documents and Settings\All Users\Desktop\Dostips.cmd"
call :expand %filename%
:expand
set filename=%~nx1
echo The name of the file is %filename%
set folder=%~dp1
echo It's path is %folder%

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

argc is the number of command line arguments given to the program at runtime, and argv is an array of arrays of characters (rather, an array of C-strings) containing these arguments. If you know you're not going to need the command line arguments, you can declare your main at taking a void argument, instead:

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

Those are the only two prototypes defined for main as per the standards, but some compilers allow a return type of void as well. More on this on Wikipedia.

BigDecimal to string

The BigDecimal can not be a double. you can use Int number. if you want to display exactly own number, you can use the String constructor of BigDecimal .

like this:

BigDecimal bd1 = new BigDecimal("10.0001");

now, you can display bd1 as 10.0001

So simple. GOOD LUCK.

Bootstrap DatePicker, how to set the start date for tomorrow?

There is no official datepicker for bootstrap; as such, you should explicitly state which one you're using.

If you're using eternicode/bootstrap-datepicker, there's a startDate option. As discussed directly under the Options section in the README:

All options that take a "Date" can handle a Date object; a String formatted according to the given format; or a timedelta relative to today, eg '-1d', '+6m +1y', etc, where valid units are 'd' (day), 'w' (week), 'm' (month), and 'y' (year).

So you would do:

$('#datepicker').datepicker({
    startDate: '+1d'
})

How to convert Nonetype to int or string?

A common "Pythonic" way to handle this kind of situation is known as EAFP for "It's easier to ask forgiveness than permission". Which usually means writing code that assumes everything is fine, but then wrapping it with a try...except block to handle things—just in case—it's not.

Here's that coding style applied to your problem:

try:
    my_value = int(my_value)
except TypeError:
    my_value = 0  # or whatever you want to do

answer = my_value / divisor

Or perhaps the even simpler and slightly faster:

try:
    answer = int(my_value) / divisor
except TypeError:
    answer = 0

The inverse and more traditional approach is known as LBYL which stands for "Look before you leap" is what @Soviut and some of the others have suggested. For additional coverage of this topic see my answer and associated comments to the question Determine whether a key is present in a dictionary elsewhere on this site.

One potential problem with EAFP is that it can hide the fact that something is wrong with some other part of your code or third-party module you're using, especially when the exceptions frequently occur (and therefore aren't really "exceptional" cases at all).

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

There are several ways to try to prevent line breaks, and the phrase “a newer construct” might refer to more than one way—that’s actually the most reasonable interpretation. They probably mostly think of the CSS declaration white-space:nowrap and possibly the no-break space character. The different ways are not equivalent, far from that, both in theory and especially in practice, though in some given case, different ways might produce the same result.

There is probably nothing real to be gained by switching from the HTML attribute to the somewhat clumsier CSS way, and you would surely lose when style sheets are disabled. But even the nowrap attribute does no work in all situations. In general, what works most widely is the nobr markup, which has never made its way to any specifications but is alive and kicking: <td><nobr>...</nobr></td>.

How do I create an average from a Ruby array?

a = [0,4,8,2,5,0,2,6]
a.empty? ? nil : a.reduce(:+)/a.size.to_f
=> 3.375

Solves divide by zero, integer division and is easy to read. Can be easily modified if you choose to have an empty array return 0.

I like this variant too, but it's a little more wordy.

a = [0,4,8,2,5,0,2,6]
a.empty? ? nil : [a.reduce(:+), a.size.to_f].reduce(:/)
=> 3.375

MySQL: #126 - Incorrect key file for table

Every Time this has happened, it's been a full disk in my experience.

EDIT

It is also worth noting that this can be caused by a full ramdisk when doing things like altering a large table if you have a ramdisk configured. You can temporarily comment out the ramdisk line to allow such operations if you can't increase the size of it.

How to disable SSL certificate checking with Spring RestTemplate?

For the sake of other developers who finds this question and need another solution that fits not only for unit-tests:

I've found this on a blog (not my solution! Credit to the blog's owner).

TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
        .loadTrustMaterial(null, acceptingTrustStrategy)
        .build();

SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

CloseableHttpClient httpClient = HttpClients.custom()
        .setSSLSocketFactory(csf)
        .build();

HttpComponentsClientHttpRequestFactory requestFactory =
        new HttpComponentsClientHttpRequestFactory();

requestFactory.setHttpClient(httpClient);

RestTemplate restTemplate = new RestTemplate(requestFactory);

HAProxy redirecting http to https (ssl)

I don't have enough reputation to comment on a previous answer, so I'm posting a new answer to complement Jay Taylor's answer. Basically his answer will do the redirect, an implicit redirect though, meaning it will issue a 302 (temporary redirect), but since the question informs that the entire website will be served as https, then the appropriate redirect should be a 301 (permanent redirect).

redirect scheme https code 301 if !{ ssl_fc }

It seems a small change, but the impact might be huge depending on the website, with a permanent redirect we are informing the browser that it should no longer look for the http version from the start (avoiding future redirects) - a time saver for https sites. It also helps with SEO, but not dividing the juice of your links.

CSS white space at bottom of page despite having both min-height and height tag

Try setting the height of the html element to 100% as well.

html {
    min-height: 100%;
    overflow-y: scroll;
}    
body {
     min-height: 100%;
}

Reference from this answer..

How to avoid "RuntimeError: dictionary changed size during iteration" error?

The reason for the runtime error is that you cannot iterate through a data structure while its structure is changing during iteration.

One way to achieve what you are looking for is to use list to append the keys you want to remove and then use pop function on dictionary to remove the identified key while iterating through the list.

d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
pop_list = []

for i in d:
        if not d[i]:
                pop_list.append(i)

for x in pop_list:
        d.pop(x)
print (d)

Skip a submodule during a Maven build

Sure, this can be done using profiles. You can do something like the following in your parent pom.xml.

  ...
   <modules>
      <module>module1</module>
      <module>module2</module>  
      ...
  </modules>
  ...
  <profiles>
     <profile>
       <id>ci</id>
          <modules>
            <module>module1</module>
            <module>module2</module>
            ...
            <module>module-integration-test</module>
          </modules> 
      </profile>
  </profiles>
 ...

In your CI, you would run maven with the ci profile, i.e. mvn -P ci clean install

Can iterators be reset in Python?

Return a newly created iterator at the last iteration during the 'iter()' call

class ResetIter: 
  def __init__(self, num):
    self.num = num
    self.i = -1

  def __iter__(self):
    if self.i == self.num-1: # here, return the new object
      return self.__class__(self.num) 
    return self

  def __next__(self):
    if self.i == self.num-1:
      raise StopIteration

    if self.i <= self.num-1:
      self.i += 1
      return self.i


reset_iter = ResetRange(10)
for i in reset_iter:
  print(i, end=' ')
print()

for i in reset_iter:
  print(i, end=' ')
print()

for i in reset_iter:
  print(i, end=' ')

Output:

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

Where are Magento's log files located?

To create your custom log file, try this code

Mage::log('your debug message', null, 'yourlog_filename.log');

Refer this Answer

Open terminal here in Mac OS finder

This:

https://github.com/jbtule/cdto#cd-to

It's a small app that you drag into the Finder toolbar, the icon fits in very nicely. It works with Terminal, xterm (under X11), iterm.

How to check if std::map contains a key without doing insert?

Potatoswatter's answer is all right, but I prefer to use find or lower_bound instead. lower_bound is especially useful because the iterator returned can subsequently be used for a hinted insertion, should you wish to insert something with the same key.

map<K, V>::iterator iter(my_map.lower_bound(key));
if (iter == my_map.end() || key < iter->first) {    // not found
    // ...
    my_map.insert(iter, make_pair(key, value));     // hinted insertion
} else {
    // ... use iter->second here
}

SVN icon overlays not showing properly

To fix this go to TortoiseSVN > settings > Icon Overlays > Status cache changed from default to shell.

If the drive A or B is used check the Drive type as A and B.

Array.push() and unique items

In case if you are looking for one liner

For primitives

this.items.indexOf(item) === -1) && this.items.push(item);

For objects

this.items.findIndex((item: ItemType) => item.var === checkValue) === -1 && this.items.push(item);

How do I rename both a Git local and remote branch name?

  • Rename your local branch.

If you are on the branch you want to rename:

git branch -m new-name

if you stay on a different branch at the current time:

git branch -m old-name new-name
  • Delete the old-name remote branch and push the new-name local branch.

Stay on the target branch and:

git push origin :old-name new-name
  • Reset the upstream branch for the new-name local branch.

Switch to the target branch and then:

git push origin -u new-name

Get parent of current directory from Python script

You can simply use../your_script_name.py For example suppose the path to your python script is trading system/trading strategies/ts1.py. To refer to volume.csv located in trading system/data/. You simply need to refer to it as ../data/volume.csv

Copy table without copying data

SHOW CREATE TABLE bar;

you will get a create statement for that table, edit the table name, or anything else you like, and then execute it.

This will allow you to copy the indexes and also manually tweak the table creation.

You can also run the query within a program.

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

How to grep a text file which contains some binary data?

You can force grep to look at binary files with:

grep --binary-files=text

You might also want to add -o (--only-matching) so you don't get tons of binary gibberish that will bork your terminal.

jQuery UI Tabs - How to Get Currently Selected Tab Index

Another way to get the selected tab index is:

var index = jQuery('#tabs').data('tabs').options.selected;

How can I create a UIColor from a hex string?

Another implementation allowing strings like "FFF" or "FFFFFF" and using alpha:

+ (UIColor *) colorFromHexString:(NSString *)hexString alpha: (CGFloat)alpha{
    NSString *cleanString = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    if([cleanString length] == 3) {
        cleanString = [NSString stringWithFormat:@"%@%@%@%@%@%@",
                       [cleanString substringWithRange:NSMakeRange(0, 1)],[cleanString substringWithRange:NSMakeRange(0, 1)],
                       [cleanString substringWithRange:NSMakeRange(1, 1)],[cleanString substringWithRange:NSMakeRange(1, 1)],
                       [cleanString substringWithRange:NSMakeRange(2, 1)],[cleanString substringWithRange:NSMakeRange(2, 1)]];
    }
    if([cleanString length] == 6) {
        cleanString = [cleanString stringByAppendingString:@"ff"];
    }

    unsigned int baseValue;
    [[NSScanner scannerWithString:cleanString] scanHexInt:&baseValue];

    float red = ((baseValue >> 24) & 0xFF)/255.0f;
    float green = ((baseValue >> 16) & 0xFF)/255.0f;
    float blue = ((baseValue >> 8) & 0xFF)/255.0f;

    return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
}

Set value of hidden input with jquery

You don't need to set name , just giving an id is enough.

<input type="hidden" id="testId" />

and than with jquery you can use 'val()' method like below:

 $('#testId').val("work");

Python: avoiding pylint warnings about too many arguments

Perhaps you could turn some of the arguments into member variables. If you need that much state a class sounds like a good idea to me.

Installing NumPy and SciPy on 64-bit Windows (with Pip)

You can download the needed packages from here and use pip install "Abc.whl" from the directory where you have downloaded the file.

Select SQL Server database size

If you want to simply check single database size, you can do it using SSMS Gui

Go to Server Explorer -> Expand it -> Right click on Database -> Choose Properties -> In popup window choose General tab ->See Size

Source: Check database size in Sql server ( Various Ways explained)

Node.js: How to send headers with form data using request module?

Just remember set method to POST in options. Here is my code

var options = {
    url: 'http://www.example.com',
    method: 'POST', // Don't forget this line
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-MicrosoftAjax': 'Delta=true', // blah, blah, blah...
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36',
    },
    form: {
        'key-1':'value-1',
        'key-2':'value-2',
        ...
    }
};

//console.log('options:', options);

// Create request to get data
request(options, (err, response, body) => {
    if (err) {
        //console.log(err);
    } else {
        console.log('body:', body);
    }
});

How does Subquery in select statement work in oracle

It's simple-

SELECT empname,
       empid,
       (SELECT COUNT (profileid)
          FROM profile
         WHERE profile.empid = employee.empid)
           AS number_of_profiles
  FROM employee;

It is even simpler when you use a table join like this:

  SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
    FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;

Explanation for the subquery:

Essentially, a subquery in a select gets a scalar value and passes it to the main query. A subquery in select is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null to the main query. Moreover, a subquery can access columns from the from clause of the main query, as shown in my query where employee.empid is passed from the outer query to the inner query.


Edit:

When you use a subquery in a select clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.


Explanation for the left join

A left join is very handy, especially when you want to replace the select subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN keyword.

For more information read Oracle Docs on subqueries and left join or left outer join.

Can't specify the 'async' modifier on the 'Main' method of a console app

In C# 7.1 you will be able to do a proper async Main. The appropriate signatures for Main method has been extended to:

public static Task Main();
public static Task<int> Main();
public static Task Main(string[] args);
public static Task<int> Main(string[] args);

For e.g. you could be doing:

static async Task Main(string[] args)
{
    Bootstrapper bs = new Bootstrapper();
    var list = await bs.GetList();
}

At compile time, the async entry point method will be translated to call GetAwaitor().GetResult().

Details: https://blogs.msdn.microsoft.com/mazhou/2017/05/30/c-7-series-part-2-async-main

EDIT:

To enable C# 7.1 language features, you need to right-click on the project and click "Properties" then go to the "Build" tab. There, click the advanced button at the bottom:

enter image description here

From the language version drop-down menu, select "7.1" (or any higher value):

enter image description here

The default is "latest major version" which would evaluate (at the time of this writing) to C# 7.0, which does not support async main in console apps.

Bootstrap 3: Text overlay on image

You need to set the thumbnail class to position relative then the post-content to absolute.

Check this fiddle

.post-content {
    top:0;
    left:0;
    position: absolute;
}

.thumbnail{
    position:relative;

}

Giving it top and left 0 will make it appear in the top left corner.

What is difference between INNER join and OUTER join

Inner join matches tables on keys, but outer join matches keys just for one side. For example when you use left outer join the query brings the whole left side table and matches the right side to the left table primary key and where there is not matched places null.

dlib installation on Windows 10

If you're trying to install dlib on Windows 10 with Visual Studio 2019, then first perform:

pip install cmake

And set it in the environment variable. After that, make sure that you have the latest version of Visual Studio SDK installed. After that, perform:

pip install dlib

I hope this solves the problem

javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25

I was also facing the same error. The reason for this is that there is no smtp server on your environment. For creating a fake smtp server I used this fake-smtp.jar file for creating a virtual server and listening to all the requests. If you are facing the same error, I recommend you to use this jar and run it after extracting and then try to run your application.

Download latest version of fake smtp

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

mysqld --initialize to initialize the data directory then mysqld &

If you had already launched mysqld& without mysqld --initialize you might have to delete all files in your data directory

You can also modify /etc/my.cnf to add a custom path to your data directory like this :

[mysqld]
...  
datadir=/path/to/directory

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

it can also be in your capistrano config (Capfile):

set :rbenv_ruby, "2.7.1"

How do I see what character set a MySQL database / table / column is?

For all the databases you have on the server:

mysql> SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA;

Output:

+----------------------------+---------+--------------------+
| database                   | charset | collation          |
+----------------------------+---------+--------------------+
| information_schema         | utf8    | utf8_general_ci    |
| my_database                | latin1  | latin1_swedish_ci  |
...
+----------------------------+---------+--------------------+

For a single Database:

mysql> USE my_database;
mysql> show variables like "character_set_database";

Output:

    +----------------------------+---------+
    | Variable_name              |  Value  |
    +----------------------------+---------+
    | character_set_database     |  latin1 | 
    +----------------------------+---------+

Getting the collation for Tables:

mysql> USE my_database;
mysql> SHOW TABLE STATUS WHERE NAME LIKE 'my_tablename';

OR - will output the complete SQL for create table:

mysql> show create table my_tablename


Getting the collation of columns:

mysql> SHOW FULL COLUMNS FROM my_tablename;

output:

+---------+--------------+--------------------+ ....
| field   | type         | collation          |
+---------+--------------+--------------------+ ....
| id      | int(10)      | (NULL)             |
| key     | varchar(255) | latin1_swedish_ci  |
| value   | varchar(255) | latin1_swedish_ci  |
+---------+--------------+--------------------+ ....

Run task only if host does not belong to a group

You can set a control variable in vars files located in group_vars/ or directly in hosts file like this:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2

And run tasks like this:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

How to solve "The directory is not empty" error when running rmdir command in a batch script?

I had "C:\Users\User Name\OneDrive\Fonts", which was mklink'ed ( /D ) to "C:\Windows\Fonts", and I got the same problem. In my case

cd "C:\Users\User Name\OneDrive"

rd /s Fonts

Y (to confirm the action)

helped me. I hope, that it helps you too ;D

Bootstrap 3 truncate long text inside rows of a table in a responsive way

This is what I achieved, but had to set width, and it cannot be percentual.

_x000D_
_x000D_
.trunc{_x000D_
  width:250px; _x000D_
  white-space: nowrap; _x000D_
  overflow: hidden; _x000D_
  text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
      _x000D_
      <tr>_x000D_
        <td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
      <td>_x000D_
         <div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
         </div>_x000D_
    </td>_x000D_
        </tr>_x000D_
      </table>
_x000D_
_x000D_
_x000D_

or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/

print variable and a string in python

All answers above are correct, However People who are coming from other programming language. The easiest approach to follow will be.

variable = 1

print("length " + format(variable))

Differences between utf8 and latin1

In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).

How to render pdfs using C#

PdfiumViewer is great, but relatively tightly coupled to System.Drawingand WinForms. For this reason I created my own wrapper around PDFium: PDFiumSharp

Pages can be rendered to a PDFiumBitmap which in turn can be saved to disk or exposed as a stream. This way any framework capable of loading an image in BMP format from a stream can use this library to display pdf pages.

For example in a WPF application you could use the following method to render a pdf page:

using System.Linq;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using PDFiumSharp;

static class PdfRenderer
{
    public static ImageSource RenderPage(string filename, int pageIndex, string password = null, bool withTransparency = true)
    {
        using (var doc = new PdfDocument(filename, password))
        {
            var page = doc.Pages[pageIndex];
            using (var bitmap = new PDFiumBitmap((int)page.Width, (int)page.Height, withTransparency))
            {
                page.Render(bitmap);
                return new BmpBitmapDecoder(bitmap.AsBmpStream(), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
            }
        }
    }
}

Print current call stack from a method in Python code

Install Inspect-it

pip3 install inspect-it --user

Code

import inspect;print(*['\n\x1b[0;36;1m| \x1b[0;32;1m{:25}\x1b[0;36;1m| \x1b[0;35;1m{}'.format(str(x.function), x.filename+'\x1b[0;31;1m:'+str(x.lineno)+'\x1b[0m') for x in inspect.stack()])

you can Make a snippet of this line

it will show you a list of the function call stack with a filename and line number

list from start to where you put this line

Load HTML File Contents to Div [without the use of iframes]

I'd suggest getting into one of the JS libraries out there. They ensure compatibility so you can get up and running really fast. jQuery and DOJO are both really great. To do what you're trying to do in jQuery, for example, it would go something like this:

<script type="text/javascript" language="JavaScript">
$.ajax({
    url: "x.html", 
    context: document.body,
    success: function(response) {
        $("#yourDiv").html(response);
    }
});
</script>

PowerShell and the -contains operator

-Contains is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.

-match and -imatch are regular expression string matchers, and set automatic variables to use with captures.

-like, -ilike are SQL-like matchers.

Jquery show/hide table rows

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
  <tr class="black">
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
  </tr>
</thead>
<tbody>
  <tr id="white">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
  <tr class="black" style="background-color:black;">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
   $("#black_only").click(function(){
    $("#white").hide();
    $(".black").show();

   });
   $("#white_only").click(function(){
    $(".black").hide();
    $("#white").show();

   });
   $("#all").click(function(){
    $("#white").show();
    $(".black").show();

   });

});
</script>

Using both Python 2.x and Python 3.x in IPython Notebook

From my Linux installation I did:

sudo ipython2 kernelspec install-self

And now my python 2 is back on the list.

Reference:

http://ipython.readthedocs.org/en/latest/install/kernel_install.html


UPDATE:

The method above is now deprecated and will be dropped in the future. The new method should be:

sudo ipython2 kernel install

How to replace negative numbers in Pandas Data Frame by zero

Perhaps you could use pandas.where(args) like so:

data_frame = data_frame.where(data_frame < 0, 0)

jQuery select option elements by value

function select_option(index)
{
    var optwewant;
    for (opts in $('#span_id').children('select'))
    {
        if (opts.value() = index)
        {
            optwewant = opts;
            break;
        }
    }
    alert (optwewant);
}

Why is my CSS style not being applied?

I had a similar problem which was caused by a simple mistake in CSS comments.

I had written a comment using the JavaScript // way instead of /* */ which made the subsequent css-class to break but all other CSS work as expected.

How can I keep my branch up to date with master with git?

If your branch is local only and hasn't been pushed to the server, use

git rebase master

Otherwise, use

git merge master

Removing rounded corners from a <select> element in Chrome/Webkit

Eliminating the arrows should be avoided. A solution that preserves the dropdown arrows is to first remove styles from the dropdown:

.myDropdown {
  background-color: #yourbg;
  border-style: none;
}

Then create div directly before the dropdown in your HTML:

<div class="myDiv"></div>
<select class="myDropdown...">...</select>

And style the div like this:

.myDiv {
  background-color: #yourbg;
  border-style: none;
  position: absolute;
  display: inline;
  border: 1px solid #acolor;
}

Display inline will keep the div from going to a new line, position absolute removes it from the flow of the page. The end result is a nice clean underline you can style as you'd like, and your dropdown still behaves as the user would expect.

Get all rows from SQLite

I have been looking into the same problem! I think your problem is related to where you identify the variable that you use to populate the ArrayList that you return. If you define it inside the loop, then it will always reference the last row in the table in the database. In order to avoid this, you have to identify it outside the loop:

String name;
if (cursor.moveToFirst()) {

        while (cursor.isAfterLast() == false) {
            name = cursor.getString(cursor
                    .getColumnIndex(countyname));

            list.add(name);
            cursor.moveToNext();
        }
}

Daemon not running. Starting it now on port 5037

Reference link: http://www.programering.com/a/MTNyUDMwATA.html

Steps I followed 1) Execute the command adb nodaemon server in command prompt Output at command prompt will be: The following error occurred cannot bind 'tcp:5037' The original ADB server port binding failed

2) Enter the following command query which using port 5037 netstat -ano | findstr "5037" The following information will be prompted on command prompt: TCP 127.0.0.1:5037 0.0.0.0:0 LISTENING 9288

3) View the task manager, close all adb.exe

4) Restart eclipse or other IDE

The above steps worked for me.

"Could not find a version that satisfies the requirement opencv-python"

We were getting the same error.For us, it solved by upgrading pip version (also discussed in FAQ of OpenCV GitHub). Earlier we had pip-7.1.0, post upgrading it to "pip-9.0.2", it successfully installed.

pip install --upgrade pip
pip install opencv-python

How can I require at least one checkbox be checked before a form can be submitted?

This should have what you need, check out the jsfiddle at the bottom:

$(document).ready(function () {
$('#txt').val($("input[type=checkbox]:checked").length);
$('#txt2').val($("input[type=checkbox]").length);

$('input[type=checkbox]').change(function () {
checked = $("input[type=checkbox]:checked").length;
$('#block').show();
$('#block2').hide();
if (checked > 0) {
  $('#block').hide();
  $('#block2').show();
  $('#txt').val(checked);
 }
});
});

How to iterate over rows in a DataFrame in Pandas

You can also use df.apply() to iterate over rows and access multiple columns for a function.

docs: DataFrame.apply()

def valuation_formula(x, y):
    return x * y * 0.5

df['price'] = df.apply(lambda row: valuation_formula(row['x'], row['y']), axis=1)

Difference between Spring MVC and Struts MVC

Spring's Web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that you can choose an appropriate base class: if you don't have a form, you don't need a form controller. This is a major difference to Struts

How to autosize a textarea using Prototype?

Just revisiting this, I've made it a little bit tidier (though someone who is full bottle on Prototype/JavaScript could suggest improvements?).

var TextAreaResize = Class.create();
TextAreaResize.prototype = {
  initialize: function(element, options) {
    element = $(element);
    this.element = element;

    this.options = Object.extend(
      {},
      options || {});

    Event.observe(this.element, 'keyup',
      this.onKeyUp.bindAsEventListener(this));
    this.onKeyUp();
  },

  onKeyUp: function() {
    // We need this variable because "this" changes in the scope of the
    // function below.
    var cols = this.element.cols;

    var linecount = 0;
    $A(this.element.value.split("\n")).each(function(l) {
      // We take long lines into account via the cols divide.
      linecount += 1 + Math.floor(l.length / cols);
    })

    this.element.rows = linecount;
  }
}

Just it call with:

new TextAreaResize('textarea_id_name_here');

setting global sql_mode in mysql

BTW, if you set globals in MySQL:

SET GLOBAL sql_mode = 'NO_ENGINE_SUBSTITUTION';
SET SESSION sql_mode = 'NO_ENGINE_SUBSTITUTION';

This will not set it PERMANENTLY, and it will revert after every restart.

So you should set this in your config file (e.g. /etc/mysql/my.cnf in the [mysqld] section), so that the changes remain in effect after MySQL restart:

Config File: /etc/mysql/my.cnf

[mysqld] 
sql_mode = NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

UPDATE: Newer versions of Mysql (e.g. 5.7.8 or above) may require slightly different syntax:

[mysqld]
sql-mode="STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION"

Make sure that there is a dash between sql-mode not an underscore, and that modes are in double quotes.

Always reference the MySQL Docs for your version to see the sql-mode options.

jQuery autohide element after 5 seconds

jQuery(".success_mgs").show(); setTimeout(function(){ jQuery(".success_mgs").hide();},5000);

In Python How can I declare a Dynamic Array

Here's a great method I recently found on a different stack overflow post regarding multi-dimensional arrays, but the answer works beautifully for single dimensional arrays as well:

# Create an 8 x 5 matrix of 0's:
w, h = 8, 5;
MyMatrix = [ [0 for x in range( w )] for y in range( h ) ]  

# Create an array of objects:
MyList = [ {} for x in range( n ) ]

I love this because you can specify the contents and size dynamically, in one line!

One more for the road:

# Dynamic content initialization:
MyFunkyArray = [ x * a + b for x in range ( n ) ]

Mercurial: how to amend the last commit?

Another solution could be use the uncommit command to exclude specific file from current commit.

hg uncommit [file/directory]

This is very helpful when you want to keep current commit and deselect some files from commit (especially helpful for files/directories have been deleted).

How do I get a list of files in a directory in C++?

If you're in Windows & using MSVC, the MSDN library has sample code that does this.

And here's the code from that link:

#include <windows.h>
#include <tchar.h> 
#include <stdio.h>
#include <strsafe.h>

void ErrorHandler(LPTSTR lpszFunction);

int _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA ffd;
   LARGE_INTEGER filesize;
   TCHAR szDir[MAX_PATH];
   size_t length_of_arg;
   HANDLE hFind = INVALID_HANDLE_VALUE;
   DWORD dwError=0;

   // If the directory is not specified as a command-line argument,
   // print usage.

   if(argc != 2)
   {
      _tprintf(TEXT("\nUsage: %s <directory name>\n"), argv[0]);
      return (-1);
   }

   // Check that the input path plus 2 is not longer than MAX_PATH.

   StringCchLength(argv[1], MAX_PATH, &length_of_arg);

   if (length_of_arg > (MAX_PATH - 2))
   {
      _tprintf(TEXT("\nDirectory path is too long.\n"));
      return (-1);
   }

   _tprintf(TEXT("\nTarget directory is %s\n\n"), argv[1]);

   // Prepare string for use with FindFile functions.  First, copy the
   // string to a buffer, then append '\*' to the directory name.

   StringCchCopy(szDir, MAX_PATH, argv[1]);
   StringCchCat(szDir, MAX_PATH, TEXT("\\*"));

   // Find the first file in the directory.

   hFind = FindFirstFile(szDir, &ffd);

   if (INVALID_HANDLE_VALUE == hFind) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
      return dwError;
   } 

   // List all the files in the directory with some info about them.

   do
   {
      if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
      {
         _tprintf(TEXT("  %s   <DIR>\n"), ffd.cFileName);
      }
      else
      {
         filesize.LowPart = ffd.nFileSizeLow;
         filesize.HighPart = ffd.nFileSizeHigh;
         _tprintf(TEXT("  %s   %ld bytes\n"), ffd.cFileName, filesize.QuadPart);
      }
   }
   while (FindNextFile(hFind, &ffd) != 0);

   dwError = GetLastError();
   if (dwError != ERROR_NO_MORE_FILES) 
   {
      ErrorHandler(TEXT("FindFirstFile"));
   }

   FindClose(hFind);
   return dwError;
}


void ErrorHandler(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
}

HttpServletRequest - how to obtain the referring URL?

The URLs are passed in the request: request.getRequestURL().

If you mean other sites that are linking to you? You want to capture the HTTP Referrer, which you can do by calling:

request.getHeader("referer");

Set transparent background of an imageview on Android

In case you want it in code, just:

mComponentName.setBackgroundColor(Color.parseColor("#80000000"));

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

MIME types missing in IIS 7 for ASP.NET - 404.17

Fix:

I chose the "ISAPI & CGI Restrictions" after clicking the server name (not the site name) in IIS Manager, and right clicked the "ASP.NET v4.0.30319" lines and chose "Allow".

After turning on ASP.NET from "Programs and Features > Turn Windows features on or off", you must install ASP.NET from the Windows command prompt. The MIME types don't ever show up, but after doing this command, I noticed these extensions showed up under the IIS web site "Handler Mappings" section of IIS Manager.

C:\>cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>dir aspnet_reg*
 Volume in drive C is Windows
 Volume Serial Number is 8EE6-5DD0

 Directory of C:\Windows\Microsoft.NET\Framework64\v4.0.30319

03/18/2010  08:23 PM            19,296 aspnet_regbrowsers.exe
03/18/2010  08:23 PM            36,696 aspnet_regiis.exe
03/18/2010  08:23 PM           102,232 aspnet_regsql.exe
               3 File(s)        158,224 bytes
               0 Dir(s)  34,836,508,672 bytes free

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i
Start installing ASP.NET (4.0.30319).
.....
Finished installing ASP.NET (4.0.30319).

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>

However, I still got this error. But if you do what I mentioned for the "Fix", this will go away.

HTTP Error 404.2 - Not Found
The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server.

How to convert ISO8859-15 to UTF8?

Iconv just writes the converted text to stdout. You have to use -o OUTPUTFILE.txt as an parameter or write stdout to a file. (iconv -f x -t z filename.txt > OUTPUTFILE.txt or iconv -f x -t z < filename.txt > OUTPUTFILE.txt in some iconv versions)

Synopsis

iconv -f encoding -t encoding inputfile

Description

The iconv program converts the encoding of characters in inputfile from one coded character set to another. 
**The result is written to standard output unless otherwise specified by the --output option.**

--from-code, -f encoding

Convert characters from encoding

--to-code, -t encoding

Convert characters to encoding

--list

List known coded character sets

--output, -o file

Specify output file (instead of stdout)

--verbose

Print progress information.

JavaScript unit test tools for TDD

Take a look at the Dojo Object Harness (DOH) unit test framework which is pretty much framework independent harness for JavaScript unit testing and doesn't have any Dojo dependencies. There is a very good description of it at Unit testing Web 2.0 applications using the Dojo Objective Harness.

If you want to automate the UI testing (a sore point of many developers) — check out doh.robot (temporary down. update: other link http://dojotoolkit.org/reference-guide/util/dohrobot.html ) and dijit.robotx (temporary down). The latter is designed for an acceptance testing. Update:

Referenced articles explain how to use them, how to emulate a user interacting with your UI using mouse and/or keyboard, and how to record a testing session, so you can "play" it later automatically.

How to add a boolean datatype column to an existing table in sql?

Below query worked for me with default value false;

ALTER TABLE cti_contract_account ADD ready_to_audit BIT DEFAULT 0 NOT NULL;

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Can an ASP.NET MVC controller return an Image?

This might be helpful if you'd like to modify the image before returning it:

public ActionResult GetModifiedImage()
{
    Image image = Image.FromFile(Path.Combine(Server.MapPath("/Content/images"), "image.png"));

    using (Graphics g = Graphics.FromImage(image))
    {
        // do something with the Graphics (eg. write "Hello World!")
        string text = "Hello World!";

        // Create font and brush.
        Font drawFont = new Font("Arial", 10);
        SolidBrush drawBrush = new SolidBrush(Color.Black);

        // Create point for upper-left corner of drawing.
        PointF stringPoint = new PointF(0, 0);

        g.DrawString(text, drawFont, drawBrush, stringPoint);
    }

    MemoryStream ms = new MemoryStream();

    image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

    return File(ms.ToArray(), "image/png");
}

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

Calculating Page Load Time In JavaScript

Why so complicated? When you can do:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

If you need more times check out the window.performance object:

console.log(window.performance);

Will show you the timing object:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info

How to get a view table query (code) in SQL Server 2008 Management Studio

Additionally, if you have restricted access to the database (IE: Can't use "Script Function as > CREATE To"), there is another option to get this query.

Find your View > right click > "Design".

This will give you the query you are looking for.

Check if a temporary table exists and delete if it exists before creating a temporary table

The statement should be of the order

  1. Alter statement for the table
  2. GO
  3. Select statement.

Without 'GO' in between, the whole thing will be considered as one single script and when the select statement looks for the column,it won't be found.

With 'GO' , it will consider the part of the script up to 'GO' as one single batch and will execute before getting into the query after 'GO'.

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

Remove the first / in the path. Also you don't need type="text/javascript" anymore in HTML5.

jquery how to get the page's current screen top position?

var top = $('html').offset().top;

should do it.

edit: this is the negative of $(document).scrollTop()

In OS X Lion, LANG is not set to UTF-8, how to fix it?

I recently had the same issue on OS X Sierra with bash shell, and thanks to answers above I only had to edit the file

~/.bash_profile 

and append those lines

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

How to print like printf in Python3?

In Python2, print was a keyword which introduced a statement:

print "Hi"

In Python3, print is a function which may be invoked:

print ("Hi")

In both versions, % is an operator which requires a string on the left-hand side and a value or a tuple of values or a mapping object (like dict) on the right-hand side.

So, your line ought to look like this:

print("a=%d,b=%d" % (f(x,n),g(x,n)))

Also, the recommendation for Python3 and newer is to use {}-style formatting instead of %-style formatting:

print('a={:d}, b={:d}'.format(f(x,n),g(x,n)))

Python 3.6 introduces yet another string-formatting paradigm: f-strings.

print(f'a={f(x,n):d}, b={g(x,n):d}')

How to create a function in SQL Server

I can give a small hack, you can use T-SQL function. Try this:

SELECT ID, PARSENAME(WebsiteName, 2)
FROM dbo.YourTable .....

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

How to best display in Terminal a MySQL SELECT returning too many fields?

You might also find this useful (non-Windows only):

mysql> pager less -SFX
mysql> SELECT * FROM sometable;

This will pipe the outut through the less command line tool which - with these parameters - will give you a tabular output that can be scrolled horizontally and vertically with the cursor keys.

Leave this view by hitting the q key, which will quit the less tool.

Determine a string's encoding in C#

The SimpleHelpers.FileEncoding Nuget package wraps a C# port of the Mozilla Universal Charset Detector into a dead-simple API:

var encoding = FileEncoding.DetectFileEncoding(txtFile);

The remote certificate is invalid according to the validation procedure

.NET is seeing an invalid SSL certificate on the other end of the connection. There is a workaround for it, but obviously not recommended for production code:

// Put this somewhere that is only once - like an initialization method
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateCertificate);
...

static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
   return true;
}

Set default format of datetimepicker as dd-MM-yyyy

Ammending as "optional Answer". If you don't need to programmatically solve the problem, here goes the "visual way" in VS2012.

In Visual Studio, you can set custom format directly from the properties Panel: enter image description here

First Set the "Format" property to: "Custom"; Secondly, set your custom format to: "dd-MM-yyyy";

How to calculate the 95% confidence interval for the slope in a linear regression model in R

Let's fit the model:

> library(ISwR)
> fit <- lm(metabolic.rate ~ body.weight, rmr)
> summary(fit)

Call:
lm(formula = metabolic.rate ~ body.weight, data = rmr)

Residuals:
    Min      1Q  Median      3Q     Max 
-245.74 -113.99  -32.05  104.96  484.81 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept) 811.2267    76.9755  10.539 2.29e-13 ***
body.weight   7.0595     0.9776   7.221 7.03e-09 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 

Residual standard error: 157.9 on 42 degrees of freedom
Multiple R-squared: 0.5539, Adjusted R-squared: 0.5433 
F-statistic: 52.15 on 1 and 42 DF,  p-value: 7.025e-09 

The 95% confidence interval for the slope is the estimated coefficient (7.0595) ± two standard errors (0.9776).

This can be computed using confint:

> confint(fit, 'body.weight', level=0.95)
               2.5 % 97.5 %
body.weight 5.086656 9.0324

How can I convert ticks to a date format?

A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:

DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

Remove Sub String by using Python

BeautifulSoup(text, features="html.parser").text 

For the people who were seeking deep info in my answer, sorry.

I'll explain it.

Beautifulsoup is a widely use python package that helps the user (developer) to interact with HTML within python.

The above like just take all the HTML text (text) and cast it to Beautifulsoup object - that means behind the sense its parses everything up (Every HTML tag within the given text)

Once done so, we just request all the text from within the HTML object.

How do you replace all the occurrences of a certain character in a string?

I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.

def remove_chars(line):
    line7=line[7].translate(None,'abcd')
    return line[:7]+[line7]+line[8:]

line= ['ad','da','sdf','asd',
        '3424','342sfas','asdfaf','sdfa',
        'afase']
print line[7]
line = remove_chars(line)
print line[7]

Getting hold of the outer class object from the inner class object

Here's the example:

// Test
public void foo() {
    C c = new C();
    A s;
    s = ((A.B)c).get();
    System.out.println(s.getR());
}

// classes
class C {}

class A {
   public class B extends C{
     A get() {return A.this;}
   }
   public String getR() {
     return "This is string";
   }
}

Get google map link with latitude/longitude

I've tried doing the request you need using an iframe to show the result for latitude, longitude, and zoom needed:

<iframe 
  width="300" 
  height="170" 
  frameborder="0" 
  scrolling="no" 
  marginheight="0" 
  marginwidth="0" 
  src="https://maps.google.com/maps?q='+YOUR_LAT+','+YOUR_LON+'&hl=es&z=14&amp;output=embed"
 >
 </iframe>
 <br />
 <small>
   <a 
    href="https://maps.google.com/maps?q='+data.lat+','+data.lon+'&hl=es;z=14&amp;output=embed" 
    style="color:#0000FF;text-align:left" 
    target="_blank"
   >
     See map bigger
   </a>
 </small>

How can I specify system properties in Tomcat configuration on startup?

(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).

You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:

http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.

Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:

<env-entry>
    <env-entry-name>SMTP_PASSWORD</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>abc123ftw</env-entry-value>
</env-entry>

Difference between modes a, a+, w, w+, and r+ in built-in open function?

The options are the same as for the fopen function in the C standard library:

w truncates the file, overwriting whatever was already there

a appends to the file, adding onto whatever was already there

w+ opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file

a+ opens for appending and reading, allowing you both to append to the file and also read its contents

Get index of a row of a pandas dataframe as an integer

The nature of wanting to include the row where A == 5 and all rows upto but not including the row where A == 8 means we will end up using iloc (loc includes both ends of slice).

In order to get the index labels we use idxmax. This will return the first position of the maximum value. I run this on a boolean series where A == 5 (then when A == 8) which returns the index value of when A == 5 first happens (same thing for A == 8).

Then I use searchsorted to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc.

i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]

enter image description here


numpy

you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.

def find_between(df, col, v1, v2):
    vals = df[col].values
    mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
    idx = df.index.values
    i1, i2 = idx.searchsorted([mx1, mx2])
    return df.iloc[i1:i2]

find_between(df, 'A', 5, 8)

enter image description here


timing
enter image description here

PostgreSQL: Why psql can't connect to server?

I had the similar issue and the problem was in the config file pg_hba.conf. I had earlier made some changes which was causing the server to error out while trying to start it. Commenting out the extra additions solved the problem.

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Build error, This project references NuGet

This problem appeared for me when I was creating folders in the filesystem (not in my solution) and moved some projects around.

Turns out that the package paths are relative from the csproj files. So I had to change the "HintPath" of my references:

<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
    <HintPath>..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
    <Private>True</Private>
</Reference>

To:

<Reference Include="EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
    <HintPath>..\..\packages\EntityFramework.6.1.3\lib\net45\EntityFramework.dll</HintPath>
    <Private>True</Private>
</Reference>

Notice the double "..\" in 'HintPath'.

I also had to change my error conditions, for example I had to change:

<Error Condition="!Exists('..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />

To:

<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.1.1\build\Microsoft.Net.Compilers.props'))" />

Again, notice the double "..\".

How to remove the hash from window.location (URL) with JavaScript without page refresh?

How about the following?

window.location.hash=' '

Please note that am setting the hash to a single space and not an empty string.


Setting the hash to an invalid anchor does not cause a refresh either. Such as,

window.location.hash='invalidtag'

But, I find above solution to be misleading. This seems to indicate that there is an anchor on the given position with the given name although there isn't one. At the same time, using an empty string causes page to move to the top which can be unacceptable at times. Using a space also ensures that whenever the URL is copied and bookmarked and visited again, the page will usually be at the top and the space will be ignored.

And, hey, this is my first answer on StackOverflow. Hope someone finds it useful and it matches the community standards.

How to view the roles and permissions granted to any database user in Azure SQL server instance?

if you want to find about object name e.g. table name and stored procedure on which particular user has permission, use the following query:

SELECT pr.principal_id, pr.name, pr.type_desc, 
    pr.authentication_type_desc, pe.state_desc, pe.permission_name, OBJECT_NAME(major_id) objectName
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe ON pe.grantee_principal_id = pr.principal_id
--INNER JOIN sys.schemas AS s ON s.principal_id =  sys.database_role_members.role_principal_id 
     where pr.name in ('youruser1','youruser2') 

How to get a path to a resource in a Java JAR file

In my case, I have used a URL object instead Path.

File

File file = new File("my_path");
URL url = file.toURI().toURL();

Resource in classpath using classloader

URL url = MyClass.class.getClassLoader().getResource("resource_name")

When I need to read the content, I can use the following code:

InputStream stream = url.openStream();

And you can access the content using an InputStream.

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(datetime, '23/07/2009', 103)

How to add Tomcat Server in eclipse

Do as this:

Windows -> Show View -> Servers

Then in the Servers view, right-click and add new. It will show a pop up containing many server vendors. Under Apache select Tomcat v7.0 (Depending upon your downloaded server version). And in the run time configuration point it to the Tomcat folder you have downloaded.

You can try this article. It has the info you want !!

Python 3 string.join() equivalent?

'.'.join() or ".".join().. So any string instance has the method join()

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Angular.js programmatically setting a form field to dirty

If you have access to the NgModelController (you can only get access to it from a directive) then you can call

ngModel.$setViewValue("your new view value");
// or to keep the view value the same and just change it to dirty
ngModel.$setViewValue(ngModel.$viewValue);

Spring Security redirect to previous page after successful login

What happens after login (to which url the user is redirected) is handled by the AuthenticationSuccessHandler.

This interface (a concrete class implementing it is SavedRequestAwareAuthenticationSuccessHandler) is invoked by the AbstractAuthenticationProcessingFilter or one of its subclasses like (UsernamePasswordAuthenticationFilter) in the method successfulAuthentication.

So in order to have an other redirect in case 3 you have to subclass SavedRequestAwareAuthenticationSuccessHandler and make it to do what you want.


Sometimes (depending on your exact usecase) it is enough to enable the useReferer flag of AbstractAuthenticationTargetUrlRequestHandler which is invoked by SimpleUrlAuthenticationSuccessHandler (super class of SavedRequestAwareAuthenticationSuccessHandler).

<bean id="authenticationFilter"
      class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
    <property name="filterProcessesUrl" value="/login/j_spring_security_check" />
    <property name="authenticationManager" ref="authenticationManager" />
    <property name="authenticationSuccessHandler">
        <bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
            <property name="useReferer" value="true"/>
        </bean>
    </property>
    <property name="authenticationFailureHandler">
        <bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
            <property name="defaultFailureUrl" value="/login?login_error=t" />
        </bean>
    </property>
</bean>

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

You need to let Gson know additional type of your response as below

import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;


Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
List<UserSite> userSites  = gson.fromJson( response.getBody() , collectionType);

Where can I set environment variables that crontab will use?

Have 'cron' run a shell script that sets the environment before running the command.

Always.

#   @(#)$Id: crontab,v 4.2 2007/09/17 02:41:00 jleffler Exp $
#   Crontab file for Home Directory for Jonathan Leffler (JL)
#-----------------------------------------------------------------------------
#Min     Hour    Day     Month   Weekday Command
#-----------------------------------------------------------------------------
0        *       *       *       *       /usr/bin/ksh /work1/jleffler/bin/Cron/hourly
1        1       *       *       *       /usr/bin/ksh /work1/jleffler/bin/Cron/daily
23       1       *       *       1-5     /usr/bin/ksh /work1/jleffler/bin/Cron/weekday
2        3       *       *       0       /usr/bin/ksh /work1/jleffler/bin/Cron/weekly
21       3       1       *       *       /usr/bin/ksh /work1/jleffler/bin/Cron/monthly

The scripts in ~/bin/Cron are all links to a single script, 'runcron', which looks like:

:       "$Id: runcron.sh,v 2.1 2001/02/27 00:53:22 jleffler Exp $"
#
#       Commands to be performed by Cron (no debugging options)

#       Set environment -- not done by cron (usually switches HOME)
. $HOME/.cronfile

base=`basename $0`
cmd=${REAL_HOME:-/real/home}/bin/$base

if [ ! -x $cmd ]
then cmd=${HOME}/bin/$base
fi

exec $cmd ${@:+"$@"}

(Written using an older coding standard - nowadays, I'd use a shebang '#!' at the start.)

The '~/.cronfile' is a variation on my profile for use by cron - rigorously non-interactive and no echoing for the sake of being noisy. You could arrange to execute the .profile and so on instead. (The REAL_HOME stuff is an artefact of my environment - you can pretend it is the same as $HOME.)

So, this code reads the appropriate environment and then executes the non-Cron version of the command from my home directory. So, for example, my 'weekday' command looks like:

:       "@(#)$Id: weekday.sh,v 1.10 2007/09/17 02:42:03 jleffler Exp $"
#
#       Commands to be done each weekday

# Update ICSCOPE
n.updics

The 'daily' command is simpler:

:       "@(#)$Id: daily.sh,v 1.5 1997/06/02 22:04:21 johnl Exp $"
#
#       Commands to be done daily

# Nothing -- most things are done on weekdays only

exit 0

Docker how to change repository name or rename image?

docker run -it --name NEW_NAME Existing_name

To change the existing image name.

Connecting to a network folder with username/password in Powershell

This is not a PowerShell-specific answer, but you could authenticate against the share using "NET USE" first:

net use \\server\share /user:<domain\username> <password>

And then do whatever you need to do in PowerShell...

What does the Visual Studio "Any CPU" target mean?

"Any CPU" means that when the program is started, the .NET Framework will figure out, based on the OS bitness, whether to run your program in 32 bits or 64 bits.

There is a difference between x86 and Any CPU: on a x64 system, your executable compiled for X86 will run as a 32-bit executable.

As far as your suspicions go, just go to the Visual Studio 2008 command line and run the following.

dumpbin YourProgram.exe /headers

It will tell you the bitness of your program, plus a whole lot more.

Select last N rows from MySQL

SELECT * FROM table ORDER BY id DESC,datechat desc LIMIT 50

If you have a date field that is storing the date(and time) on which the chat was sent or any field that is filled with incrementally(order by DESC) or desinscrementally( order by ASC) data per row put it as second column on which the data should be order.

That's what worked for me!!!! hope it will help!!!!

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

It depends on the kind of test double you want to interact with:

  • If you don't use doNothing and you mock an object, the real method is not called
  • If you don't use doNothing and you spy an object, the real method is called

In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.

How to find and replace with regex in excel

If you want a formula to do it then:

=IF(ISNUMBER(SEARCH("*texts are *",A1)),LEFT(A1,FIND("texts are ",A1) + 9) & "WORD",A1)

This will do it. Change `"WORD" To the word you want.

JSON.parse vs. eval()

You are more vulnerable to attacks if using eval: JSON is a subset of Javascript and json.parse just parses JSON whereas eval would leave the door open to all JS expressions.

How to convert int to date in SQL Server 2008

You can't convert an integer value straight to a date but you can first it to a datetime then to a date type

select cast(40835 as datetime)

and then convert to a date (SQL 2008)

select cast(cast(40835 as datetime) as date)

cheers

Scrollbar without fixed height/Dynamic height with scrollbar

 <div id="scroll">
    <p>Try to add more text</p>
 </div>

here's the css code

#scroll {
   overflow-y:auto;
   height:auto;
   max-height:200px;
   border:1px solid black;
   width:300px;
 }

here's the demo JSFIDDLE