Programs & Examples On #Sharepoint

For SharePoint-specific questions, please see the SharePoint Stack Exchange ( site. Use this tag for programming questions which may involve SharePoint. Microsoft SharePoint is a platform and a family of software products developed by Microsoft for collaboration and web publishing.

Auto number column in SharePoint list

If you want to control the formatting of the unique identifier you can create your own <FieldType> in SharePoint. MSDN also has a visual How-To. This basically means that you're creating a custom column.

WSS defines the Counter field type (which is what the ID column above is using). I've never had the need to re-use this or extend it, but it should be possible.

A solution might exist without creating a custom <FieldType>. For example: if you wanted unique IDs like CUST1, CUST2, ... it might be possible to create a Calculated column and use the value of the ID column in you formula (="CUST" & [ID]). I haven't tried this, but this should work :)

Get the content of a sharepoint folder with Excel VBA

Drive mapping to sharepoint (also https)

Getting sharepoint contents worked for me via the mapped drive iterating it as a filesystem object; trick is how to set up the mapping: from sharepoint, open as explorer Then copy path (line with http*) (see below)

address in explorer

Use this path in Map drive from explorer or command (i.e. net use N: https:://thepathyoujustcopied) Note: https works ok with windows7/8, not with XP.

That may work for you, but I prefer a different approach as drive letters are different on each pc. The trick here is to start from sharepoint (and not from a VBA script accessing sharepoint as a web server).

Set up a data connection to excel sheet

  • in sharepoint, browse to the view you want to monitor
  • export view to excel (in 2010: library tools; libarry | export to Excel) export to excel
  • when viewing this excel, you'll find a datasource set up (tab: data, connections, properties, definition)

connection tab

You can either include this query in vba, or maintain the database link in your speadsheet, iterating over the table by VBA. Please note: the image above does not show the actual database connection (command text), which would tell you how to access my sharepoint.

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Run this script from SharePoint 2010 Management Shell as Administrator.

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

How to pass credentials to httpwebrequest for accessing SharePoint Library

If you need to set the credentials on the fly, have a look at this source:

private ICredentials BuildCredentials(string siteurl, string username, string password, string authtype) {
    NetworkCredential cred;
    if (username.Contains(@"\")) {
        string domain = username.Substring(0, username.IndexOf(@"\"));
        username = username.Substring(username.IndexOf(@"\") + 1);
        cred = new System.Net.NetworkCredential(username, password, domain);
    } else {
        cred = new System.Net.NetworkCredential(username, password);
    CredentialCache cache = new CredentialCache();
    if (authtype.Contains(":")) {
        authtype = authtype.Substring(authtype.IndexOf(":") + 1); //remove the TMG: prefix
    cache.Add(new Uri(siteurl), authtype, cred);
    return cache;

SharePoint : How can I programmatically add items to a custom list instance

I think these both blog post should help you solving your problem.

Short walk through:

  1. Get a instance of the list you want to add the item to.
  2. Add a new item to the list:

    SPListItem newItem = list.AddItem();
  3. To bind you new item to a content type you have to set the content type id for the new item:

    newItem["ContentTypeId"] = <Id of the content type>;
  4. Set the fields specified within your content type.

  5. Commit your changes:


"Object doesn't support this property or method" error in IE11

What fixed this for me was that I had a React component being rendered prior to my core.js shim being loaded.

import ReactComponent from '.'
import 'core-js/es6'

Loading the core-js prior to the ReactComponent fixed my issue

import 'core-js/es6'
import ReactComponent from '.'

Can two or more people edit an Excel document at the same time?

The new version of SharePoint and Office (SharePoint 2010 and Office 2010) respectively are supposed to allow for this. This also includes the web based versions. I have seen Word and Excel in action do this, not sure about other client applications.

I am not sure about the specific implementation features you are asking about in terms of security though. Sorry.,=

Here is a discussion

Filtering Sharepoint Lists on a "Now" or "Today"

In the View, modify the current view or create a new view and make a filter change, select the radio button "Show items only when the following is true", in the below columns type "Created" and in the next dropdown select "is less than" and fill the next column [Today]-7.

The keyword [Today] denotes the current day for the calculation and this view will show as per your requirement

Best way to resolve file path too long exception

What worked for me is moving my project as it was on the desktop (C:\Users\lachezar.l\Desktop\MyFolder) to (C:\0\MyFolder) which as you can see uses shorter path and reducing it solved the problem.

Bypass invalid SSL certificate errors when calling web services in .Net

Like Jason S's answer:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

I put this in my Main and look to my app.config and test if (ConfigurationManager.AppSettings["IgnoreSSLCertificates"] == "True") before calling that line of code.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

If the 2nd company is happy for you to access their content in an IFrame then they need to take the restriction off - they can do this fairly easily in the IIS config.

There's nothing you can do to circumvent it and anything that does work should get patched quickly in a security hotfix. You can't tell the browser to just render the frame if the source content header says not allowed in frames. That would make it easier for session hijacking.

If the content is GET only you don't post data back then you could get the page server side and proxy the content without the header, but then any post back should get invalidated.

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

You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.

Upload using Object Model:

String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "";
String documentLibraryName = "Shared Documents";

using (SPSite oSite = new SPSite(sharePointSite))
    using (SPWeb oWeb = oSite.OpenWeb())
        if (!System.IO.File.Exists(fileToUpload))
            throw new FileNotFoundException("File not found.", fileToUpload);                    

        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

        // Prepare to upload
        Boolean replaceExistingFiles = true;
        String fileName = System.IO.Path.GetFileName(fileToUpload);
        FileStream fileStream = File.OpenRead(fileToUpload);

        // Upload document
        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

        // Commit 

How can you have SharePoint Link Lists default to opening in a new window?

The same instance for SP2010; the Links List webpart will not automatically open in a new window, rather user must manually rt click Link object and select Open in New Window.

The add/ insert Link option withkin SP2010 will allow a user to manually configure the link to open in a new window.

Maybe SP2012 release will adrress this...

CAML query with nested ANDs and ORs for multiple fields

You can try U2U Query Builder you can use their API U2U.SharePoint.CAML.Server.dll and U2U.SharePoint.CAML.Client.dll

I didn't use them but I'm sure it will help you achieving your task.

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Try this, pick or create one column and make that value required so that it's always populated such as title. A field that doesn't hold the name of the folder. Then in your filter put the filter you wanted that will select only the files you want. Then add an or to your filter, select your "required" field then set it equal to and leave the filter blank. Since all folders will have a blank in this required field your folders will show up with your files.

SharePoint 2013 get current user using JavaScript

You can use the SharePoint JSOM to get your current user's account information. This code (when added as the snippet in the Script Editor web part) will just pop up the user's display and account name in the browser - you'll want to add whatever else in gotAccount to get the name in the format you want.

<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.UserProfiles.js"></script>
<script type="text/javascript">

  var personProperties;

  SP.SOD.executeOrDelayUntilScriptLoaded(getCurrentUser, 'SP.UserProfiles.js');

  function getCurrentUser() {
    var clientContext = new SP.ClientContext.get_current();
    personProperties = new SP.UserProfiles.PeopleManager(clientContext).getMyProperties();
    clientContext.executeQueryAsync(gotAccount, requestFailed);

  function gotAccount(sender, args) {
    alert("Display Name: "+ personProperties.get_displayName() + 
        ", Account Name: " + personProperties.get_accountName());

  function requestFailed(sender, args) {
    alert('Cannot get user account information: ' + args.get_message());


See the SP.UserProfiles.PersonProperties documentation in MSDN for more info.

The HTTP request is unauthorized with client authentication scheme 'Ntlm' The authentication header received from the server was 'NTLM'

I would try to connect to your Sharepoint site with this tool here. If that works you can be sure that the problem is in your code / configuration. That maybe does not solve your problem immediately but it rules out that there is something wrong with the server. Assuming that it does not work I would investigate the following:

  • Does your user really have enough rights on the site?
  • Is there a proxy that interferes? (Your configuration looks a bit like there is a proxy. Can you bypass it?)

I think there is nothing wrong with using security mode Transport, but I am not so sure about the proxyCredentialType="Ntlm", maybe this should be set to None. page without a code behind

I thought you could deploy just your .aspx page without the .aspx.cs so long as the DLL was in your bin. Part of the issue here is how visual studio .net works with .aspx pages.

Check it out here: Working with Single-File Web Forms Pages in Visual Studio .NET

I know for sure that VS2008 with MVC RC you don't have code-behind files for your views.

Is it possible to create a 'link to a folder' in a SharePoint document library?

i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.

Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.

.url files can be made by saving a favourite with internet exploiter.

How do I solve this error, "error while trying to deserialize parameter"

I found the actual solution...There is a problem in invoking your service from the client.. check the following things.

  1. Make sure all [datacontract], [datamember] attribute are placed properly i.e. make sure WCF is error free

  2. The WCF client, either web.config or any window app config, make sure config entries are properly pointing to the right ones.. binding info, url of the service..etc..etc

Then above problem : tempuri issue is resolved.. it has nothing to do with namespace.. though you are sure you lived with default,

Hope it saves your number of hours!

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

At times the error code 409 occurs when you name you folder or files a reserved or blocked name. These could be names like register, contact

In my case I named a folder contact, turns out the name was blocked from being used as folder names.

When testing my script on postman, I was getting this error:

    document.cookie = "humans_21909=1"; document.location.reload(true)

I changed the folder name from contact to contacts and it worked. The error was gone.

Where is the default log location for SharePoint/MOSS?

For Sharepoint 2007

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS

Could not load file or assembly '' or one of its dependencies

Following worked for me.

  • Remove Temporary Files C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files
    • then right click on Temporary Files>properties>security and give total control access to IIS and to all user runing my project

Breadth First Vs Depth First

Understanding the terms:

This picture should give you the idea about the context in which the words breadth and depth are used.

Understanding Breadth and Depth

Depth-First Search:

Depth-First Search

  • Depth-first search algorithm acts as if it wants to get as far away from the starting point as quickly as possible.

  • It generally uses a Stack to remember where it should go when it reaches a dead end.

  • Rules to follow: Push first vertex A on to the Stack

    1. If possible, visit an adjacent unvisited vertex, mark it as visited, and push it on the stack.
    2. If you can’t follow Rule 1, then, if possible, pop a vertex off the stack.
    3. If you can’t follow Rule 1 or Rule 2, you’re done.
  • Java code:

    public void searchDepthFirst() {
        // Begin at vertex 0 (A)
        vertexList[0].wasVisited = true;
        while (!stack.isEmpty()) {
            int adjacentVertex = getAdjacentUnvisitedVertex(stack.peek());
            // If no such vertex
            if (adjacentVertex == -1) {
            } else {
                vertexList[adjacentVertex].wasVisited = true;
                // Do something
        // Stack is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++)
            vertexList[j].wasVisited = false;
  • Applications: Depth-first searches are often used in simulations of games (and game-like situations in the real world). In a typical game you can choose one of several possible actions. Each choice leads to further choices, each of which leads to further choices, and so on into an ever-expanding tree-shaped graph of possibilities.

Breadth-First Search:

Breadth-First Search

  • The breadth-first search algorithm likes to stay as close as possible to the starting point.
  • This kind of search is generally implemented using a Queue.
  • Rules to follow: Make starting Vertex A the current vertex
    1. Visit the next unvisited vertex (if there is one) that’s adjacent to the current vertex, mark it, and insert it into the queue.
    2. If you can’t carry out Rule 1 because there are no more unvisited vertices, remove a vertex from the queue (if possible) and make it the current vertex.
    3. If you can’t carry out Rule 2 because the queue is empty, you’re done.
  • Java code:

    public void searchBreadthFirst() {
        vertexList[0].wasVisited = true;
        int v2;
        while (!queue.isEmpty()) {
            int v1 = queue.remove();
            // Until it has no unvisited neighbors, get one
            while ((v2 = getAdjUnvisitedVertex(v1)) != -1) {
                vertexList[v2].wasVisited = true;
                // Do something
        // Queue is empty, so we're done, reset flags
        for (int j = 0; j < nVerts; j++) 
            vertexList[j].wasVisited = false;
  • Applications: Breadth-first search first finds all the vertices that are one edge away from the starting point, then all the vertices that are two edges away, and so on. This is useful if you’re trying to find the shortest path from the starting vertex to a given vertex.

Hopefully that should be enough for understanding the Breadth-First and Depth-First searches. For further reading I would recommend the Graphs chapter from an excellent data structures book by Robert Lafore.

Jquery UI datepicker. Disable array of Dates

If you also want to block Sundays (or other days) as well as the array of dates, I use this code:


    var disabledDays = [
       "27-4-2016", "25-12-2016", "26-12-2016",
       "4-4-2017", "5-4-2017", "6-4-2017", "6-4-2016", "7-4-2017", "8-4-2017", "9-4-2017"

   //replace these with the id's of your datepickers
      beforeShowDay: function(date){
         var day = date.getDay();
         var string = jQuery.datepicker.formatDate('d-m-yy', date);
         var isDisabled = ($.inArray(string, disabledDays) != -1);

         //day != 0 disables all Sundays
         return [day != 0 && !isDisabled];

android - How to get view from context?

Why don't you just use a singleton?

import android.content.Context;

public class ClassicSingleton {
    private Context c=null;
    private static ClassicSingleton instance = null;
    protected ClassicSingleton()
       // Exists only to defeat instantiation.
    public void setContext(Context ctx)
    public Context getContext()
       return c;
    public static ClassicSingleton getInstance()
        if(instance == null) {
            instance = new ClassicSingleton();
        return instance;

Then in the activity class:

 private ClassicSingleton cs = ClassicSingleton.getInstance();

And in the non activity class:

ClassicSingleton cs= ClassicSingleton.getInstance();
        Context c=cs.getContext();
        ImageView imageView = (ImageView) ((Activity)c).findViewById(;

How to find list intersection?

A functional way can be achieved using filter and lambda operator.

list1 = [1,2,3,4,5,6]

list2 = [2,4,6,9,10]

>>> list(filter(lambda x:x in list1, list2))

[2, 4, 6]

Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:

>>> list(filter(lambda x:x not in list1, list2))

Edit2: python3 filter returns a filter object, encapsulating it with list returns the output list.

Carriage return and Line feed... Are both required in C#?

System.Environment.NewLine is the constant you are looking for - which will provide environment specific combination that most programs on given OS will consider "next line of text".

In practice most of the text tools treat all variations that include \n as "new line" and you can just use it in your text "foo\nbar". Especially if you are trying to construct multi-line format strings like $"V1 = {value1}\nV2 = {value2}\n". If you are building text with string concatenation consider using NewLine. In any case make sure tools you are using understand output the way you want and you may need for example always use \r\n irrespective of platform if editor of your choice can't correctly open files otherwise.

Note that WriteLine methods use NewLine so if you plan to write text with one these methods avoid using just \n as resulting text may contain mix of \r\n and just \n which may confuse some tools and definitely does not look neat.

For historical background see Difference between \n and \r?

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

private String getCurrentDateInSpecificFormat(Calendar currentCalDate) {
    String dayNumberSuffix = getDayNumberSuffix(currentCalDate.get(Calendar.DAY_OF_MONTH));
    DateFormat dateFormat = new SimpleDateFormat(" d'" + dayNumberSuffix + "' MMMM yyyy");
    return dateFormat.format(currentCalDate.getTime());

private String getDayNumberSuffix(int day) {
    if (day >= 11 && day <= 13) {
        return "th";
    switch (day % 10) {
    case 1:
        return "st";
    case 2:
        return "nd";
    case 3:
        return "rd";
        return "th";

How do I write a RGB color value in JavaScript?


parent.childNodes[1].style.color = "rgb(155, 102, 102)"; 


parent.childNodes[1].style.color = "#"+(155).toString(16)+(102).toString(16)+(102).toString(16);

How do I remove/delete a folder that is not empty?

From the python docs on os.walk():

# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))

What exactly does Perl's "bless" do?

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.

Add/delete row from a table

Lots of good answers, but here is one more ;)

You can add handler for the click to the table

<table id = 'dsTable' onclick="tableclick(event)">

And then just find out what the target of the event was

function tableclick(e) {
     e = window.event;

    if( == "Delete")
       deleteRow( );

Then you don't have to add event handlers for each row and your html looks neater. If you don't want any javascript in your html you can even add the handler when page loads:



Here is working code:

How to delete a cookie?

would this work?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

Generate a dummy-variable

We can also use cSplit_e from splitstackshape. Using @zx8754's data

df1 <- data.frame(id = 1:4, year = 1991:1994)
splitstackshape::cSplit_e(df1, "year", fill = 0)

#  id year year_1 year_2 year_3 year_4
#1  1 1991      1      0      0      0
#2  2 1992      0      1      0      0
#3  3 1993      0      0      1      0
#4  4 1994      0      0      0      1

To make it work for data other than numeric we need to specify type as "character" explicitly

df1 <- data.frame(id = 1:4, let = LETTERS[1:4])
splitstackshape::cSplit_e(df1, "let", fill = 0, type = "character")

#  id let let_A let_B let_C let_D
#1  1   A     1     0     0     0
#2  2   B     0     1     0     0
#3  3   C     0     0     1     0
#4  4   D     0     0     0     1

How to ignore ansible SSH authenticity checking?

Changing host_key_checking to false for all hosts is a very bad idea.

The only time you want to ignore it, is on "first contact", which these two tasks will accomplish:

    - name: Check SSH known_hosts for {{ inventory_hostname }}
      local_action: shell ssh-keygen -F {{ inventory_hostname }}
      register: checkForKnownHostsEntry
      failed_when: false
      changed_when: false
      ignore_errors: yes
    - name: Add {{ inventory_hostname }} to SSH known hosts automatically
      when: checkForKnownHostsEntry.rc == 1
      changed_when: checkForKnownHostsEntry.rc == 1
        ansible_ssh_common_args: '-o StrictHostKeyChecking=no'

So we only turn off host key checking if we don't have the host key in our known_hosts file.

Proxy Basic Authentication in C#: HTTP 407 error

You can use like this, it works!

        WebProxy proxy = new WebProxy
            Address = new Uri(""),
            Credentials = new NetworkCredential("", "")

        HttpClientHandler httpClientHandler = new HttpClientHandler
            Proxy = proxy,
            UseProxy = true

        HttpClient client = new HttpClient(httpClientHandler);

        HttpResponseMessage response = await client.PostAsync("...");

Convert textbox text to integer

int num = int.Parse(textBox.Text);

try this. It worked for me

hardcoded string "row three", should use @string resource

It is not good practice to hard code strings into your layout files/ code. You should add them to a string resource file and then reference them from your layout.

  1. This allows you to update every occurrence of the same word in all
    layouts at the same time by just editing your strings.xml file.
  2. It is also extremely useful for supporting multiple languages as a separate strings.xml file can be used for each supported language
  3. the actual point of having the @string system please read over the localization documentation. It allows you to easily locate text in your app and later have it translated.
  4. Strings can be internationalized easily, allowing your application to support multiple languages with a single application package file (APK).


  • Lets say you used same string in 10 different locations in the code. What if you decide to alter it? Instead of searching for where all it has been used in the project you just change it once and changes are reflected everywhere in the project.
  • Strings don’t clutter up your application code, leaving it clear and easy to maintain.

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)

How can I download a specific Maven artifact in one command line?

one liner to download latest maven artifact without mvn:

curl -O -J -L  ""

How to draw vertical lines on a given plot in matplotlib

For multiple lines

xposition = [0.3, 0.4, 0.45]
for xc in xposition:
    plt.axvline(x=xc, color='k', linestyle='--')

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • How to set a header for a HTTP GET request, and trigger file download?

    There are two ways to download a file where the HTTP request requires that a header be set.

    The credit for the first goes to @guest271314, and credit for the second goes to @dandavis.

    The first method is to use the HTML5 File API to create a temporary local file, and the second is to use base64 encoding in conjunction with a data URI.

    The solution I used in my project uses the base64 encoding approach for small files, or when the File API is not available, otherwise using the the File API approach.


            var id = 123;
            var req = ic.ajax.raw({
                type: 'GET',
                url: '/api/dowloads/'+id,
                beforeSend: function (request) {
                    request.setRequestHeader('token', 'token for '+id);
                processData: false
            var maxSizeForBase64 = 1048576; //1024 * 1024
                function resolve(result) {
                    var str = result.response;
                    var anchor = $('.vcard-hyperlink');
                    var windowUrl = window.URL || window.webkitURL;
                    if (str.length > maxSizeForBase64 && typeof windowUrl.createObjectURL === 'function') {
                        var blob = new Blob([result.response], { type: 'text/bin' });
                        var url = windowUrl.createObjectURL(blob);
                        anchor.prop('href', url);
                        anchor.prop('download', id+'.bin');
                    else {
                        //use base64 encoding when less than set limit or file API is not available
                            href: 'data:text/plain;base64,'+FormatUtils.utf8toBase64(result.response),
                            download: id+'.bin',
                function reject(err) {

    Note that I'm not using a raw XMLHttpRequest, and instead using ic-ajax, and should be quite similar to a jQuery.ajax solution.

    Note also that you should substitute text/bin and .bin with whatever corresponds to the file type being downloaded.

    The implementation of FormatUtils.utf8toBase64 can be found here

    Get elements by attribute when querySelectorAll is not available without using libraries?

    Try this - I slightly changed the above answers:

    var getAttributes = function(attribute) {
        var allElements = document.getElementsByTagName('*'),
            allElementsLen = allElements.length,
            results = [];
        for(i = 0; i < allElementsLen; i += 1) {
            curElement = allElements[i];
            if(curElement.getAttribute(attribute)) {
        return results;



    Append values to query string

    This is even more frustrating because now (.net 5) MS have marked many (all) of their methods that take a string instead of a Uri as obsolete.

    Anyway, probably a better way to manipulate relative Uris is to give it what it wants:

    var requestUri = new Uri("x://x").MakeRelativeUri(
       new UriBuilder("x://x") { Path = path, Query = query }.Uri);

    You can use the other answers to actually build the query string.

    An efficient compression algorithm for short text strings

    If you are talking about actually compressing the text not just shortening then Deflate/gzip (wrapper around gzip), zip work well for smaller files and text. Other algorithms are highly efficient for larger files like bzip2 etc.

    Wikipedia has a list of compression times. (look for comparison of efficiency)

    Name       | Text         | Binaries      | Raw images
    7-zip      | 19% in 18.8s | 27% in  59.6s | 50% in 36.4s
    bzip2      | 20% in  4.7s | 37% in  32.8s | 51% in 20.0s
    rar (2.01) | 23% in 30.0s | 36% in 275.4s | 58% in 52.7s
    advzip     | 24% in 21.1s | 37% in  70.6s | 57& in 41.6s
    gzip       | 25% in  4.2s | 39% in  23.1s | 60% in  5.4s
    zip        | 25% in  4.3s | 39% in  23.3s | 60% in  5.7s

    Datatables - Search Box outside datatable

    You could move the div when the table is drawn using the fnDrawCallback function.

        "fnDrawCallback": function (oSettings) {
            $(".dataTables_filter").each(function () {

    How to get the current location in Google Maps Android API v2?

    the accepted answer works but some of the used methods are now deprecated so I think it is best if I answer this question with updated methods.

    this is answer is completely from this guide on google developers

    so here is step by step guide:

    1. implement all this in your map activity

      MapActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks

    2. in your onCreate:

      private GoogleMap mMap;
      private Context context;
      private TextView txtStartPoint,txtEndPoint;
      private GoogleApiClient mGoogleApiClient;
      private Location mLastKnownLocation;
      private LatLng mDefaultLocation;
      private CameraPosition mCameraPosition;
      private boolean mLocationPermissionGranted;
      protected void onCreate(Bundle savedInstanceState) {
      context = this;
      mGoogleApiClient = new GoogleApiClient.Builder(this)
              .enableAutoManage(this /* FragmentActivity */,
                      this /* OnConnectionFailedListener */)
    3. in your onConnected :

      SupportMapFragment mapFragment = (SupportMapFragment)     getSupportFragmentManager()
    4. in your onMapReady :

      public void onMapReady(GoogleMap googleMap) {
      mMap = googleMap;
      // Do other setup activities here too, as described elsewhere in this tutorial.
      // Turn on the My Location layer and the related control on the map.
      // Get the current location of the device and set the position of the map.
    5. and these two are methods in onMapReady :

      private void updateLocationUI() {
        if (mMap == null) {
      if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
              == PackageManager.PERMISSION_GRANTED) {
          mLocationPermissionGranted = true;
      if (mLocationPermissionGranted) {
      } else {
          mLastKnownLocation = null;
      private void getDeviceLocation() {
      if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
              == PackageManager.PERMISSION_GRANTED) {
          mLocationPermissionGranted = true;
      if (mLocationPermissionGranted) {
          mLastKnownLocation = LocationServices.FusedLocationApi
      // Set the map's camera position to the current location of the device.
      float DEFAULT_ZOOM = 15;
      if (mCameraPosition != null) {
      } else if (mLastKnownLocation != null) {
                  new LatLng(mLastKnownLocation.getLatitude(),
                          mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
      } else {
          Log.d("pouya", "Current location is null. Using defaults.");
          mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));

    this is very fast , smooth and effective. hope this helps

    Eclipse comment/uncomment shortcut?

    1. Single line comment Ctrl + /
    2. Single line uncomment Ctrl + /

    1. Multiline comment Ctrl + Shift + /
    2. Multiline uncomment Ctrl + Shift + \ (note the backslash)

    How do you join tables from two different SQL Server instances in one SQL query

    The best way I can think of to accomplish this is via sp_addlinkedserver. You need to make sure that whatever account you use to add the link (via sp_addlinkedsrvlogin) has permissions to the table you're joining, but then once the link is established, you can call the server by name, i.e.:

    SELECT *
    FROM server1table
        INNER JOIN server2.database.dbo.server2table ON .....

    How to get maximum value from the Collection (for example ArrayList)?

    In addition to gotomanners answer, in case anyone else came here looking for a null safe solution to the same problem, this is what I ended up with

    Collections.max(arrayList, Comparator.nullsFirst(Comparator.naturalOrder()))

    Array Index Out of Bounds Exception (Java)

    import java.util.Scanner;
    class ar1 {
        public static void main(String[] args) {
            //Scanner sc=new Scanner(;
            int[] a={10,20,30,40,12,32};
            int bi=0,sm=0;
            for(int i=0;i<=a.length-1;i++) {

    Calculate correlation for more than two variables?

    Use the same function (cor) on a data frame, e.g.:

    > cor(VADeaths)
                 Rural Male Rural Female Urban Male Urban Female
    Rural Male    1.0000000    0.9979869  0.9841907    0.9934646
    Rural Female  0.9979869    1.0000000  0.9739053    0.9867310
    Urban Male    0.9841907    0.9739053  1.0000000    0.9918262
    Urban Female  0.9934646    0.9867310  0.9918262    1.0000000

    Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:

    > cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
                mpg        cyl       disp         hp        drat         wt        qsec         vs          am       gear        carb
    mpg   1.0000000 -0.8521620 -0.8475514 -0.7761684  0.68117191 -0.8676594  0.41868403  0.6640389  0.59983243  0.4802848 -0.55092507
    cyl  -0.8521620  1.0000000  0.9020329  0.8324475 -0.69993811  0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866  0.52698829
    disp -0.8475514  0.9020329  1.0000000  0.7909486 -0.71021393  0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692  0.39497686
    hp   -0.7761684  0.8324475  0.7909486  1.0000000 -0.44875912  0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043  0.74981247
    drat  0.6811719 -0.6999381 -0.7102139 -0.4487591  1.00000000 -0.7124406  0.09120476  0.4402785  0.71271113  0.6996101 -0.09078980
    wt   -0.8676594  0.7824958  0.8879799  0.6587479 -0.71244065  1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870  0.42760594
    qsec  0.4186840 -0.5912421 -0.4336979 -0.7082234  0.09120476 -0.1747159  1.00000000  0.7445354 -0.22986086 -0.2126822 -0.65624923
    vs    0.6640389 -0.8108118 -0.7104159 -0.7230967  0.44027846 -0.5549157  0.74453544  1.0000000  0.16834512  0.2060233 -0.56960714
    am    0.5998324 -0.5226070 -0.5912270 -0.2432043  0.71271113 -0.6924953 -0.22986086  0.1683451  1.00000000  0.7940588  0.05753435
    gear  0.4802848 -0.4926866 -0.5555692 -0.1257043  0.69961013 -0.5832870 -0.21268223  0.2060233  0.79405876  1.0000000  0.27407284
    carb -0.5509251  0.5269883  0.3949769  0.7498125 -0.09078980  0.4276059 -0.65624923 -0.5696071  0.05753435  0.2740728  1.00000000

    How to check if a subclass is an instance of a class at runtime?

    Maybe I'm missing something, but wouldn't this suffice:

    if (view instanceof B) {
        // this view is an instance of B

    How to define optional methods in Swift protocol?

    Here is a concrete example with the delegation pattern.

    Setup your Protocol:

    @objc protocol MyProtocol:class
        func requiredMethod()
        optional func optionalMethod()
    class MyClass: NSObject
        weak var delegate:MyProtocol?
        func callDelegate()

    Set the delegate to a class and implement the Protocol. See that the optional method does not need to be implemented.

    class AnotherClass: NSObject, MyProtocol
            let myInstance = MyClass()
            myInstance.delegate = self
        func requiredMethod()

    One important thing is that the optional method is optional and needs a "?" when calling. Mention the second question mark.


    How can I get around MySQL Errcode 13 with SELECT INTO OUTFILE?

    Does Ubuntu use SELinux? Check to see if it's enabled and enforcing. /var/log/audit/audit.log may be helpul (if that's where Ubuntu sticks it -- that's the RHEL/Fedora location).

    HTML5 required attribute seems not working

    Actually speaking, when I tried this, it worked only when I set the action and method value for the form. Funny how it works though!

    How to change the ROOT application?

    I'll look at my docs; there's a way of specifying a configuration to change the path of the root web application away from ROOT (or ROOT.war), but it seems to have changed between Tomcat 5 and 6.

    Found this:

    So, it seems that changing the root path (in ROOT.xml) is possible, but a bit broken -- you need to move your WAR outside of the auto-deployment directory. Mind if I ask why just renaming your file to ROOT.war isn't a workable solution?

    Difference between IsNullOrEmpty and IsNullOrWhiteSpace in C#

    The first method checks if a string is null or a blank string. In your example you can risk a null reference since you are not checking for null before trimming

    1- string.IsNullOrEmpty(text.Trim())

    The second method checks if a string is null or an arbitrary number of spaces in the string (including a blank string)

    2- string .IsNullOrWhiteSpace(text)

    The method IsNullOrWhiteSpace covers IsNullOrEmpty, but it also returns true if the string contains white space.

    In your concrete example you should use 2) as you run the risk of a null reference exception in approach 1) since you're calling trim on a string that may be null

    NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

    Copy all order entries of home folder .iml file into your /src/main/main.iml file. This will solve the problem.

    Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

    My fix was as simple as making sure the correct connection string was in ALL appsettings.json files, not just the default one.

    Examples for string find in Python


    myString = 'abcabc'

    This will give you the index!!!

    httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

    Start with root user or with sudo, it works fine, here is sample output:

    [ec2-user@ip-172-31-12-164 ~]$ service httpd start
    Starting httpd: (13)Permission denied: make_sock: could not bind to address [::]:80
    (13)Permission denied: make_sock: could not bind to address
    no listening sockets available, shutting down
    Unable to open logs
    [ec2-user@ip-172-31-12-164 ~]$ sudo service httpd start
    Starting httpd:                                            [  OK  ]
    [ec2-user@ip-172-31-12-164 ~]$ sudo service httpd status
    httpd (pid  3077) is running...

    What is the easiest way to parse an INI file in Java?

    Here's a simple, yet powerful example, using the apache class HierarchicalINIConfiguration:

    HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile); 
    // Get Section names in ini file     
    Set setOfSections = iniConfObj.getSections();
    Iterator sectionNames = setOfSections.iterator();
     String sectionName =;
     SubnodeConfiguration sObj = iniObj.getSection(sectionName);
     Iterator it1 =   sObj.getKeys();
        while (it1.hasNext()) {
        // Get element
        Object key =;
        System.out.print("Key " + key.toString() +  " Value " +  
                         sObj.getString(key.toString()) + "\n");

    Commons Configuration has a number of runtime dependencies. At a minimum, commons-lang and commons-logging are required. Depending on what you're doing with it, you may require additional libraries (see previous link for details).

    Groovy - How to compare the string?

    If you don't want to check on upper or lowercases you can use the following method.

    String str = "India" 
    def compareString(String str){ 
      def str2 = "india" 
      if( str2.toUpperCase() == str.toUpperCase() ) { 
        println "same" 
        println "not same" 

    So now if you change str to "iNdIa" it'll still work, so you lower the chance that you make a typo.

    Laravel 5 Carbon format datetime

    Try that:

    $createdAt = Carbon::parse(date_format($item['created_at'],'d/m/Y H:i:s');
    $createdAt= $createdAt->format('M d Y');

    How to change a TextView's style at runtime

    Like Jonathan suggested, using textView.setTextTypeface works, I just used it in an app a few seconds ago.

    textView.setTypeface(null, Typeface.BOLD); // Typeface.NORMAL, Typeface.ITALIC etc.

    Get a substring of a char*

    Use char* strncpy(char* dest, char* src, int n) from <cstring>. In your case you will need to use the following code:

    char* substr = malloc(4);
    strncpy(substr, buff+10, 4);

    Full documentation on the strncpy function here.

    Is it possible to set ENV variables for rails development environment in my code?

    The way I am trying to do this in my question actually works!

    # environment/development.rb
    ENV['admin_password'] = "secret" 

    I just had to restart the server. I thought running reload! in rails console would be enough but I also had to restart the web server.

    I am picking my own answer because I feel this is a better place to put and set the ENV variables

    keycode 13 is for which key

    Keycode 13 means the Enter key.

    If you would want to get more keycodes and what the key the key is, go to:

    Why do I need to configure the SQL dialect of a data source?

    A dialect is a form of the language that is spoken by a particular group of people.

    Here, in context of hibernate framework, When hibernate wants to talk(using queries) with the database it uses dialects.

    The SQL dialect's are derived from the Structured Query Language which uses human-readable expressions to define query statements.
    A hibernate dialect gives information to the framework of how to convert hibernate queries(HQL) into native SQL queries.

    The dialect of hibernate can be configured using below property:


    Here, is a complete list of hibernate dialects.

    Note: The dialect property of hibernate is not mandatory.

    Display / print all rows of a tibble (tbl_df)

    I prefer to turn the tibble to data.frame. It shows everything and you're done

    df %>% data.frame 

    Press any key to continue

    Check out the ReadKey() method on the System.Console .NET class. I think that will do what you're looking for.


    Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

    Parse JSON String to JSON Object in C#.NET

    Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

    It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

    And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

    There is a System.Json.dll you should add to your project References.


    how to sync windows time from a ntp time server in command

    net stop w32time
    w32tm /config /syncfromflags:manual /manualpeerlist:""
    net start w32time
    w32tm /config /update
    w32tm /resync /rediscover

    .BAT Sample File:

    I also recommend this program:

    CSS: Hover one element, effect for multiple elements?

    This is not difficult to achieve, but you need to use the javascript onmouseover function. Pseudoscript:

    <div class="section ">
    <div class="image"><img src="myImage.jpg" onmouseover=".layer {border: 1px solid black;} .image {border: 1px solid black;}" /></div>
    <div class="layer">Lorem Ipsum</div>

    Use your own colors. You can also reference javascript functions in the mouseover command.

    Uninstalling Android ADT

    The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details.

    Select a plug-in you want to uninstall, then click Uninstall... button at the bottom.

    enter image description here

    If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.

    Error: 'int' object is not subscriptable - Python

    It would be a lot more simple just to do this;

    name = input("What's your name? ")
    age = int(input("How old are you? "))
    print ("Hi,{0} you will be 21 in {1} years.".format(name, 21 - age))`

    DLL load failed error when importing cv2

    Please Remember if you want to install python package/libraries for windows,

    you should always consider Python unofficial Binaries

    Step 1:

    Search for your package, download dependent version 2.7 or 3.6 you can find it under Downloads/your_package_version.whl its called python wheel

    Step 2:

    Now install using pip,

    pip install ~/Downloads/your_packae_ver.whl

    this will install without any error.

    Checkout one file from Subversion

    Try svn export instead of svn checkout. That works for single files.

    The reason for the limitation is that checkout creates a working copy, that contains meta-information about repository, revision, attributes, etc. That metadata is stored in subdirectories named '.svn'. And single files don't have subdirectories.

    Drawing Circle with OpenGL

    Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius

    void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
        int i;
        int triangleAmount = 20; //# of triangles used to draw circle
        //GLfloat radius = 0.8f; //radius
        GLfloat twicePi = 2.0f * PI;
        glVertex2f(x, y); // center of circle
        for (i = 0; i <= triangleAmount; i++) {
                x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
                y + ((ycenter-1)* sin(i * twicePi / triangleAmount))

    How to revert a merge commit that's already pushed to remote branch?

    Ben has told you how to revert a merge commit, but it's very important you realize that in doing so

    "...declares that you will never want the tree changes brought in by the merge. As a result, later merges will only bring in tree changes introduced by commits that are not ancestors of the previously reverted merge. This may or may not be what you want." (git-merge man page).

    An article/mailing list message linked from the man page details the mechanisms and considerations that are involved. Just make sure you understand that if you revert the merge commit, you can't just merge the branch again later and expect the same changes to come back.

    The Android emulator is not starting, showing "invalid command-line parameter"

    There is currently a problem with R12 where the SDK location cannot contain any spaces.

    The default installation location is: C:\Programme Files(x86)\Android\android-sdk. They are currently fixing the problem but you can currently work around it by changing the SDK location path in eclipse to C:\PROGRA~2\Android\android-sdk.

    If you are running 32-bit Windows, change the path to C:\PROGRA~1\Android\android-sdk.

    Comprehensive methods of viewing memory usage on Solaris

    Top can be compiled from sources or downloaded from As previously posted, vmstat is available (I believe it's in the core install?).

    How can I convert ticks to a date format?

    It's much simpler to do this:

    DateTime dt = new DateTime(633896886277130000);

    Which gives

    dt.ToString() ==> "9/27/2009 10:50:27 PM"

    You can format this any way you want by using dt.ToString(MyFormat). Refer to this reference for format strings. "MMMM dd, yyyy" works for what you specified in the question.

    Not sure where you get October 1.

    Am I trying to connect to a TLS-enabled daemon without TLS?

    On Ubuntu after installing lxc-docker you need to add your user to the docker user group:

    sudo usermod -a -G docker myusername

    This is because of the socket file permissions:

    srw-rw---- 1 root docker 0 Mar 20 07:43 /var/run/docker.sock

    DO NOT RUN usermod WITHOUT "-a" as suggested in one of the other comments or it will wipe your additional groups setting and will just leave the "docker" group

    This is what will happen:

    ?  ~  id pawel
    uid=1000(pawel) gid=1000(pawel) groups=1000(pawel),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),108(lpadmin),124(sambashare),998(docker)
    ?  ~  usermod -G docker pawel
    ?  ~  id pawel               
    uid=1000(pawel) gid=1000(pawel) groups=1000(pawel),998(docker)

    jQuery AJAX submit form

    There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.


    HTTP status code 0 - Error Domain=NSURLErrorDomain?

    We got the error:

    GET http://localhost/pathToWebSite/somePage.aspx raised an http.status: 0 error

    That call is made from windows task that calls a VBS file, so to troubleshoot the problem, pointed a browser to the url and we get a Privacy Error:

    Your connection is not private

    Attackers might be trying to steal your information from localhost (for example, passwords, messages, or credit cards). NET::ERR_CERT_COMMON_NAME_INVALID

    Automatically report details of possible security incidents to Google. Privacy policy Back to safety This server could not prove that it is localhost; its security certificate is from * This may be caused by a misconfiguration or an attacker intercepting your connection. Learn more.

    This is because we have a IIS URL Rewrite rule set to force connections use https. That rule diverts http://localhost to https://localhost but our SSL certificate is based on an outside facing domain name not localhost, thus the error which is reported as status code 0. So a Privacy error could be a very obscure reason for this status code 0.

    In our case the solution was to add an exception to the rule for localhost and allow http://localhost/pathToWebSite/somePage.aspx to use http. Obscure, yes, but I'll run into this next year and now I'll find my answer in a google search.

    How to get current time with jQuery

    I use moment for all my time manipulation/display needs (both client side, and node.js if you use it), if you just need a simple format the answers above will do, if you are looking for something a bit more complex, moment is the way to go IMO.

    Printing object properties in Powershell

    # Json to object
    $obj = $obj | ConvertFrom-Json
    Write-host $obj.PropertyName

    json and empty array

    "location" : null // this is not really an array it's a null object
    "location" : []   // this is an empty array

    It looks like this API returns null when there is no location defined - instead of returning an empty array, not too unusual really - but they should tell you if they're going to do this.

    Pandas dataframe groupby plot

    Simple plot,

    you can use:


    Or you can set the index to be Date beforehand, then it's easy to plot the column you want:

    df.set_index('Date', inplace=True)

    If you want a chart with one series by ticker on it

    You need to groupby before:

    df.set_index('Date', inplace=True)

    enter image description here

    If you want a chart with individual subplots:

    grouped = df.groupby('ticker')
    nrows = int(np.ceil(grouped.ngroups/ncols))
    fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
    for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):

    enter image description here

    Use PPK file in Mac Terminal to connect to remote connection over SSH

    Convert PPK to OpenSSh

    OS X: Install Homebrew, then run

    brew install putty

    Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search

    To generate the private key:

    cd ~

    puttygen id_dsa.ppk -O private-openssh -o id_dsa

    and to generate the public key:

    puttygen id_dsa.ppk -O public-openssh -o

    Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:

    mkdir -p ~/.ssh
    mv -i ~/id_dsa* ~/.ssh
    chmod 600 ~/.ssh/id_dsa
    chmod 666 ~/.ssh/

    connect with ssh server

    ssh -i ~/.ssh/id_dsa username@servername

    Port Forwarding to connect mysql remote server

    ssh -i ~/.ssh/id_dsa -L 9001: username@serverName

    Prevent BODY from scrolling when a modal is opened

    The best solution is the css-only body{overflow:hidden} solution used by most of these answers. Some answers provide a fix that also prevent the "jump" caused by the disappearing scrollbar; however, none were too elegant. So, I wrote these two functions, and they seem to work pretty well.

    var $body = $(window.document.body);
    function bodyFreezeScroll() {
        var bodyWidth = $body.innerWidth();
        $body.css('overflow', 'hidden');
        $body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
    function bodyUnfreezeScroll() {
        var bodyWidth = $body.innerWidth();
        $body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
        $body.css('overflow', 'auto');

    Check out this jsFiddle to see it in use.

    Check whether specific radio button is checked

    You should remove the '@' before 'name'; it's not needed anymore (for current jQuery versions).

    You're want to return all checked elements with name 'test2', but you don't have any elements with that name, you're using an id of 'test2'.

    If you're going to use IDs, just try:

    return $('#test2').attr('checked');

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

    A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

    $ mkdir repo
    $ cd repo
    $ git init
    Initialized empty Git repository in /home/me/repo/.git/
    $ git branch
    $ touch foo
    $ git add foo
    $ git commit -m "new file"
    1 file changed, 0 insertions(+), 0 deletions(-)
    create mode 100644 foo
    $ git branch
    * master

    TypeError: 'float' object is not callable

    The problem is with -3.7(prof[x]), which looks like a function call (note the parens). Just use a * like this -3.7*prof[x].

    Make multiple-select to adjust its height to fit options without scroll bar

    To remove the scrollbar add the following CSS:

    select[multiple] {
        overflow-y: auto;

    Here's a snippet:

    select[multiple] {_x000D_
      overflow-y: auto;_x000D_
      <option value="1">One</option>_x000D_
      <option value="2">Two</option>_x000D_
      <option value="3">Three</option>_x000D_
    <select multiple size="3">_x000D_
      <option value="1">One</option>_x000D_
      <option value="2">Two</option>_x000D_
      <option value="3">Three</option>_x000D_

    Play audio as microphone input

    Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

    I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

    If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

    How to change font size in a textbox in html

    For a <input type='text'> element:

    input { font-size: 18px; }

    or for a <textarea>:

    textarea { font-size: 18px; }

    or for a <select>:

    select { font-size: 18px; }

    you get the drift.

    From ND to 1D arrays

    Although this isn't using the np array format, (to lazy to modify my code) this should do what you want... If, you truly want a column vector you will want to transpose the vector result. It all depends on how you are planning to use this.

    def getVector(data_array,col):
        vector = []
        imax = len(data_array)
        for i in range(imax):
        return ( vector )
    a = ([1,2,3], [4,5,6])
    b = getVector(a,1)

    So if you need to transpose, you can do something like this:

    def transposeArray(data_array):
        # need to test if this is a 1D array 
        # can't do a len(data_array[0]) if it's 1D
        two_d = True
        if isinstance(data_array[0], list):
            dimx = len(data_array[0])
            dimx = 1
            two_d = False
        dimy = len(data_array)
        # init output transposed array
        data_array_t = [[0 for row in range(dimx)] for col in range(dimy)]
        # fill output transposed array
        for i in range(dimx):
            for j in range(dimy):
                if two_d:
                    data_array_t[j][i] = data_array[i][j]
                    data_array_t[j][i] = data_array[j]
        return data_array_t

    No mapping found for HTTP request with URI Spring MVC


    change to:


    scrollable div inside container

    I created an enhanced version, based on Trey Copland's fiddle, that I think is more like what you wanted. Added here for future reference to those who come here later. Fiddle example

    .modal {
      height: 390px;
      border: 5px solid green;
    .heading {
      padding: 10px;
    .content {
      height: 300px;
      border: 5px solid red;
    .scrollable {
      height: 1200px;
      border: 5px solid yellow;
    .footer {
      height: 2em;
      padding: .5em;
          <div class="modal">
              <div class="heading">
              <div class="content">
                  <div class="scrollable" >hello</div>
              <div class="footer">

    How to disable or enable viewpager swiping in android

    If you want to extend it just because you need Not-Swipeable behaviour, you dont need to do it. ViewPager2 provides nice property called : isUserInputEnabled

    Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

    Just finished a 2 hour wild goose chase trying to solve this. None of the posted answers worked for me. Im on a Mac (Mojave Version 10.14.6, Xcode Version 11.3).

    It turns out the ruby file headers were missing so i had to run open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

    That didnt work for me at first because the version of CommandLineTools i had installed did not have the "Packages" folder. So i uninstalled and reinstalled like this:

    rm -rf /Library/Developer/CommandLineTools

    xcode-select --install

    Then i ran the previous command again:

    open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

    After install the error was fixed!

    Ambiguous overload call to abs(double)

    Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

    Hope this helps anyone who is having the same problem!

    How to parseInt in Angular.js

    Inside template this working finely.

    <!DOCTYPE html>
    <script src=""></script>
    <div ng-app="">
    <input ng-model="name" value="0">
    <p>My first expression: {{ (name-0) + 5 }}</p>

    How can I make XSLT work in chrome?

    I tried putting the file in the wwwroot. So when accessing the page in Chrome, this is the address localhost/yourpage.xml.

    How to position the Button exactly in CSS

    So, the trick here is to use absolute positioning calc like this:

    top: calc(50% - XYpx);
    left: calc(50% - XYpx);

    where XYpx is half the size of your image, in my case, the image was a square. Of course, in this now obsolete case, the image must also change its size proportionally in response to window resize to be able to remain at the center without looking out of proportion.

    Http Get using Android HttpURLConnection

    Try getting the input stream from this you can then get the text data as so:-

        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL("");
            urlConnection = (HttpURLConnection) url
            InputStream in = urlConnection.getInputStream();
            InputStreamReader isw = new InputStreamReader(in);
            int data =;
            while (data != -1) {
                char current = (char) data;
                data =;
        } catch (Exception e) {
        } finally {
            if (urlConnection != null) {

    You can probably use other inputstream readers such as buffered reader also.

    The problem is that when you open the connection - it does not 'pull' any data.

    Loading custom functions in PowerShell

    You have to dot source them:

    . .\build_funtions.ps1
    . .\build_builddefs.ps1

    Note the extra .

    This heyscriptingguy article should be of help - How to Reuse Windows PowerShell Functions in Scripts

    Hashmap holding different data types as values for instance Integer, String and Object

    Create an object holding following properties with an appropriate name.

    1. message
    2. timestamp
    3. count
    4. version

    and use this as a value in your map.

    Also consider overriding the equals() and hashCode() method accordingly if you do not want object equality to be used for comparison (e.g. when inserting values into your map).

    Page Redirect after X seconds wait using JavaScript

    It looks you are almost there. Try:

    if(error == true){
        // Your application has indicated there's an error
            // Move to a new location or you can do something else
            window.location.href = "";
        }, 5000);

    How can I read and parse CSV files in C++?

    As all the CSV questions seem to get redirected here, I thought I'd post my answer here. This answer does not directly address the asker's question. I wanted to be able to read in a stream that is known to be in CSV format, and also the types of each field was already known. Of course, the method below could be used to treat every field to be a string type.

    As an example of how I wanted to be able to use a CSV input stream, consider the following input (taken from wikipedia's page on CSV):

    const char input[] =
    "1997,Ford,E350,\"ac, abs, moon\",3000.00\n"
    "1999,Chevy,\"Venture \"\"Extended Edition\"\"\",\"\",4900.00\n"
    "1999,Chevy,\"Venture \"\"Extended Edition, Very Large\"\"\",\"\",5000.00\n"
    "1996,Jeep,Grand Cherokee,\"MUST SELL!\n\
    air, moon roof, loaded\",4799.00\n"

    Then, I wanted to be able to read in the data like this:

    std::istringstream ss(input);
    std::string title[5];
    int year;
    std::string make, model, desc;
    float price;
        >> title[0] >> title[1] >> title[2] >> title[3] >> title[4];
    while (csv_istream(ss)
           >> year >> make >> model >> desc >> price) {
        // something with the record...

    This was the solution I ended up with.

    struct csv_istream {
        std::istream &is_;
        csv_istream (std::istream &is) : is_(is) {}
        void scan_ws () const {
            while (is_.good()) {
                int c = is_.peek();
                if (c != ' ' && c != '\t') break;
        void scan (std::string *s = 0) const {
            std::string ws;
            int c = is_.get();
            if (is_.good()) {
                do {
                    if (c == ',' || c == '\n') break;
                    if (s) {
                        ws += c;
                        if (c != ' ' && c != '\t') {
                            *s += ws;
                    c = is_.get();
                } while (is_.good());
                if (is_.eof()) is_.clear();
        template <typename T, bool> struct set_value {
            void operator () (std::string in, T &v) const {
                std::istringstream(in) >> v;
        template <typename T> struct set_value<T, true> {
            template <bool SIGNED> void convert (std::string in, T &v) const {
                if (SIGNED) v = ::strtoll(in.c_str(), 0, 0);
                else v = ::strtoull(in.c_str(), 0, 0);
            void operator () (std::string in, T &v) const {
                convert<is_signed_int<T>::val>(in, v);
        template <typename T> const csv_istream & operator >> (T &v) const {
            std::string tmp;
            set_value<T, is_int<T>::val>()(tmp, v);
            return *this;
        const csv_istream & operator >> (std::string &v) const {
            if (is_.peek() != '"') scan(&v);
            else {
                std::string tmp;
                std::getline(is_, tmp, '"');
                while (is_.peek() == '"') {
                    v += tmp;
                    v += is_.get();
                    std::getline(is_, tmp, '"');
                v += tmp;
            return *this;
        template <typename T>
        const csv_istream & operator >> (T &(*manip)(T &)) const {
            is_ >> manip;
            return *this;
        operator bool () const { return !; }

    With the following helpers that may be simplified by the new integral traits templates in C++11:

    template <typename T> struct is_signed_int { enum { val = false }; };
    template <> struct is_signed_int<short> { enum { val = true}; };
    template <> struct is_signed_int<int> { enum { val = true}; };
    template <> struct is_signed_int<long> { enum { val = true}; };
    template <> struct is_signed_int<long long> { enum { val = true}; };
    template <typename T> struct is_unsigned_int { enum { val = false }; };
    template <> struct is_unsigned_int<unsigned short> { enum { val = true}; };
    template <> struct is_unsigned_int<unsigned int> { enum { val = true}; };
    template <> struct is_unsigned_int<unsigned long> { enum { val = true}; };
    template <> struct is_unsigned_int<unsigned long long> { enum { val = true}; };
    template <typename T> struct is_int {
        enum { val = (is_signed_int<T>::val || is_unsigned_int<T>::val) };

    Try it online!

    How do I check if a number is a palindrome?

    Below is the answer in swift. It reads number from left and right side and compare them if they are same. Doing this way we will never face a problem of integer overflow (which can occure on reversing number method) as we are not creating another number.


    1. Get length of number
    2. Loop from length + 1(first) --> 0
    3. Get ith digit & get last digit
    4. if both digits are not equal return false as number is not palindrome
    5. i --
    6. discard last digit from num (num = num / 10)
    7. end of loo return true

      func isPalindrom(_ input: Int) -> Bool {
             if input < 0 {
                  return false
              if input < 10 {
                  return true
              var num = input
              let length = Int(log10(Float(input))) + 1
              var i = length
              while i > 0 && num > 0 {
                  let ithDigit = (input / Int(pow(10.0, Double(i) - 1.0)) ) % 10
                  let r = Int(num % 10)
                  if ithDigit != r {
                      return false
                  num = num / 10
                  i -= 1
              return true

    Blue and Purple Default links, how to remove?

    By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-

    For example color is: #000

    a:visited, a:hover, a:focus {
        text-decoration: none;
        color: #000;

    If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code

       a:hover {
            color: red;
        a:visited {
            color: green;
        a:focus {
            color: yellow;

    NB: good practice is to use color code.

    Android Center text on canvas

    Align vertically is difficult because text descent and ascent happened, lots of guys used Paint.getTextBounds() to retrieve the TextWidth and TextHeight, but it doesn't make the text center very much. Here we can use Paint.measureText() to calculate the TextWidth, the TextHeight we simply do subtracting with descent and ascent, then we got the most approach TextSize, the following work is fairly easy for each other.

    // the Paint instance(should be assign as a field of class).
    Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    // the display area.
    Rect areaRect = new Rect(0, 0, 240, 60);
    // draw the background style (pure color or image)
    yourCanvas.drawRect(areaRect, mPaint);
    String pageTitle = "????";
    RectF bounds = new RectF(areaRect);
    // measure text width
    bounds.right = mPaint.measureText(pageTitle, 0, pageTitle.length());
    // measure text height
    bounds.bottom = mPaint.descent() - mPaint.ascent();
    bounds.left += (areaRect.width() - bounds.right) / 2.0f; += (areaRect.height() - bounds.bottom) / 2.0f;
    yourCanvas.drawText(pageTitle, bounds.left, - mPaint.ascent(), mPaint);

    screen shot by the code

    By the way, we highly recommend use RectF rather than Rect because the positions need more accurate values, in my experience, RectF done the top&bottom deviation just one pixel on xhdpi device, Rect would be two more.

    Git on Mac OS X v10.7 (Lion)

    It's part of Xcode. You'll need to reinstall the developer tools.

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

    Add an extension

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

    Then check if keyboard is present,

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

    Linq select objects in list where exists IN (A,B,C)

    NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

    So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

    // Filter the orders based on the order status
    var filteredOrders = from order in orders.Order
                         where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                         select order;

    It's the opposite to what you know from SQL this is why it is not so obvious.

    Of course, if you prefer fluent syntax here it is:

    var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));

    Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

    Passing struct to function

    You need to specify a type on person:

    void addStudent(struct student person) {

    Also, you can typedef your struct to avoid having to type struct every time you use it:

    typedef struct student{
    } student_t;
    void addStudent(student_t person) {

    Clear and reset form input fields

    Why not use HTML-controlled items such as <input type="reset">

    Javascript switch vs. if...else if...else

    Other than syntax, a switch can be implemented using a tree which makes it O(log n), while a if/else has to be implemented with an O(n) procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?

    Create a <ul> and fill it based on a passed array

    What are disadvantages of the following solution? Seems to be faster and shorter.

    var options = {
        set0: ['Option 1','Option 2'],
        set1: ['First Option','Second Option','Third Option']
    var list = "<li>" + options.set0.join("</li><li>") + "</li>";
    document.getElementById("list").innerHTML = list;

    List all virtualenv

    For conda created env use:

    conda info --envs  # or 
    conda info -e      # or 
    conda env list 

    For virtualenvwrapper created env use:


    Override devise registrations controller

    In your form are you passing in any other attributes, via mass assignment that don't belong to your user model, or any of the nested models?

    If so, I believe the ActiveRecord::UnknownAttributeError is triggered in this instance.

    Otherwise, I think you can just create your own controller, by generating something like this:

    # app/controllers/registrations_controller.rb
    class RegistrationsController < Devise::RegistrationsController
      def new
      def create
        # add custom create logic here
      def update

    And then tell devise to use that controller instead of the default with:

    # app/config/routes.rb
    devise_for :users, :controllers => {:registrations => "registrations"}

    php Replacing multiple spaces with a single space

    $output = preg_replace('/\s+/', ' ',$input);

    \s is shorthand for [ \t\n\r]. Multiple spaces will be replaced with single space.

    How to view the current heap size that an application is using?

    Personal favourite for when jvisualvm is overkill or you need cli-only: jvmtop

    JvmTop 0.8.0 alpha   amd64  8 cpus, Linux 2.6.32-27, load avg 0.12
    3370 rapperSimpleApp  165m  455m  109m  176m  0.12%  0.00% S6U37 web        21
    11272 ver.resin.Resin [ERROR: Could not attach to VM]
    27338 WatchdogManager   11m   28m   23m  130m  0.00%  0.00% S6U37 web        31
    19187 m.jvmtop.JvmTop   20m 3544m   13m  130m  0.93%  0.47% S6U37 web        20
    16733 artup.Bootstrap  159m  455m  166m  304m  0.12%  0.00% S6U37 web        46

    NULL vs nullptr (Why was it replaced?)

    You can find a good explanation of why it was replaced by reading A name for the null pointer: nullptr, to quote the paper:

    This problem falls into the following categories:

    • Improve support for library building, by providing a way for users to write less ambiguous code, so that over time library writers will not need to worry about overloading on integral and pointer types.

    • Improve support for generic programming, by making it easier to express both integer 0 and nullptr unambiguously.

    • Make C++ easier to teach and learn.

    get the selected index value of <select> tag in php

    Your form is valid. Only thing that comes to my mind is, after seeing your full html, is that you're passing your "default" value (which is not set!) instead of selecting something. Try as suggested by @Vina in the comment, i.e. giving it a selected option, or writing a default value

    <select name="gender">
    <option value="default">Select </option>    
    <option value="male">   Male   </option>
    <option value="female"> Female </option>


    <select name="gender">
    <option value="male" selected="selected">   Male   </option>
    <option value="female"> Female </option>

    When you get your $_POST vars, check for them being set; you can assign a default value, or just an empty string in case they're not there.

    Most important thing, AVOID SQL INJECTIONS:

    $fname   = isset($_POST["fname"]) ? mysql_real_escape_string($_POST['fname']) : '';
    $lname   = isset($_POST['lname']) ? mysql_real_escape_string($_POST['lname']) : '';
    $email   = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : '';
    you might also want to validate e-mail:
    if($mail = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
      $email = mysql_real_escape_string($_POST['email']);
      //die ('invalid email address');
      // or whatever, a default value? $email = '';
    $paswod  = isset($_POST["paswod"]) ? mysql_real_escape_string($_POST['paswod']) : '';
    $gender  = isset($_POST['gender']) ? mysql_real_escape_string($_POST['gender']) : '';
    $query = mysql_query("SELECT Email FROM users WHERE Email = '".$email."')";
    if(mysql_num_rows($query)> 0)
      echo 'userid is already there';
     $sql = "INSERT INTO users (FirstName, LastName, Email, Password, Gender)
             VALUES ('".$fname."','".$lname."','".$email."','".paswod."','".$gender."')";
    $res = mysql_query($sql) or die('Error:'.mysql_error());
    echo 'created';

    How to get first N number of elements from an array

    arr.length = n

    This might be surprising but length property of an array is not only used to get number of array elements but it's also writable and can be used to set array's length MDN link. This will mutate the array.

    If you don't care about immutability or don't want to allocate memory i.e. for a game this will be the fastest way.

    to empty an array

    arr.length = 0

    Share link on Google+

    No, you cannot. Google Plus has been discontinued. Clicking any link for any answer here brings me to this text:

    Google+ is no longer available for consumer (personal) and brand accounts

    From all of us on the Google+ team,

    thank you for making Google+ such a special place.

    There is one section that reads that the product is continued for "G Suite," but as of Feb., 2020, the chat and social service listed for G Suite is Hangouts, not Google+.

    The format was documented at, but this documentation has since been removed, probably because no part of Google+ continues in development. If you are feeling nostalgic, you can see what the API used to say with an link.

    org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

    This seems to be an issue with local Maven repository. (i.e. .m2 folder) may be due to some corrupt .jar file

    For me, the following actions helped to overcome this issue.

    1. On my local file system, I've deleted the directory .m2 (Maven local repository)

    2. In Eclipse, updated the project (select Maven > Update Project)

    3. Ran the app again on Tomcat server.

    Rails 3 execute custom sql query without a model

    How about this :

    @client =
          :adapter => 'mysql2',
          :host => 'host',
          :database => 'siteconfig_development',
          :username => 'username',
          :password => 'password'
    sql = "SELECT * FROM users"
    result = @client.execute(sql)
    results.each do |row|
    puts row[0]

    You need to have TinyTds gem installed, since you didn't specify it in your question I didn't use Active Record

    How to represent the double quotes character (") in regex?

    you need to use backslash before ". like \"

    From the doc here you can see that

    A character preceded by a backslash ( \ ) is an escape sequence and has special meaning to the compiler.

    and " (double quote) is a escacpe sequence

    When an escape sequence is encountered in a print statement, the compiler interprets it accordingly. For example, if you want to put quotes within quotes you must use the escape sequence, \", on the interior quotes. To print the sentence

    She said "Hello!" to me.

    you would write

    System.out.println("She said \"Hello!\" to me.");

    Convert Mat to Array/Vector in OpenCV

    If the memory of the Mat mat is continuous (all its data is continuous), you can directly get its data to a 1D array:

    std::vector<uchar> array(mat.rows*mat.cols*mat.channels());
    if (mat.isContinuous())
        array =;

    Otherwise, you have to get its data row by row, e.g. to a 2D array:

    uchar **array = new uchar*[mat.rows];
    for (int i=0; i<mat.rows; ++i)
        array[i] = new uchar[mat.cols*mat.channels()];
    for (int i=0; i<mat.rows; ++i)
        array[i] = mat.ptr<uchar>(i);

    UPDATE: It will be easier if you're using std::vector, where you can do like this:

    std::vector<uchar> array;
    if (mat.isContinuous()) {
      // array.assign(mat.datastart, mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
      array.assign(, +*mat.channels());
    } else {
      for (int i = 0; i < mat.rows; ++i) {
        array.insert(array.end(), mat.ptr<uchar>(i), mat.ptr<uchar>(i)+mat.cols*mat.channels());

    p.s.: For cv::Mats of other types, like CV_32F, you should do like this:

    std::vector<float> array;
    if (mat.isContinuous()) {
      // array.assign((float*)mat.datastart, (float*)mat.dataend); // <- has problems for sub-matrix like mat = big_mat.row(i)
      array.assign((float*), (float*) +*mat.channels());
    } else {
      for (int i = 0; i < mat.rows; ++i) {
        array.insert(array.end(), mat.ptr<float>(i), mat.ptr<float>(i)+mat.cols*mat.channels());

    UPDATE2: For OpenCV Mat data continuity, it can be summarized as follows:

    • Matrices created by imread(), clone(), or a constructor will always be continuous.
    • The only time a matrix will not be continuous is when it borrows data (except the data borrowed is continuous in the big matrix, e.g. 1. single row; 2. multiple rows with full original width) from an existing matrix (i.e. created out of an ROI of a big mat).

    Please check out this code snippet for demonstration.

    GridView Hide Column by code

    Since you want to hide your column you can always hide the column in preRender event of the gridview . This helps you with reducing one operation for every rowdatabound event per row . You will need only one operation for prerender event .

    protected void gvVoucherList_PreRender(object sender, EventArgs e)
                int RoleID = Convert.ToInt32(Session["RoleID"]);
                switch (RoleID)
                    case 6: gvVoucherList.Columns[11].Visible = false;
                    case 1: gvVoucherList.Columns[10].Visible = false;
                if(hideActionColumn == "ActionSM")
                    gvVoucherList.Columns[10].Visible = false;
                    hideActionColumn = string.Empty;
            catch (Exception Ex)

    Youtube API Limitations

    Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 10,000 units per day. Projects that had enabled the YouTube Data API before April 20, 2016, have a default quota of 50M/day.

    You can read about what a unit is here:

    • A simple read operation that only retrieves the ID of each returned resource has a cost of approximately 1 unit.
    • A write operation has a cost of approximately 50 units.
    • A video upload has a cost of approximately 1600 units.

    If you hit the limits, Google will stop returning results until your quota is reset. You can apply for more than 1M requests per day, but you will have to pay for those extra requests.

    Also, you can read about why Google has deferred support to StackOverflow on their YouTube blog here:

    There are a number of active members on the YouTube Developer Relations team here including Jeff Posnick, Jarek Wilkiewicz, and Ibrahim Ulukaya who all have knowledge of Youtube internals...

    UPDATE: Increased the quota numbers to reflect current limits on December 10, 2013.

    UPDATE: Decreased the quota numbers from 50M to 1M per day to reflect current limits on May 13, 2016.

    UPDATE: Decreased the quota numbers from 1M to 10K per day as of January 11, 2019.

    jQuery: How can I show an image popup onclick of the thumbnail?

    I like prettyPhoto

    prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox Remote host closed connection during handshake during web service communicaiton

    I ran into a similar issue and found I was hitting the wrong port. After fixing the port things worked great.

    JPA & Criteria API - Select only specific columns

    One of the JPA ways for getting only particular columns is to ask for a Tuple object.

    In your case you would need to write something like this:

    CriteriaQuery<Tuple> cq = builder.createTupleQuery();
    // write the Root, Path elements as usual
    Root<EntityClazz> root = cq.from(EntityClazz.class);
    cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
    List<Tuple> tupleResult = em.createQuery(cq).getResultList();
    for (Tuple t : tupleResult) {
        Long id = (Long) t.get(0);
        Long version = (Long) t.get(1);

    Another approach is possible if you have a class representing the result, like T in your case. T doesn't need to be an Entity class. If T has a constructor like:

    public T(Long id, Long version)

    then you can use T directly in your CriteriaQuery constructor:

    CriteriaQuery<T> cq = builder.createQuery(T.class);
    // write the Root, Path elements as usual
    Root<EntityClazz> root = cq.from(EntityClazz.class);
    cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
    List<T> result = em.createQuery(cq).getResultList();

    See this link for further reference.

    Select distinct values from a large DataTable column

    Try this:

    var idColumn="id";
    var list = dt.DefaultView
        .ToTable(true, idColumn)
        .Select(row => row[idColumn])

    Element implicitly has an 'any' type because expression of type 'string' can't be used to index

    This is what it worked for me. The tsconfig.json has an option noImplicitAny that it was set to true, I just simply set it to false and now I can access properties in objects using strings.

    How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

    maybe useful for somebody, I got next problem on windows 8, apache 2.4, php 7+.

    php.ini conf>

    php on apache works ok but on cli problem with libs loading, as a result, I changed to


    How to convert color code into media.brush?

    For simplicity you could create an extension:-

        public static SolidColorBrush ToSolidColorBrush(this string hex_code)
            return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);

    And then to use:-

     SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();

    How to Load an Assembly to AppDomain with all references recursively?

    It took me a while to understand @user1996230's answer so I decided to provide a more explicit example. In the below example I make a proxy for an object loaded in another AppDomain and call a method on that object from another domain.

    class ProxyObject : MarshalByRefObject
        private Type _type;
        private Object _object;
        public void InstantiateObject(string AssemblyPath, string typeName, object[] args)
            assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + AssemblyPath); //LoadFrom loads dependent DLLs (assuming they are in the app domain's base directory
            _type = assembly.GetType(typeName);
            _object = Activator.CreateInstance(_type, args); ;
        public void InvokeMethod(string methodName, object[] args)
            var methodinfo = _type.GetMethod(methodName);
            methodinfo.Invoke(_object, args);
    static void Main(string[] args)
        AppDomainSetup setup = new AppDomainSetup();
        setup.ApplicationBase = @"SomePathWithDLLs";
        AppDomain domain = AppDomain.CreateDomain("MyDomain", null, setup);
        ProxyObject proxyObject = (ProxyObject)domain.CreateInstanceFromAndUnwrap(typeof(ProxyObject).Assembly.Location,"ProxyObject");
        proxyObject.InstantiateObject("SomeDLL","SomeType", new object[] { "someArgs});
        proxyObject.InvokeMethod("foo",new object[] { "bar"});

    jQuery CSS Opacity

    Try this:

    jQuery('#main').css('opacity', '0.6');


    jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});

    if you want to support IE7, IE8 and so on.

    How to add message box with 'OK' button?

    I think there may be problem that you haven't added click listener for ok positive button.

        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              //dismiss the dialog  

    Execute Immediate within a stored procedure keeps giving insufficient priviliges error

    you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.

    Set SSH connection timeout

    The ConnectTimeout option allows you to tell your ssh client how long you're willing to wait for a connection before returning an error. By setting ConnectTimeout to 1, you're effectively saying "try for at most 1 second and then fail if you haven't connected yet".

    The problem is that when you connect by name, the DNS lookup can take several seconds. Connecting by IP address is much faster, and may actually work in one second or less. What sinelaw is experiencing is that every attempt to connect by DNS name is failing to occur within one second. The default setting of ConnectTimeout defers to the linux kernel connect timeout, which is usually pretty long.

    Where can I find Android source code online?

    gitweb will allow you to browse through the code (and changes) via a browser.

    (Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)

    Correlation between two vectors?

    For correlations you can just use the corr function (statistics toolbox)

    corr(A_1(:), A_2(:))

    Note that you can also just use

    corr(A_1, A_2)

    But the linear indexing guarantees that your vectors don't need to be transposed.

    Adding new column to existing DataFrame in Python pandas

    this is a special case of adding a new column to a pandas dataframe. Here, I am adding a new feature/column based on an existing column data of the dataframe.

    so, let our dataFrame has columns 'feature_1', 'feature_2', 'probability_score' and we have to add a new_column 'predicted_class' based on data in column 'probability_score'.

    I will use map() function from python and also define a function of my own which will implement the logic on how to give a particular class_label to every row in my dataFrame.

    data = pd.read_csv('data.csv')
    def myFunction(x):
       //implement your logic here
       if so and so:
            return a
       return b
    variable_1 = data['probability_score']
    predicted_class =
    data['predicted_class'] = predicted_class
    // check dataFrame, new column is included based on an existing column data for each row

    Is Xamarin free in Visual Studio 2015?

    Visual Studio 2015 does include Xamarin Starter edition

    Xamarin Starter is free and allows developers to build and publish simple apps with the following limitations:

    • Contain no more than 128k of compiled user code (IL)
    • Do NOT call out to native third party libraries (i.e., developers may not P/Invoke into C/C++/Objective-C/Java)
    • Built using Xamarin.iOS / Xamarin.Android (NOT Xamarin.Forms)

    Xamarin Starter installs automatically with Visual Studio 2015, and works with VS 2012, 2013, and 2015 (including Community Editions). When your app outgrows Starter, you will be offered the opportunity to upgrade to a paid subscription, which you can learn more about here:

    Select a random sample of results from a query result

    Suppose you are trying to select exactly 1,000 random rows from a table called my_table. This is one way to do it:

                row_number() over(order by dbms_random.value) as random_id,
                my_table x
        random_id <= 1000

    This is a slight deviation from the answer posted by @Quassnoi. They both have the same costs and execution times. The only difference is that you can select the random number used to fetch the sample.

    Javascript "Cannot read property 'length' of undefined" when checking a variable's length

    If you aren't doing some kind of numeric comparison of the length property, it's better not to use it in the if statement, just do:

       // do stuff
      // do other stuff

    An empty (or undefined, as it is in this case) string will evaluate to false (just like a length of zero would.)

    Send array with Ajax to PHP script

    dataString suggests the data is formatted in a string (and maybe delimted by a character).

    $data = explode(",", $_POST['data']);
    foreach($data as $d){
         echo $d;

    if dataString is not a string but infact an array (what your question indicates) use JSON.

    Curly braces in string in PHP

    This is the complex (curly) syntax for string interpolation. From the manual:

    Complex (curly) syntax

    This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

    Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

    // Show all errors
    $great = 'fantastic';
    // Won't work, outputs: This is { fantastic}
    echo "This is { $great}";
    // Works, outputs: This is fantastic
    echo "This is {$great}";
    echo "This is ${great}";
    // Works
    echo "This square is {$square->width}00 centimeters broad."; 
    // Works, quoted keys only work using the curly brace syntax
    echo "This works: {$arr['key']}";
    // Works
    echo "This works: {$arr[4][3]}";
    // This is wrong for the same reason as $foo[bar] is wrong  outside a string.
    // In other words, it will still work, but only because PHP first looks for a
    // constant named foo; an error of level E_NOTICE (undefined constant) will be
    // thrown.
    echo "This is wrong: {$arr[foo][3]}"; 
    // Works. When using multi-dimensional arrays, always use braces around arrays
    // when inside of strings
    echo "This works: {$arr['foo'][3]}";
    // Works.
    echo "This works: " . $arr['foo'][3];
    echo "This works too: {$obj->values[3]->name}";
    echo "This is the value of the var named $name: {${$name}}";
    echo "This is the value of the var named by the return value of getName(): {${getName()}}";
    echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
    // Won't work, outputs: This is the return value of getName(): {getName()}
    echo "This is the return value of getName(): {getName()}";

    Often, this syntax is unnecessary. For example, this:

    $a = 'abcd';
    $out = "$a $a"; // "abcd abcd";

    behaves exactly the same as this:

    $out = "{$a} {$a}"; // same

    So the curly braces are unnecessary. But this:

    $out = "$aefgh";

    will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

    $out = "${a}efgh"; // or
    $out = "{$a}efgh";

    What are all the possible values for HTTP "Content-Type" header?

    If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

    Spring Rest POST Json RequestBody Content type not supported

    Really! after spending 4 hours and insane debugging I found this very strange code at com.fasterxml.jackson.databind.deser.DeserializerCache

    if (deser == null) {
        try {
            deser = _createAndCacheValueDeserializer(ctxt, factory, type);
        } catch (Exception e) {
            return false;

    Ya, the problem was double setter.

    How can I get enum possible values in a MySQL database?

    You can parse the string as though it was a CSV (Comma Separated Value) string. PHP has a great build-in function called str_getcsv which converts a CSV string to an array.

    // This is an example to test with
    $enum_or_set = "'blond','brunette','redhead'";
    // Here is the parser
    $options = str_getcsv($enum_or_set, ',', "'");
    // Output the value

    This should give you something similar to the following:

        [0] => blond
        [1] => brunette
        [2] => redhead

    This method also allows you to have single quotes in your strings (notice the use of two single quotes):

    $enum_or_set = "'blond','brunette','red''head'";
        [0] => blond
        [1] => brunette
        [2] => red'head

    For more information on the str_getcsv function, check the PHP manual:

    How to set up ES cluster?

    It is usually handled automatically.

    If autodiscovery doesn't work. Edit the elastic search config file, by enabling unicast discovery

    Node 1: mycluster "node1"
        node.master: true true false [""]

    Node 2: mycluster "node2"
        node.master: false true false [""]

    and so on for node 3,4,5. Make node 1 master, and the rest only as data nodes.

    Edit: Please note that by ES rule, if you have N nodes, then by convention, N/2+1 nodes should be masters for fail-over mechanisms They may or may not be data nodes, though.

    Also, in case auto-discovery doesn't work, most probable reason is because the network doesn't allow it (and therefore disabled). If too many auto-discovery pings take place across multiple servers, the resources to manage those pings will prevent other services from running correctly.

    For ex, think of a 10,000 node cluster and all 10,000 nodes doing the auto-pings.

    Drop all tables whose names begin with a certain string

    I saw this post when I was looking for mysql statement to drop all WordPress tables based on @Xenph Yan here is what I did eventually:

    SELECT CONCAT(  'DROP TABLE `', TABLE_NAME,  '`;' ) AS query

    this will give you the set of drop queries for all tables begins with wp_

    How to use z-index in svg elements?

    You can use use.

    <svg xmlns="" viewBox="0 0 160 120">
            <g id="one">
                <circle fill="green" cx="100" cy="105" r="20" />
            <g id="two">
                <circle fill="orange" cx="100" cy="95" r="20" />
        <use xlink:href="#one" />

    The green circle appears on top.

    How to check if a file exists in Ansible?

      mypath: "/etc/file.txt"
      - name: checking the file exists
        command: touch file.txt
        when: mypath is not exists

    close fxml window by code, javafx

    Hide doesn't close the window, just put in visible mode. The best solution was:

    private void exitButtonOnAction(ActionEvent event){

    How to get all checked checkboxes

    In IE9+, Chrome or Firefox you can do:

    var checkedBoxes = document.querySelectorAll('input[name=mycheckboxes]:checked');

    What is Node.js?

    Q: The programming model is event driven, especially the way it handles I/O.

    Correct. It uses call-backs, so any request to access the file system would cause a request to be sent to the file system and then Node.js would start processing its next request. It would only worry about the I/O request once it gets a response back from the file system, at which time it will run the callback code. However, it is possible to make synchronous I/O requests (that is, blocking requests). It is up to the developer to choose between asynchronous (callbacks) or synchronous (waiting).

    Q: It uses JavaScript and the parser is V8.


    Q: It can be easily used to create concurrent server applications.

    Yes, although you'd need to hand-code quite a lot of JavaScript. It might be better to look at a framework, such as - which comes with full online documentation and a sample application.

    JNI converting jstring to char *

    Thanks Jason Rogers's answer first.

    In Android && cpp should be this:

    const char *nativeString = env->GetStringUTFChars(javaString, nullptr);
    // use your string
    env->ReleaseStringUTFChars(javaString, nativeString);

    Can fix this errors:

    1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

    2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

    3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

    4.add "env->DeleteLocalRef(nativeString);" at end.

    Android: Pass data(extras) to a fragment

    I prefer Serializable = no boilerplate code. For passing data to other Fragments or Activities the speed difference to a Parcelable does not matter.

    I would also always provide a helper method for a Fragment or Activity, this way you always know, what data has to be passed. Here an example for your ListMusicFragment:

    private static final String EXTRA_MUSIC_LIST = "music_list";
    public static ListMusicFragment createInstance(List<Music> music) {
        ListMusicFragment fragment = new ListMusicFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(EXTRA_MUSIC_LIST, music);
        return fragment;
    public View onCreateView(...) { 
        Bundle bundle = intent.getArguments();
        List<Music> musicList = (List<Music>)bundle.getSerializable(EXTRA_MUSIC_LIST);

    Convert Date/Time for given Timezone - java

    display date and time for all timezones

    import java.util.Calendar;
    import java.util.TimeZone;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    static final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ssZ";
    DateFormat dateFormat = new SimpleDateFormat(ISO8601);
    Calendar c = Calendar.getInstance();
    String formattedTime;
    for (String availableID : TimeZone.getAvailableIDs()) {
        formattedTime = dateFormat.format(c.getTime());
        System.out.println(formattedTime + " " + availableID);

    How to resolve : Can not find the tag library descriptor for ""

    You have to write as

    <%@taglib uri="" prefix="c"%>

    Make sure you have jstl-1.0 & standard.jar BOTH files are placed in a classpath

    SVN 405 Method Not Allowed

    This means that the folder/file that you are trying to put on svn already exists there. My advice is that before doing anything just right click on the folder/file and click on repo-browser. By doing this you will be able to see all the files/sub-folders etc that are already present on svn. If the required file/folder is not present on the svn then you just delete(after taking backup) the file that you you want to add and then run an update.

    Make function wait until element exists

    Another variation of Iftah

    var counter = 10;
    var checkExist = setInterval(function() {
      if ($('#the-canvas').length || counter === 0) {
        console.log("by bye!");
    }, 200);

    Just in case the element is never shown, so we don't check infinitely.

    How to query DATETIME field using only date in Microsoft SQL Server?

    -- Reverse the date format
    -- this false:
        select * from test where date = '28/10/2015'
    -- this true:
        select * from test where date = '2015/10/28'

    how to use sqltransaction in c#

    First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

    sqlCommand.Transaction = transaction;

    And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

    sqlCommand.CommandText = "select * from table1";
    sqlCommand.CommandText = "select * from table2";

    Query to list all users of a certain group

    For Active Directory users, an alternative way to do this would be -- assuming all your groups are stored in OU=Groups,DC=CorpDir,DC=QA,DC=CorpName -- to use the query (&(objectCategory=group)(CN=GroupCN)). This will work well for all groups with less than 1500 members. If you want to list all members of a large AD group, the same query will work, but you'll have to use ranged retrieval to fetch all the members, 1500 records at a time.

    The key to performing ranged retrievals is to specify the range in the attributes using this syntax: attribute;range=low-high. So to fetch all members of an AD Group with 3000 members, first run the above query asking for the member;range=0-1499 attribute to be returned, then for the member;range=1500-2999 attribute.

    How to pass a callback as a parameter into another function

    Yes of course, function are objects and can be passed, but of course you must declare it:

    function firstFunction(){
        //some code
        var callbackfunction = function(data){
           //do something with the data returned from the ajax request
        //a callback function is written for $.post() to execute

    an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).

    Recursive mkdir() system call on Unix

    There is not a system call to do it for you, unfortunately. I'm guessing that's because there isn't a way to have really well-defined semantics for what should happen in error cases. Should it leave the directories that have already been created? Delete them? What if the deletions fail? And so on...

    It is pretty easy to roll your own, however, and a quick google for 'recursive mkdir' turned up a number of solutions. Here's one that was near the top:

    static void _mkdir(const char *dir) {
            char tmp[256];
            char *p = NULL;
            size_t len;
            snprintf(tmp, sizeof(tmp),"%s",dir);
            len = strlen(tmp);
            if(tmp[len - 1] == '/')
                    tmp[len - 1] = 0;
            for(p = tmp + 1; *p; p++)
                    if(*p == '/') {
                            *p = 0;
                            mkdir(tmp, S_IRWXU);
                            *p = '/';
            mkdir(tmp, S_IRWXU);

    How to turn a vector into a matrix in R?

    Just use matrix:

    matrix(vec,nrow = 7,ncol = 7)

    One advantage of using matrix rather than simply altering the dimension attribute as Gavin points out, is that you can specify whether the matrix is filled by row or column using the byrow argument in matrix.

    Add Favicon with React and Webpack

    This worked for me:
    Add this in index.html (inside src folder along with favicon.ico)
    **<link rel="icon" href="/src/favicon.ico" type="image/x-icon" />**
    webpack.config.js is like:
     plugins: [new HtmlWebpackPlugin({`enter code here`
            template: './src/index.html'

    Tuples( or arrays ) as Dictionary keys in C#

    The good, clean, fast, easy and readable ways is:

    • generate equality members (Equals() and GetHashCode()) method for the current type. Tools like ReSharper not only creates the methods, but also generates the necessary code for an equality check and/or for calculating hash code. The generated code will be more optimal than Tuple realization.
    • just make a simple key class derived from a tuple.

    add something similar like this:

    public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
        public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }
        public TypeA DataA => Item1; 
        public TypeB DataB => Item2;
        public TypeC DataC => Item3;

    So you can use it with dictionary:

    var myDictinaryData = new Dictionary<myKey, string>()
        {new myKey(1, 2, 3), "data123"},
        {new myKey(4, 5, 6), "data456"},
        {new myKey(7, 8, 9), "data789"}
    • You also can use it in contracts
    • as a key for join or groupings in linq
    • going this way you never ever mistype order of Item1, Item2, Item3 ...
    • you no need to remember or look into to code to understand where to go to get something
    • no need to override IStructuralEquatable, IStructuralComparable, IComparable, ITuple they all alredy here

    A valid provisioning profile for this executable was not found for debug mode

    Changing the provisioning profile to automatic then running prompted Xcode to "fix" the issue. I then changed back to my original provisioning profile and everything worked fine.

    How to get a variable value if variable name is stored as string?

    You can use ${!a}:

    var1="this is the real value"
    echo "${!a}" # outputs 'this is the real value'

    This is an example of indirect parameter expansion:

    The basic form of parameter expansion is ${parameter}. The value of parameter is substituted.

    If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.

    Asyncio.gather vs asyncio.wait

    In addition to all the previous answers, I would like to tell about the different behavior of gather() and wait() in case they are cancelled.

    Gather cancellation

    If gather() is cancelled, all submitted awaitables (that have not completed yet) are also cancelled.

    Wait cancellation

    If the wait() task is cancelled, it simply throws an CancelledError and the waited tasks remain intact.

    Simple example:

    import asyncio
    async def task(arg):
        await asyncio.sleep(5)
        return arg
    async def cancel_waiting_task(work_task, waiting_task):
        await asyncio.sleep(2)
            await waiting_task
            print("Waiting done")
        except asyncio.CancelledError:
            print("Waiting task cancelled")
            res = await work_task
            print(f"Work result: {res}")
        except asyncio.CancelledError:
            print("Work task cancelled")
    async def main():
        work_task = asyncio.create_task(task("done"))
        waiting = asyncio.create_task(asyncio.wait({work_task}))
        await cancel_waiting_task(work_task, waiting)
        work_task = asyncio.create_task(task("done"))
        waiting = asyncio.gather(work_task)
        await cancel_waiting_task(work_task, waiting)


    Waiting task cancelled
    Work result: done
    Waiting task cancelled
    Work task cancelled

    Sometimes it becomes necessary to combine wait() and gather() functionality. For example, we want to wait for the completion of at least one task and cancel the rest pending tasks after that, and if the waiting itself was canceled, then also cancel all pending tasks.

    As real examples, let's say we have a disconnect event and a work task. And we want to wait for the results of the work task, but if the connection was lost, then cancel it. Or we will make several parallel requests, but upon completion of at least one response, cancel all others.

    It could be done this way:

    import asyncio
    from typing import Optional, Tuple, Set
    async def wait_any(
            tasks: Set[asyncio.Future], *, timeout: Optional[int] = None,
    ) -> Tuple[Set[asyncio.Future], Set[asyncio.Future]]:
        tasks_to_cancel: Set[asyncio.Future] = set()
            done, tasks_to_cancel = await asyncio.wait(
                tasks, timeout=timeout, return_when=asyncio.FIRST_COMPLETED
            return done, tasks_to_cancel
        except asyncio.CancelledError:
            tasks_to_cancel = tasks
            for task in tasks_to_cancel:
    async def task():
        await asyncio.sleep(5)
    async def cancel_waiting_task(work_task, waiting_task):
        await asyncio.sleep(2)
            await waiting_task
            print("Waiting done")
        except asyncio.CancelledError:
            print("Waiting task cancelled")
            res = await work_task
            print(f"Work result: {res}")
        except asyncio.CancelledError:
            print("Work task cancelled")
    async def check_tasks(waiting_task, working_task, waiting_conn_lost_task):
            await waiting_task
            print("waiting is done")
        except asyncio.CancelledError:
            print("waiting is cancelled")
            await waiting_conn_lost_task
            print("connection is lost")
        except asyncio.CancelledError:
            print("waiting connection lost is cancelled")
            await working_task
            print("work is done")
        except asyncio.CancelledError:
            print("work is cancelled")
    async def work_done_case():
        working_task = asyncio.create_task(task())
        connection_lost_event = asyncio.Event()
        waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
        waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
        await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
    async def conn_lost_case():
        working_task = asyncio.create_task(task())
        connection_lost_event = asyncio.Event()
        waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
        waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
        await asyncio.sleep(2)
        connection_lost_event.set()  # <---
        await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
    async def cancel_waiting_case():
        working_task = asyncio.create_task(task())
        connection_lost_event = asyncio.Event()
        waiting_conn_lost_task = asyncio.create_task(connection_lost_event.wait())
        waiting_task = asyncio.create_task(wait_any({working_task, waiting_conn_lost_task}))
        await asyncio.sleep(2)
        waiting_task.cancel()  # <---
        await check_tasks(waiting_task, working_task, waiting_conn_lost_task)
    async def main():
        print("Work done")
        await work_done_case()
        print("\nConnection lost")
        await conn_lost_case()
        print("\nCancel waiting")
        await cancel_waiting_case()


    Work done
    waiting is done
    waiting connection lost is cancelled
    work is done
    Connection lost
    waiting is done
    connection is lost
    work is cancelled
    Cancel waiting
    waiting is cancelled
    waiting connection lost is cancelled
    work is cancelled

    How do I search within an array of hashes by hash values in ruby?

    if your array looks like

    array = [
     {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
     {:name => "John" , :age => 26 , :place => "xtz"} ,
     {:name => "Anil" , :age => 26 , :place => "xsz"} 

    And you Want To know if some value is already present in your array. Use Find Method

    array.find {|x| x[:name] == "Hitesh"}

    This will return object if Hitesh is present in name otherwise return nil

    What is the best project structure for a Python application?

    This blog post by Jean-Paul Calderone is commonly given as an answer in #python on Freenode.

    Filesystem structure of a Python project


    • name the directory something related to your project. For example, if your project is named "Twisted", name the top-level directory for its source files Twisted. When you do releases, you should include a version number suffix: Twisted-2.5.
    • create a directory Twisted/bin and put your executables there, if you have any. Don't give them a .py extension, even if they are Python source files. Don't put any code in them except an import of and call to a main function defined somewhere else in your projects. (Slight wrinkle: since on Windows, the interpreter is selected by the file extension, your Windows users actually do want the .py extension. So, when you package for Windows, you may want to add it. Unfortunately there's no easy distutils trick that I know of to automate this process. Considering that on POSIX the .py extension is a only a wart, whereas on Windows the lack is an actual bug, if your userbase includes Windows users, you may want to opt to just have the .py extension everywhere.)
    • If your project is expressable as a single Python source file, then put it into the directory and name it something related to your project. For example, Twisted/ If you need multiple source files, create a package instead (Twisted/twisted/, with an empty Twisted/twisted/ and place your source files in it. For example, Twisted/twisted/
    • put your unit tests in a sub-package of your package (note - this means that the single Python source file option above was a trick - you always need at least one other file for your unit tests). For example, Twisted/twisted/test/. Of course, make it a package with Twisted/twisted/test/ Place tests in files like Twisted/twisted/test/
    • add Twisted/README and Twisted/ to explain and install your software, respectively, if you're feeling nice.


    • put your source in a directory called src or lib. This makes it hard to run without installing.
    • put your tests outside of your Python package. This makes it hard to run the tests against an installed version.
    • create a package that only has a and then put all your code into Just make a module instead of a package, it's simpler.
    • try to come up with magical hacks to make Python able to import your module or package without having the user add the directory containing it to their import path (either via PYTHONPATH or some other mechanism). You will not correctly handle all cases and users will get angry at you when your software doesn't work in their environment.

    What is the keyguard in Android?

    In a nutshell, it is your lockscreen.

    PIN, pattern, face, password locks or the default lock (slide to unlock), but it is your lock screen.

    Context.startForegroundService() did not then call Service.startForeground()

    Ok, something I noticed on this that might help a few others too. This is strictly from testing to see if I could figure out how to fix the occurrences I am seeing. For simplicity sake, let's say I have a method that calls this from the presenter.

    context.startForegroundService(new Intent(context, TaskQueueExecutorService.class));
    try {
    } catch (InterruptedException e) {

    This will crash with the same error. The Service will NOT start until the method is complete, therefore no onCreate() in the service.

    So even if you update the UI off the main thread, IF you have anything that might hold up that method after it, it won't start on time and give you the dreaded Foreground Error. In my case we were loading some things onto a queue and each called startForegroundService, but some logic was involved with each in the background. So if the logic took too long to finish that method since they were called back to back, crash time. The old startService just ignored it and went on it's way and since we called it each time, the next round would finish up.

    This left me wondering, if I called the service from a thread in the background, could it not be fully bound on the start and run immediately, so I started experimenting. Even though this does NOT start it immediately, it does not crash.

    new Handler(Looper.getMainLooper()).post(new Runnable() {
            public void run() {
                   context.startForegroundService(new Intent(context, 
                   try {
                   } catch (InterruptedException e) {

    I will not pretend to know why it does not crash although I suspect this forces it to wait until the main thread can handle it in a timely fashion. I know it's not ideal to tie it to the main thread, but since my usage calls it in the background, I'm not real concerned if it waits until it can complete rather than crash.

    Difference between .keystore file and .jks file

    One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

    Compile to a stand-alone executable (.exe) in Visual Studio

    If I understand you correctly, yes you can, but not under Visual Studio (from what I know). To force the compiler to generate a real, standalone executable (which means you use C# like any other language) you use the program mkbundle (shipped with Mono). This will compile your C# app into a real, no dependency executable.

    There is a lot of misconceptions about this around the internet. It does not defeat the purpose of the .net framework like some people state, because how can you lose future features of the .net framework if you havent used these features to begin with? And when you ship updates to your app, it's not exactly hard work to run it through the mkbundle processor before building your installer. There is also a speed benefit involved making your app run at native speed (because now it IS native).

    In C++ or Delphi you have the same system, but without the middle MSIL layer. So if you use a namespace or sourcefile (called a unit under Delphi), then it's compiled and included in your final binary. So your final binary will be larger (Read: "Normal" size for a real app). The same goes for the parts of the framework you use in .net, these are also included in your app. However, smart linking does shave a conciderable amount.

    Hope it helps!

    Replacing all non-alphanumeric characters with empty strings

    If you want to also allow alphanumeric characters which don't belong to the ascii characters set, like for instance german umlaut's, you can consider using the following solution:

     String value = "your value";
     // this could be placed as a static final constant, so the compiling is only done once
     Pattern pattern = Pattern.compile("[^\\w]", Pattern.UNICODE_CHARACTER_CLASS);
     value = pattern.matcher(value).replaceAll("");

    Please note that the usage of the UNICODE_CHARACTER_CLASS flag could have an impose on performance penalty (see javadoc of this flag)

    What is &amp used for

    HTML doesn't recognize the & but it will recognize &amp; because it is equal to & in HTML

    I looked over this post someone had made:

    How can I concatenate two arrays in Java?

    I've recently fought problems with excessive memory rotation. If a and/or b are known to be commonly empty, here is another adaption of silvertab's code (generified too):

    private static <T> T[] concatOrReturnSame(T[] a, T[] b) {
        final int alen = a.length;
        final int blen = b.length;
        if (alen == 0) {
            return b;
        if (blen == 0) {
            return a;
        final T[] result = (T[]) java.lang.reflect.Array.
                newInstance(a.getClass().getComponentType(), alen + blen);
        System.arraycopy(a, 0, result, 0, alen);
        System.arraycopy(b, 0, result, alen, blen);
        return result;

    Edit: A previous version of this post stated that array re-usage like this shall be clearly documented. As Maarten points out in the comments it would in general be better to just remove the if statements, thus voiding the need for having documentation. But then again, those if statements were the whole point of this particular optimization in the first place. I'll leave this answer here, but be wary!

    Check file uploaded is in csv format

    There are a lot of possible MIME types for CSV files, depending on the user's OS and browser version.

    This is how I currently validate the MIME types of my CSV files:

    $csv_mimetypes = array(
    if (in_array($_FILES['upload']['type'], $csv_mimetypes)) {
        // possible CSV file
        // could also check for file content at this point

    angular 2 ngIf and CSS transition/animation

    One way is to use a setter for the ngIf property and set the state as part of updating the value.

    StackBlitz example


     import {
      } from '@angular/animations';
      import { ChangeDetectionStrategy, Component, Input } from '@angular/core';
      export type FadeState = 'visible' | 'hidden';
        selector: 'app-fade',
        templateUrl: './fade.component.html',
        styleUrls: ['./fade.component.scss'],
        animations: [
          trigger('state', [
                opacity: '1'
                opacity: '0'
            transition('* => visible', [animate('500ms ease-out')]),
            transition('visible => hidden', [animate('500ms ease-out')])
        changeDetection: ChangeDetectionStrategy.OnPush
      export class FadeComponent {
        state: FadeState;
        // tslint:disable-next-line: variable-name
        private _show: boolean;
        get show() {
          return this._show;
        set show(value: boolean) {
          if (value) {
            this._show = value;
            this.state = 'visible';
          } else {
            this.state = 'hidden';
        animationDone(event: AnimationEvent) {
          if (event.fromState === 'visible' && event.toState === 'hidden') {
            this._show = false;


        <button mat-raised-button color="primary">test</button>


    :host {
      display: block;
    .fade {
      opacity: 0;

    How to include libraries in Visual Studio 2012?

    Typically you need to do 5 things to include a library in your project:

    1) Add #include statements necessary files with declarations/interfaces, e.g.:

    #include "library.h"

    2) Add an include directory for the compiler to look into

    -> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)

    3) Add a library directory for *.lib files:

    -> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)

    4) Link the lib's *.lib files

    -> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;

    5) Place *.dll files either:

    -> in the directory you'll be opening your final executable from or into Windows/system32

    Input placeholders for Internet Explorer

    After trying some suggestions and seeing issues in IE here is the one that works:

    What I have liked - you just include the js file. No need to initiate it or anything.

    How to analyze disk usage of a Docker container

    The volume part did not work anymore so if anyone is insterested I just change the above script a little bit:

    for d in `docker ps | awk '{print $1}' | tail -n +2`; do
        d_name=`docker inspect -f {{.Name}} $d`
        echo "========================================================="
        echo "$d_name ($d) container size:"
        sudo du -d 2 -h /var/lib/docker/aufs | grep `docker inspect -f "{{.Id}}" $d`
        echo "$d_name ($d) volumes:"
        for mount in `docker inspect -f "{{range .Mounts}} {{.Source}}:{{.Destination}}                                                                                                                                                      
        {{end}}" $d`; do
            size=`echo $mount | cut -d':' -f1 | sudo xargs du -d 0 -h`
            mnt=`echo $mount | cut -d':' -f2`
            echo "$size mounted on $mnt"

    Difference between null and empty ("") Java String

    String s=null;

    String is not initialized for null. if any string operation tried it can throw null pointer exception

    String t="null";

    It is a string literal with value string "null" same like t = "xyz". It will not throw null pointer.

    String u="";

    It is as empty string , It will not throw null pointer.

    Get environment value in controller

    In the book of Matt Stauffer he suggest to create an array in your config/app.php to add the variable and then anywhere you reference to it with:

    $myvariable = new Namearray(config('fileWhichContainsVariable.array.ConfigKeyVariable'))

    Have try this solution? is good ?

    How to get file path from OpenFileDialog and FolderBrowserDialog?

    Create this class as Extension:

    public static class Extensiones
        public static string FolderName(this OpenFileDialog ofd)
                string resp = "";
                resp = ofd.FileName.Substring(0, 3);
                var final = ofd.FileName.Substring(3);
                var info = final.Split('\\');
                for (int i = 0; i < info.Length - 1; i++)
                    resp += info[i] + "\\";
                return resp;

    Then, you could use in this way:

            //ofdSource is an OpenFileDialog 
            if (ofdSource.ShowDialog(this) == DialogResult.OK)

    javascript regular expression to check for IP addresses

    If you are using nodejs try:


    doc net.isIP()

    How do I write a batch script that copies one directory to another, replaces old files?

    It seems that the latest function for this in windows 7 is robocopy.

    Usage example:

    robocopy <source> <destination> /e /xf <file to exclude> <another file>

    /e copies subdirectories including empty ones, /xf excludes certain files from being copied.

    More options here:

    How to find substring inside a string (or how to grep a variable)?

    You can use "index" if you only want to find a single character, e.g.:

    LIST="server1 server2 server3 server4 server5"
    if expr index "$LIST" "$SOURCE"; then
        echo "match"
        exit -1
        echo "no match"

    Output is:


    Date format in the json output using spring boot

    If you have Jackson integeration with your application to serialize your bean to JSON format, then you can use Jackson anotation @JsonFormat to format your date to specified format.
    In your case if you need your date into yyyy-MM-dd format you need to specify @JsonFormat above your field on which you want to apply this format.

    For Example :

    public class Subject {
         private String uid;
         private String number;
         private String initials;
         private Date dateOfBirth;  
         //Other Code  

    From Docs :

    annotation used for configuring details of how values of properties are to be serialized.

    More Reference Doc

    Hope this helps.

    C# "internal" access modifier when doing unit testing

    I'm using .NET Core 3.1.101 and the .csproj additions that worked for me were:

      <!-- Explicitly generate Assembly Info -->
      <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute">

    Parse query string into an array

    You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.

    $get_string = "pg_id=2&parent_id=2&document&video";
    parse_str($get_string, $get_array);

    Hiding the address bar of a browser (popup)

    What is the truth?

    Microsoft's documentation describing the behaviour of their browser is correct.

    Is there any solution to hide the addressbar?

    No. If you could hide it, then you could use HTML/CSS to make something that looked like a common address bar. You could then put a different address in it. You could then trick people into thinking they were on a different site and entering their password for it.

    It is impossible to conceal the user's location from them because it is essential for security that they know what their location is.

    Difference between if () { } and if () : endif;

    I used to use the curly braces but now a days I prefer to use this short-hand alternative syntax because of code readability and accessibility.

    Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

    Right click on the server, then Add/Remove, then remove any projects that are in the Configured panel. Then right click on the server and choose "Clean..." from the context menu. Then the Server Locations option will be enabled.

    What is a NullPointerException, and how do I fix it?

    A null pointer exception is an indicator that you are using an object without initializing it.

    For example, below is a student class which will use it in our code.

    public class Student {
        private int id;
        public int getId() {
        public setId(int newId) {
   = newId;

    The below code gives you a null pointer exception.

    public class School {
        Student student;
        public School() {
            try {
            catch(Exception e) {
                System.out.println("Null pointer exception");

    Because you are using student, but you forgot to initialize it like in the correct code shown below:

    public class School {
        Student student;
        public School() {
            try {
                student = new Student();
            catch(Exception e) {
                System.out.println("Null pointer exception");

    Maximum Length of Command Line String

    As @Sugrue I'm also digging out an old thread.

    To explain why there is 32768 (I think it should be 32767, but lets believe experimental testing result) characters limitation we need to dig into Windows API.

    No matter how you launch program with command line arguments it goes to ShellExecute, CreateProcess or any extended their version. These APIs basically wrap other NT level API that are not officially documented. As far as I know these calls wrap NtCreateProcess, which requires OBJECT_ATTRIBUTES structure as a parameter, to create that structure InitializeObjectAttributes is used. In this place we see UNICODE_STRING. So now lets take a look into this structure:

    typedef struct _UNICODE_STRING {
        USHORT Length;
        USHORT MaximumLength;
        PWSTR  Buffer;

    It uses USHORT (16-bit length [0; 65535]) variable to store length. And according this, length indicates size in bytes, not characters. So we have: 65535 / 2 = 32767 (because WCHAR is 2 bytes long).

    There are a few steps to dig into this number, but I hope it is clear.

    Also, to support @sunetos answer what is accepted. 8191 is a maximum number allowed to be entered into cmd.exe, if you exceed this limit, The input line is too long. error is generated. So, answer is correct despite the fact that cmd.exe is not the only way to pass arguments for new process.

    How to assign name for a screen?

    The easiest way use screen with name

    screen -S 'name' 'application'
    • Ctrl+a, d = exit and leave application open

    Return to screen:

    screen -r 'name'

    for example using lynx with screen

    Create screen:

    screen -S lynx lynx

    Ctrl+a, d =exit

    later you can return with:

    screen -r lynx

    How do I get a Date without time in Java?

    What about this?

    public static Date formatStrictDate(int year, int month, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, dayOfMonth, 0, 0, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTime();