Programs & Examples On #Yard

YARD stands for "Yay! A Ruby Documentation tool". It is considered an alternative to the rdoc tool with more features.

ES6 modules implementation, how to load a json file

With json-loader installed, now you can simply use:

import suburbs from '../suburbs.json';

or, even more simply:

import suburbs from '../suburbs';

How to use cURL to get jSON data and decode the data?

you can also use

$result = curl_exec($ch);
return response()->json(json_decode($result));

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

The existing answers are broadly accurate:

  • Heroku is very easy to use and deploy to, can be easily configured for auto-deployment a repository (eg GitHub), has lots of third party add-ons and charges more per instance.

  • AWS has a wider range of competitively priced first party services including DNS, load balancing, cheap file storage and has enterprise features like being able to define security policies.

For the tl;dr skip to the end of this post.

AWS ElasticBeanstalk is an attempt to provide a Heroku-like autoscaling and easy deployment platform. As it uses EC2 instances (which it creates automatically) EB servers can do everything any other EC2 instance can do and it's cheap to run.

Deployment with EB is very slow; deploying an update can take 10-15 minutes per server and deploying to a larger cluster can take the best part of an hour - compared to just seconds to deploy an update on Heroku. Deployments on EB are not handled particularly seamlessly either, which may impose constraints on application design.

You can use all the services ElasticBeanstalk uses behind the scenes to build your own bespoke system (with CodeDeploy, Elastic Load Balancer, Auto Scaling Groups - and CodeCommit, CodeBuild and CodePipeline if you want to go all in) but you can definitely spend a good couple of weeks setting it up the the first time as it's fairly convoluted and slightly tricker than just configuring things in EC2.

AWS Lightsail offers a competitively priced hosting option, but doesn't help with deployment or scaling - it's really just a wrapper for their EC2 offering (but costs much more). It lets you automatically run a bash script on initial setup, which is nice touch but it's pricy compared to the cost of just setting up an EC2 instance (which you can also do programmatically).

Some thoughts on comparing (to try and answer the questions, albeit in a roundabout way):

  1. Don't underestimate how much work system administration is, including keeping everything you have installed up to date with security patches (and occasional OS updates).

  2. Don't underestimate how much of a benefit automatic deployment, auto-scaling, and SSL provisioning and configuration are.

    Automatic deployment when you update your Git repository is effortless with Heroku. It is near instant, graceful so there are no outages for end users and can be set to update only if the tests / Continuous Integration passes so you don't break your site if you deploy broken code.

    You can also use ElasticBeanstalk for automatic deployment, but be prepared to spend a week setting that up the first time - you may have to change how you deploy and build assets (like CSS and JS) to work with how ElasticBeanstalk handles deployments or build logic into your app to handle deployments.

    Be aware in estimating costs that for seamless deployment with no outage on EB you need to run multiple instances - EB rolls out updates to each server individually so that your service is not degraded - where as Heroku spins up a new dyno for you and just deprecates the old service until all the requests to it are done being handled (then it deletes it).

    Interestingly, the hosting cost of running multiple servers with EB can be cheaper than a single Heroku instance, especially once you include the cost of add-ons.

Some other issues not specifically asked about, but raised by other answers:

  1. Using a different provider for production and development is a bad idea.

    I am cringing that people are suggesting this. While ideally code should run just fine on any reasonable platform so it's as portable as possible, versions of software on each host will vary greatly and just because code runs in staging doesn't mean it will run in production (e.g. major Node.js/Ruby/Python/PHP/Perl versions can differ in ways that make code incompatible, often in silent ways that might not be caught even if you have decent test coverage).

    What is a good idea is to leverage something like Heroku for prototyping, smaller projects and microsites - so you can build and deploy things quickly without investing a lot of time in configuration and maintenance.

    Be sure to factor in the cost of running both production and pre-production instances when making that decision, not forgetting the cost of replicating the entire environment (including third party services such as data stores / add ons, installing and configuring SSL, etc).

  2. If using AWS, be wary of AWS pre-configured instances from vendors like Bitnami - they are a security nightmare. They can expose lots of notoriously vulnerable applications by default without mentioning it in the description.

    Consider instead just using a well supported mainstream distribution, such as Ubuntu or Debian (or CentOS if you need RPM support).

    Note: Amazon offer have their own distribution called Amazon Linux, which uses RPM, but it's EC2 specific and less well supported by third party/open source software.

  3. You could also setup an EC2 instance on AWS (or Lightsail) and configure with something like flynn or dokku on it - on which you could then deploy multiple sites easily, which can be worth it if you maintain a lot of services or want to be able to spin up new things easily. However getting it set up is not as automagic as just using Heroku and you can end up spending a lot of time configuring and maintaining it (to the point I've found deploying using Amazon clustering and Docker Swarm to be easier than setting them up; YMMV).

I have used AWS EC instances (alone and in clusters), Elastic Beanstalk and Lightsail and Heroku at the same time depending on the needs of the project I'm working on.

I hate spending time configuring services but my Heroku bill would be thousands per year if I used it for everything and AWS works out a fraction of the cost.

tl;dr

If money was never an issue I'd use Heroku for almost everything as it's a huge timesaver - but I'd still want to use AWS for more complicated projects where I need the flexibility and more advanced services that Heroku doesn't offer.

The ideal scenario for me would be if ElasticBeanstalk just worked more like Heroku - i.e. with easier configuration and quicker and a better deployment mechanism.

An example of a service that is almost this is now.sh, which actually uses AWS behind the scenes, but makes deployments and clustering as easy as it is on Heroku (with automatic SSL, DNS, graceful deployments, super-easy cluster setup and management).

I've used it quite lot for both Node.js app and Docker image deployments, the major caveat is the instances are shared (something reflected in their lower cost) and currently no option to buy dedicated instances. However their open source deployment tool 'now' can also be used to deploy to dedicated instances on AWS as well as Google Cloud and Azure.

incompatible character encodings: ASCII-8BIT and UTF-8

you can force UTF8 with force_encoding(Encoding::UTF_8):

Example:

<%= yield.force_encoding(Encoding::UTF_8) %>

How do you implement a Stack and a Queue in JavaScript?

Arrays.

Stack:

var stack = [];

//put value on top of stack
stack.push(1);

//remove value from top of stack
var value = stack.pop();

Queue:

var queue = [];

//put value on end of queue
queue.push(1);

//Take first value from queue
var value = queue.shift();

How to print something to the console in Xcode?

In some environments, NSLog() will be unresponsive. But there are other ways to get output...

NSString* url = @"someurlstring";
printf("%s", [url UTF8String]);

By using printf with the appropriate parameters, we can display things this way. This is the only way I have found to work on online Objective-C sandbox environments.

mssql '5 (Access is denied.)' error during restoring database

I had exactly same problem but my fix was different - my company is encrypting all the files on my machines. After decrypting the file MSSQL did not have any issues to accessing and created the DB. Just right click .bak file -> Properties -> Advanced... -> Encrypt contents to secure data. Decrypting

How can I get a user's media from Instagram without authenticating as a user?

JSFiddle

Javascript:

$(document).ready(function(){

    var username = "leomessi";
    var max_num_items = 5;

    var jqxhr = $.ajax( "https://www.instagram.com/"+username+"/?__a=1" ).done(function() {
        //alert( "success" );
    }).fail(function() {
        //alert( "error" );
    }).always(function(data) {
        //alert( "complete" )
        items = data.graphql.user.edge_owner_to_timeline_media.edges;
        $.each(items, function(n, item) {
            if( (n+1) <= max_num_items )
            {
                var data_li = "<li><a target='_blank' href='https://www.instagram.com/p/"+item.node.shortcode+"'><img src='" + item.node.thumbnail_src + "'/></a></li>";
                $("ul.instagram").append(data_li);
            }
        });

    });

});

HTML:

<ul class="instagram">
</ul>

CSS:

ul.instagram {
    list-style: none;
}

ul.instagram li {
  float: left;
}

ul.instagram li img {
    height: 100px;
}

can we use xpath with BeautifulSoup?

from lxml import etree
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('path of your localfile.html'),'html.parser')
dom = etree.HTML(str(soup))
print dom.xpath('//*[@id="BGINP01_S1"]/section/div/font/text()')

Above used the combination of Soup object with lxml and one can extract the value using xpath

jQuery AutoComplete Trigger Change Event

They are binding to keydown in the autocomplete source, so triggering the keydown will case it to update.

$("#CompanyList").trigger('keydown');

They aren't binding to the 'change' event because that only triggers at the DOM level when the form field loses focus. The autocomplete needs to respond faster than 'lost focus' so it has to bind to a key event.

Doing this:

companyList.autocomplete('option','change').call(companyList);

Will cause a bug if the user retypes the exact option that was there before.

Choosing line type and color in Gnuplot 4.0

You might want to look at the Pyxplot plotting package http://pyxplot.org.uk which has very similar syntax to gnuplot, but with the rough edges cleaned up. It handles colors and line styles quite neatly, and homogeneously between x11 and eps/pdf terminals.

The Pyxplot script for what you want to do above would be:

set style 1 lt 1 lw 3 color red
set style 2 lt 1 lw 3 color blue
set style 3 lt 2 lw 3 color red
set style 4 lt 2 lw 3 color blue
plot 'data1.dat' using 1:3 w l style 1,\
  'data1.dat' using 1:4 w l style 2,\
  'data2.dat' using 1:3 w l style 3,\
  'data2.dat' using 1:4 w l style 4`

Android Studio - mergeDebugResources exception

inside your project directory, run:

./gradlew clean build

or from Android Studio select:

Build > Clean Project

Updated: As @VinceFior pointed out in a comment below

How to run iPhone emulator WITHOUT starting Xcode?

As the multitude of answers indicate, there are lots of different ways to address this issue. Not all of them address what is my number one issue, and what seems to be the asker's priority, as well: The ability to launch from Spotlight.

Here's the solution that works well for me, and should work with any OS X and XCode versions. I've tested it on OS X 10.11 and XCode 7.3.

Initial setup does require launching XCode, but after that, you won't need to just to get to the Simulator.

Setup

  1. Launch XCode
  2. From the XCode menu, select Open Developer Tool > Simulator
  3. In the dock, control (or right) click on the Simulator icon
  4. Select Options > Show in Finder
  5. While holding down Command and Option, drag the Simulator icon to the applications directory. This creates an alias to it.
  6. If desired, rename the alias from "Simulator" to "iOS Simulator". Whatever you name it is what it will show up as in Spotlight.

Note: There are other ways to get to the location of the Simulator app (steps 1-4), such as using Go to Folder… in the Finder, but those require knowing the location of the Simulator to begin with. Since that has changed from version to version of XCode, this way should work regardless of these changes.

Use

  1. Launch Spotlight (command-space, etc.)
  2. Type "simulator" or "ios" (if you renamed the alias).
  3. If necessary, use the down arrow to scroll to the Simulator alias. Eventually, spotlight should learn and make the alias the top choice so you can skip this step.
  4. Hit return

Spring Security exclude url patterns in security annotation configurartion

specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"

http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().

What does [object Object] mean? (JavaScript)

Alerts aren't the best for displaying objects. Try console.log? If you still see Object Object in the console, use JSON.parse like this > var obj = JSON.parse(yourObject); console.log(obj)

to remove first and last element in array

_x000D_
_x000D_
var fruits = ["Banana", "Orange", "Apple", "Mango"];_x000D_
var newFruits = fruits.slice(1, -1);_x000D_
console.log(newFruits); //  ["Orange", "Apple"];
_x000D_
_x000D_
_x000D_

Here, -1 denotes the last element in an array and 1 denotes the second element.

How to Import .bson file format on mongodb

It's very simple to import a .bson file:

mongorestore -d db_name -c collection_name /path/file.bson

Incase only for a single collection.Try this:

mongorestore --drop -d db_name -c collection_name /path/file.bson

For restoring the complete folder exported by mongodump:

mongorestore -d db_name /path/

html <input type="text" /> onchange event not working

use following events instead of "onchange"

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

Java Round up Any Number

Math.ceil() is the correct function to call. I'm guessing a is an int, which would make a / 100 perform integer arithmetic. Try Math.ceil(a / 100.0) instead.

int a = 142;
System.out.println(a / 100);
System.out.println(Math.ceil(a / 100));
System.out.println(a / 100.0);
System.out.println(Math.ceil(a / 100.0));
System.out.println((int) Math.ceil(a / 100.0));

Outputs:

1
1.0
1.42
2.0
2

See http://ideone.com/yhT0l

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Globally catch exceptions in a WPF application?

Here is complete example using NLog

using NLog;
using System;
using System.Windows;

namespace MyApp
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Logger logger = LogManager.GetCurrentClassLogger();

        public App()
        {
            var currentDomain = AppDomain.CurrentDomain;
            currentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var ex = (Exception)e.ExceptionObject;
            logger.Error("UnhandledException caught : " + ex.Message);
            logger.Error("UnhandledException StackTrace : " + ex.StackTrace);
            logger.Fatal("Runtime terminating: {0}", e.IsTerminating);
        }        
    }


}

Cleanest way to toggle a boolean variable in Java?

There are several

The "obvious" way (for most people)

theBoolean = !theBoolean;

The "shortest" way (most of the time)

theBoolean ^= true;

The "most visual" way (most uncertainly)

theBoolean = theBoolean ? false : true;

Extra: Toggle and use in a method call

theMethod( theBoolean ^= true );

Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Android: why is there no maxHeight for a View?

I have an answer here:

https://stackoverflow.com/a/29178364/1148784

Just create a new class extending ScrollView and override it's onMeasure method.

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (maxHeight > 0){
            int hSize = MeasureSpec.getSize(heightMeasureSpec);
            int hMode = MeasureSpec.getMode(heightMeasureSpec);

            switch (hMode){
                case MeasureSpec.AT_MOST:
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.AT_MOST);
                    break;
                case MeasureSpec.UNSPECIFIED:
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);
                    break;
                case MeasureSpec.EXACTLY:
                    heightMeasureSpec = MeasureSpec.makeMeasureSpec(Math.min(hSize, maxHeight), MeasureSpec.EXACTLY);
                    break;
            }
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

The Import android.support.v7 cannot be resolved

I had the same issue every time I tried to create a new project, but based on the console output, it was because of two versions of android-support-v4 that were different:

[2014-10-29 16:31:57 - HeadphoneSplitter] Found 2 versions of android-support-v4.jar in the dependency list,
[2014-10-29 16:31:57 - HeadphoneSplitter] but not all the versions are identical (check is based on SHA-1 only at this time).
[2014-10-29 16:31:57 - HeadphoneSplitter] All versions of the libraries must be the same at this time.
[2014-10-29 16:31:57 - HeadphoneSplitter] Versions found are:
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\appcompat_v7\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter]   Length: 627582
[2014-10-29 16:31:57 - HeadphoneSplitter]   SHA-1: cb6883d96005bc85b3e868f204507ea5b4fa9bbf
[2014-10-29 16:31:57 - HeadphoneSplitter] Path: C:\Users\jbaurer\workspace\HeadphoneSplitter\libs\android-support-v4.jar
[2014-10-29 16:31:57 - HeadphoneSplitter]   Length: 758727
[2014-10-29 16:31:57 - HeadphoneSplitter]   SHA-1: efec67655f6db90757faa37201efcee2a9ec3507
[2014-10-29 16:31:57 - HeadphoneSplitter] Jar mismatch! Fix your dependencies

I don't know a lot about Eclipse. but I simply deleted the copy of the jar file from my project's libs folder so that it would use the appcompat_v7 jar file instead. This fixed my issue.

How to add manifest permission to an application?

When using eclipse, Follow these steps

1) Double click on the manifest to show it on the editor
2) Click on the permissions tab below the manifest editor
3) Click on Add button
4) on the dialog that appears Click uses permission. (Ussually the last item on the list)
5) Notice the view that appears on the rigth side Select "android.permission.INTERNET"
6) Then a series of Ok and finally save.

Hope this helps

word-wrap break-word does not work in this example

to get the smart break (break-word) work well on different browsers, what worked for me was the following set of rules:

#elm {
    word-break:break-word; /* webkit/blink browsers */
    word-wrap:break-word; /* ie */
}
-moz-document url-prefix() {/* catch ff */
    #elm {
        word-break: break-all; /* in ff-  with no break-word we'll settle for break-all */
    }
}

What does flex: 1 mean?

In Chrome Ver 84, flex: 1 is equivalent to flex: 1 1 0%. The followings are a bunch of screenshots.

enter image description here

Re-ordering factor levels in data frame

Assuming your dataframe is mydf:

mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))

Determine device (iPhone, iPod Touch) with iOS

Adding to Arash's code, I don't care for my app what model I'm using, I just want to know what kind of device, so, I can test as follows:

    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        {
            NSLog(@"I'm definitely an iPad");
    } else {
    NSString *deviceType = [UIDevice currentDevice].model;
                if([deviceType rangeOfString:@"iPhone"].location!=NSNotFound)
                {
                    NSLog(@"I must be an iPhone");

                } else {
                    NSLog(@"I think I'm an iPod");

                }
}

Simple two column html layout without using tables

You can create text columns with CSS Multiple Columns property. You don't need any table or multiple divs.

HTML

<div class="column">
       <!-- paragraph text comes here -->
</div> 

CSS

.column {
    column-count: 2;
    column-gap: 40px;
}

Read more about CSS Multiple Columns at https://www.w3schools.com/css/css3_multiple_columns.asp

How to set the initial zoom/width for a webview

I'm working with loading images for this answer and I want them to be scaled to the device's width. I find that, for older phones with versions less than API 19 (KitKat), the behavior for Brian's answer isn't quite as I like it. It puts a lot of whitespace around some images on older phones, but works on my newer one. Here is my alternative, with help from this answer: Can Android's WebView automatically resize huge images? The layout algorithm SINGLE_COLUMN is deprecated, but it works and I feel like it is appropriate for working with older webviews.

WebSettings settings = webView.getSettings();

// Image set to width of device. (Must be done differently for API < 19 (kitkat))
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
    if (!settings.getLayoutAlgorithm().equals(WebSettings.LayoutAlgorithm.SINGLE_COLUMN))
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
    if (!settings.getLoadWithOverviewMode()) settings.setLoadWithOverviewMode(true);
    if (!settings.getUseWideViewPort()) settings.setUseWideViewPort(true);
}

How to force Docker for a clean build of an image

The command docker build --no-cache . solved our similar problem.

Our Dockerfile was:

RUN apt-get update
RUN apt-get -y install php5-fpm

But should have been:

RUN apt-get update && apt-get -y install php5-fpm

To prevent caching the update and install separately.

See: Best practices for writing Dockerfiles

How to achieve ripple animation using support library?

sometimes will b usable this line on any layout or components.

 android:background="?attr/selectableItemBackground"

Like as.

 <RelativeLayout
                android:id="@+id/relative_ticket_checkin"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:background="?attr/selectableItemBackground">

PHP - check if variable is undefined

if(isset($variable)){
    $isTouch = $variable;
}

OR

if(!isset($variable)){
    $isTouch = "";// 
}

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How do you increase the max number of concurrent connections in Apache?

Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild

http://web.archive.org/web/20160415001028/http://www.genericarticles.com/mediawiki/index.php?title=How_to_optimize_apache_web_server_for_maximum_concurrent_connections_or_increase_max_clients_in_apache

ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25

First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers parameter. Then each process will start 25 threads determined by ThreadsPerChild parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients. This also means that if I set MaxClients to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient parameter. In this case, we need to also increase ServerLimit to 1000/25 i.e. MaxClients/ThreadsPerChild=40 So this is the optmized configuration to server 1000 clients

<IfModule mpm_worker_module>
    ServerLimit          40
    StartServers          2
    MaxClients          1000
    MinSpareThreads      25
    MaxSpareThreads      75 
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>

socket.error: [Errno 48] Address already in use

Just in case above solutions didn't work:

  1. Get the port your process is listening to:

    $ ps ax | grep python

  2. Kill the Process

    $ kill PROCESS_NAME

What's the maximum value for an int in PHP?

It subjects to architecture of the server on which PHP runs. For 64-bit,

print PHP_INT_MIN . ", ” . PHP_INT_MAX; yields -9223372036854775808, 9223372036854775807

Define css class in django Forms

If you want all the fields in the form to inherit a certain class, you just define a parent class, that inherits from forms.ModelForm, and then inherit from it

class BaseForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(BaseForm, self).__init__(*args, **kwargs)
        for field_name, field in self.fields.items():
            field.widget.attrs['class'] = 'someClass'


class WhateverForm(BaseForm):
    class Meta:
        model = SomeModel

This helped me to add the 'form-control' class to all of the fields on all of the forms of my application automatically, without adding replication of code.

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

the mremote option offers more automation and almost replicates the vmware workstation graphical experience plus major benefits: NO DPI (guest resolution) hassle no copy pose hassle Automation = starting vms and suspending them automatically plus more if you look deeper

On select change, get data attribute value

this works for me

<select class="form-control" id="foo">
    <option value="first" data-id="1">first</option>
    <option value="second" data-id="2">second</option>
</select>

and the script

$('#foo').on("change",function(){
    var dataid = $("#foo option:selected").attr('data-id');
    alert(dataid)
});

Sort array by value alphabetically php

asort() - Maintains key association: yes.

sort() - Maintains key association: no.

Source: http://php.net/manual/en/array.sorting.php

Check if a string is a valid Windows directory (folder) path

    private bool IsValidPath(string path)
    {
        Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
        if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
        string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
        strTheseAreInvalidFileNameChars += @":/?*" + "\"";
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
        if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            return false;

        DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
        if (!dir.Exists)
            dir.Create();
        return true;
    }

Duplicate keys in .NET dictionaries?

This is a tow way Concurrent dictionary I think this will help you:

public class HashMapDictionary<T1, T2> : System.Collections.IEnumerable
{
    private System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>> _keyValue = new System.Collections.Concurrent.ConcurrentDictionary<T1, List<T2>>();
    private System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>> _valueKey = new System.Collections.Concurrent.ConcurrentDictionary<T2, List<T1>>();

    public ICollection<T1> Keys
    {
        get
        {
            return _keyValue.Keys;
        }
    }

    public ICollection<T2> Values
    {
        get
        {
            return _valueKey.Keys;
        }
    }

    public int Count
    {
        get
        {
            return _keyValue.Count;
        }
    }

    public bool IsReadOnly
    {
        get
        {
            return false;
        }
    }

    public List<T2> this[T1 index]
    {
        get { return _keyValue[index]; }
        set { _keyValue[index] = value; }
    }

    public List<T1> this[T2 index]
    {
        get { return _valueKey[index]; }
        set { _valueKey[index] = value; }
    }

    public void Add(T1 key, T2 value)
    {
        lock (this)
        {
            if (!_keyValue.TryGetValue(key, out List<T2> result))
                _keyValue.TryAdd(key, new List<T2>() { value });
            else if (!result.Contains(value))
                result.Add(value);

            if (!_valueKey.TryGetValue(value, out List<T1> result2))
                _valueKey.TryAdd(value, new List<T1>() { key });
            else if (!result2.Contains(key))
                result2.Add(key);
        }
    }

    public bool TryGetValues(T1 key, out List<T2> value)
    {
        return _keyValue.TryGetValue(key, out value);
    }

    public bool TryGetKeys(T2 value, out List<T1> key)
    {
        return _valueKey.TryGetValue(value, out key);
    }

    public bool ContainsKey(T1 key)
    {
        return _keyValue.ContainsKey(key);
    }

    public bool ContainsValue(T2 value)
    {
        return _valueKey.ContainsKey(value);
    }

    public void Remove(T1 key)
    {
        lock (this)
        {
            if (_keyValue.TryRemove(key, out List<T2> values))
            {
                foreach (var item in values)
                {
                    var remove2 = _valueKey.TryRemove(item, out List<T1> keys);
                }
            }
        }
    }

    public void Remove(T2 value)
    {
        lock (this)
        {
            if (_valueKey.TryRemove(value, out List<T1> keys))
            {
                foreach (var item in keys)
                {
                    var remove2 = _keyValue.TryRemove(item, out List<T2> values);
                }
            }
        }
    }

    public void Clear()
    {
        _keyValue.Clear();
        _valueKey.Clear();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return _keyValue.GetEnumerator();
    }
}

examples:

public class TestA
{
    public int MyProperty { get; set; }
}

public class TestB
{
    public int MyProperty { get; set; }
}

            HashMapDictionary<TestA, TestB> hashMapDictionary = new HashMapDictionary<TestA, TestB>();

            var a = new TestA() { MyProperty = 9999 };
            var b = new TestB() { MyProperty = 60 };
            var b2 = new TestB() { MyProperty = 5 };
            hashMapDictionary.Add(a, b);
            hashMapDictionary.Add(a, b2);
            hashMapDictionary.TryGetValues(a, out List<TestB> result);
            foreach (var item in result)
            {
                //do something
            }

Getting unique values in Excel by using formulas only

Ok, I have two ideas for you. Hopefully one of them will get you where you need to go. Note that the first one ignores the request to do this as a formula since that solution is not pretty. I figured I make sure the easy way really wouldn't work for you ;^).

Use the Advanced Filter command

  1. Select the list (or put your selection anywhere inside the list and click ok if the dialog comes up complaining that Excel does not know if your list contains headers or not)
  2. Choose Data/Advanced Filter
  3. Choose either "Filter the list, in-place" or "Copy to another location"
  4. Click "Unique records only"
  5. Click ok
  6. You are done. A unique list is created either in place or at a new location. Note that you can record this action to create a one line VBA script to do this which could then possible be generalized to work in other situations for you (e.g. without the manual steps listed above).

Using Formulas (note that I'm building on Locksfree solution to end up with a list with no holes)

This solution will work with the following caveats:

  • The list must be sorted (ascending or descending does not matter). Actually that's quite accurate as the requirement is really that all like items must be contiguous but sorting is the easiest way to reach that state.
  • Three new columns are required (two new columns for calculations and one new column for the new list). The second and third columns could be combined but I'll leave that as an exercise to the reader.

    Here is the summary of the solution:

    1. For each item in the list, calculate the number of duplicates above it.
    2. For each place in the unique list, calculate the index of the next unique item.
    3. Finally, use the indexes to create a new list with only unique items.

    And here is a step by step example:

    1. Open a new spreadsheet
    2. In a1:a6 enter the example given in the original question ("red", "blue", "red", "green", "blue", "black")
    3. Sort the list: put the selection in the list and choose the sort command.
    4. In column B, calculate the duplicates:
      1. In B1, enter "=IF(COUNTIF($A$1:A1,A1) = 1,0,COUNTIF(A1:$A$6,A1))". Note that the "$" in the cell references are very important as it will make the next step (populating the rest of the column) much easier. The "$" indicates an absolute reference so that when the cell content is copy/pasted the reference will not update (as opposed to a relative reference which will update).
      2. Use smart copy to populate the rest of column B: Select B1. Move your mouse over the black square in the lower right hand corner of the selection. Click and drag down to the bottom of the list (B6). When you release, the formula will be copied into B2:B6 with the relative references updated.
      3. The value of B1:B6 should now be "0,0,1,0,0,1". Notice that the "1" entries indicate duplicates.
    5. In Column C, create an index of unique items:
      1. In C1, enter "=Row()". You really just want C1 = 1 but using Row() means this solution will work even if the list does not start in row 1.
      2. In C2, enter "=IF(C1+1<=ROW($B$6), C1+1+INDEX($B$1:$B$6,C1+1),C1+1)". The "if" is being used to stop a #REF from being produced when the index reaches the end of the list.
      3. Use smart copy to populate C3:C6.
      4. The value of C1:C6 should be "1,2,4,5,7,8"
    6. In column D, create the new unique list:
      1. In D1, enter "=IF(C1<=ROW($A$6), INDEX($A$1:$A$6,C1), "")". And, the "if" is being used to stop the #REF case when the index goes beyond the end of the list.
      2. Use smart copy to populate D2:D6.
      3. The values of D1:D6 should now be "black","blue","green","red","","".

    Hope this helps....

  • Update multiple rows using select statement

    Run a select to make sure it is what you want

    SELECT t1.value AS NEWVALUEFROMTABLE1,t2.value AS OLDVALUETABLE2,*
    FROM Table2 t2
    INNER JOIN Table1 t1 on t1.ID = t2.ID
    

    Update

    UPDATE Table2
    SET Value = t1.Value
    FROM Table2 t2
    INNER JOIN Table1 t1 on t1.ID = t2.ID
    

    Also, consider using BEGIN TRAN so you can roll it back if needed, but make sure you COMMIT it when you are satisfied.

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

    This code worked for me, it kills all existing connections of a database. All you have to do is change the line Set @dbname = 'databaseName' so it has your database name.

    Use Master
    Go
    
    Declare @dbname sysname
    
    Set @dbname = 'databaseName'
    
    Declare @spid int
    Select @spid = min(spid) from master.dbo.sysprocesses
    where dbid = db_id(@dbname)
    While @spid Is Not Null
    Begin
            Execute ('Kill ' + @spid)
            Select @spid = min(spid) from master.dbo.sysprocesses
            where dbid = db_id(@dbname) and spid > @spid
    End
    

    after this I was able to restore it

    Multiple try codes in one block

    Lets say each code is a function and its already written then the following can be used to iter through your coding list and exit the for-loop when a function is executed without error using the "break".

    def a(): code a
    def b(): code b
    def c(): code c
    def d(): code d
    
    for func in [a, b, c, d]:  # change list order to change execution order.
       try:
           func()
           break
       except Exception as err:
           print (err)
           continue
    

    I used "Exception " here so you can see any error printed. Turn-off the print if you know what to expect and you're not caring (e.g. in case the code returns two or three list items (i,j = msg.split('.')).

    How to include multiple js files using jQuery $.getScript() method

    This works for me:

    function getScripts(scripts) {
        var prArr = [];
        scripts.forEach(function(script) { 
            (function(script){
                prArr .push(new Promise(function(resolve){
                    $.getScript(script, function () {
                        resolve();
                    });
                }));
            })(script);
        });
        return Promise.all(prArr, function(){
            return true;
        });
    }
    

    And use it:

    var jsarr = ['script1.js','script2.js'];
    getScripts(jsarr).then(function(){
    ...
    });
    

    How to pipe list of files returned by find command to cat to view all the files

    Modern version

    POSIX 2008 added the + marker to find which means it now automatically groups as many files as are reasonable into a single command execution, very much like xargs does, but with a number of advantages:

    1. You don't have to worry about odd characters in the file names.
    2. You don't have to worry about the command being invoked with zero file names.

    The file name issue is a problem with xargs without the -0 option, and the 'run even with zero file names' issue is a problem with or without the -0 option — but GNU xargs has the -r or --no-run-if-empty option to prevent that happening. Also, this notation cuts down on the number of processes, not that you're likely to measure the difference in performance. Hence, you could sensibly write:

    find . -exec grep something {} +
    

    Classic version

    find . -print | xargs grep something
    

    If you're on Linux or have the GNU find and xargs commands, then use -print0 with find and -0 with xargs to handle file names containing spaces and other odd-ball characters.

    find . -print0 | xargs -0 grep something
    

    Tweaking the results from grep

    If you don't want the file names (just the text) then add an appropriate option to grep (usually -h to suppressing 'headings'). To absolutely guarantee the file name is printed by grep (even if only one file is found, or the last invocation of grep is only given 1 file name), then add /dev/null to the xargs command line, so that there will always be at least two file names.

    Maintaining href "open in new tab" with an onClick handler in React

    The answer from @gunn is correct, target="_blank makes the link open in a new tab.

    But this can be a security risk for you page; you can read about it here. There is a simple solution for that: adding rel="noopener noreferrer".

    <a style={{display: "table-cell"}} href = "someLink" target = "_blank" 
    rel = "noopener noreferrer">text</a>
    

    Unsigned keyword in C++

    Yes, it means unsigned int. It used to be that if you didn't specify a data type in C there were many places where it just assumed int. This was try, for example, of function return types.

    This wart has mostly been eradicated, but you are encountering its last vestiges here. IMHO, the code should be fixed to say unsigned int to avoid just the sort of confusion you are experiencing.

    Run a mySQL query as a cron job?

    It depends on what runs cron on your system, but all you have to do to run a php script from cron is to do call the location of the php installation followed by the script location. An example with crontab running every hour:

    # crontab -e
    00 * * * * /usr/local/bin/php /home/path/script.php
    

    On my system, I don't even have to put the path to the php installation:

    00 * * * * php /home/path/script.php
    

    On another note, you should not be using mysql extension because it is deprecated, unless you are using an older installation of php. Read here for a comparison.

    XPath selecting a node with some attribute value equals to some other node's attribute value

    I think this is what you want:

    /grand/parent/child[@id="#grand"]
    

    jQuery window scroll event does not fire up

    My issue was I had this code in my css

    html,
    body {
        height: 100%;
        width: 100%;
        overflow: auto;
    }
    

    Once I removed it, the scroll event on window fired again

    How to prevent text in a table cell from wrapping

    <th nowrap="nowrap">
    

    or

    <th style="white-space:nowrap;">
    

    or

    <th class="nowrap">
    <style type="text/css">
    .nowrap { white-space: nowrap; }
    </style>
    

    how to filter out a null value from spark dataframe

    A good solution for me was to drop the rows with any null values:

    Dataset<Row> filtered = df.filter(row => !row.anyNull);

    In case one is interested in the other case, just call row.anyNull. (Spark 2.1.0 using Java API)

    res.sendFile absolute path

    you can use send instead of sendFile so you wont face with error! this works will help you!

    fs.readFile('public/index1.html',(err,data)=>{
    if(err){
      consol.log(err);
    }else {
    res.setHeader('Content-Type', 'application/pdf');
    

    for telling browser that your response is type of PDF

    res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');
    

    if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.

    res.send(data)
    

    Picasso v/s Imageloader v/s Fresco vs Glide

    I am one of the engineers on the Fresco project. So obviously I'm biased.

    But you don't have to take my word for it. We've released a sample app that allows you to compare the performance of five libraries - Fresco, Picasso, UIL, Glide, and Volley Image Loader - side by side. You can get it at our GitHub repo.

    I should also point out that Fresco is available on Maven Central, as com.facebook.fresco:fresco.

    Fresco offers features that Picasso, UIL, and Glide do not yet have:

    1. Images aren't stored in the Java heap, but in the ashmem heap. Intermediate byte buffers are also stored in the native heap. This leaves a lot more memory available for applications to use. It reduces the risk of OutOfMemoryErrors. It also reduces the amount of garbage collection apps have to do, leading to better performance.
    2. Progressive JPEG images can be streamed, just like in a web browser.
    3. Images can be cropped around any point, not just the center.
    4. JPEG images can be resized natively. This avoids the problem of OOMing while trying to downsize an image.

    There are many others (see our documentation), but these are the most important.

    How do you overcome the svn 'out of date' error?

    In my case only deleting of the local version and re checkout of fresh copy was a solution.

    Python Unicode Encode Error

    Python 3.5, 2018

    If you don't know what the encoding but the unicode parser is having issues you can open the file in Notepad++ and in the top bar select Encoding->Convert to ANSI. Then you can write your python like this

    with open('filepath', 'r', encoding='ANSI') as file:
        for word in file.read().split():
            print(word)
    

    Origin is not allowed by Access-Control-Allow-Origin

    In Ruby Sinatra

    response['Access-Control-Allow-Origin'] = '*' 
    

    for everyone or

    response['Access-Control-Allow-Origin'] = 'http://yourdomain.name' 
    

    Regular expression to match a line that doesn't contain a word

    If you want to match a character to negate a word similar to negate character class:

    For example, a string:

    <?
    $str="aaa        bbb4      aaa     bbb7";
    ?>
    

    Do not use:

    <?
    preg_match('/aaa[^bbb]+?bbb7/s', $str, $matches);
    ?>
    

    Use:

    <?
    preg_match('/aaa(?:(?!bbb).)+?bbb7/s', $str, $matches);
    ?>
    

    Notice "(?!bbb)." is neither lookbehind nor lookahead, it's lookcurrent, for example:

    "(?=abc)abcde", "(?!abc)abcde"
    

    ASP.NET postback with JavaScript

    You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

    LINQ Aggregate algorithm explained

    Learned a lot from Jamiec's answer.

    If the only need is to generate CSV string, you may try this.

    var csv3 = string.Join(",",chars);
    

    Here is a test with 1 million strings

    0.28 seconds = Aggregate w/ String Builder 
    0.30 seconds = String.Join 
    

    Source code is here

    Using getline() with file input in C++

    you should do as:

    getline(name, sizeofname, '\n');
    strtok(name, " ");
    

    This will give you the "joht" in name then to get next token,

    temp = strtok(NULL, " ");
    

    temp will get "smith" in it. then you should use string concatination to append the temp at end of name. as:

    strcat(name, temp);
    

    (you may also append space first, to obtain a space in between).

    How to display HTML <FORM> as inline element?

    Just use the style float: left in this way:

    <p style="float: left"> Lorem Ipsum </p> 
    <form style="float: left">
       <input  type='submit'/>
    </form>
    <p style="float: left"> Lorem Ipsum </p>
    

    Spark java.lang.OutOfMemoryError: Java heap space

    You should configure offHeap memory settings as shown below:

    val spark = SparkSession
         .builder()
         .master("local[*]")
         .config("spark.executor.memory", "70g")
         .config("spark.driver.memory", "50g")
         .config("spark.memory.offHeap.enabled",true)
         .config("spark.memory.offHeap.size","16g")   
         .appName("sampleCodeForReference")
         .getOrCreate()
    

    Give the driver memory and executor memory as per your machines RAM availability. You can increase the offHeap size if you are still facing the OutofMemory issue.

    How can I get the name of an object in Python?

    As others have mentioned, this is a really tricky question. Solutions to this are not "one size fits all", not even remotely. The difficulty (or ease) is really going to depend on your situation.

    I have come to this problem on several occasions, but most recently while creating a debugging function. I wanted the function to take some unknown objects as arguments and print their declared names and contents. Getting the contents is easy of course, but the declared name is another story.

    What follows is some of what I have come up with.

    Return function name

    Determining the name of a function is really easy as it has the __name__ attribute containing the function's declared name.

    name_of_function = lambda x : x.__name__
    
    def name_of_function(arg):
        try:
            return arg.__name__
        except AttributeError:
            pass`
    

    Just as an example, if you create the function def test_function(): pass, then copy_function = test_function, then name_of_function(copy_function), it will return test_function.

    Return first matching object name

    1. Check whether the object has a __name__ attribute and return it if so (declared functions only). Note that you may remove this test as the name will still be in globals().

    2. Compare the value of arg with the values of items in globals() and return the name of the first match. Note that I am filtering out names starting with '_'.

    The result will consist of the name of the first matching object otherwise None.

    def name_of_object(arg):
        # check __name__ attribute (functions)
        try:
            return arg.__name__
        except AttributeError:
            pass
    
        for name, value in globals().items():
            if value is arg and not name.startswith('_'):
                return name
    

    Return all matching object names

    • Compare the value of arg with the values of items in globals() and store names in a list. Note that I am filtering out names starting with '_'.

    The result will consist of a list (for multiple matches), a string (for a single match), otherwise None. Of course you should adjust this behavior as needed.

    def names_of_object(arg):
        results = [n for n, v in globals().items() if v is arg and not n.startswith('_')]
        return results[0] if len(results) is 1 else results if results else None
    

    Ruby get object keys as array

    Like taro said, keys returns the array of keys of your Hash:

    http://ruby-doc.org/core-1.9.3/Hash.html#method-i-keys

    You'll find all the different methods available for each class.

    If you don't know what you're dealing with:

     puts my_unknown_variable.class.to_s
    

    This will output the class name.

    How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

    What worked for me - should really be moved to iPhone:

    Charles

    1. Enable transparent Http proxying
    2. Enable SSL proxying
    3. Right click on incoming request and select SSL proxying

    Mac

    1. Download Charles CA Certificate bundle http://www.charlesproxy.com/ssl.zip
    2. Email yourself charles-proxy-ssl-proxying-certificate.crt

    iPhone

    1. Enable http proxy for Charles on port 8888
    2. Select and install email attachment, yes trust it!

    Voila, you can now view encrypted traffic from the domain added in the SSL proxying

    Reading Excel file using node.js

    Useful link

    https://ciphertrick.com/read-excel-files-convert-json-node-js/

     var express = require('express'); 
        var app = express(); 
        var bodyParser = require('body-parser');
        var multer = require('multer');
        var xlstojson = require("xls-to-json-lc");
        var xlsxtojson = require("xlsx-to-json-lc");
        app.use(bodyParser.json());
        var storage = multer.diskStorage({ //multers disk storage settings
            destination: function (req, file, cb) {
                cb(null, './uploads/')
            },
            filename: function (req, file, cb) {
                var datetimestamp = Date.now();
                cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
            }
        });
        var upload = multer({ //multer settings
                        storage: storage,
                        fileFilter : function(req, file, callback) { //file filter
                            if (['xls', 'xlsx'].indexOf(file.originalname.split('.')[file.originalname.split('.').length-1]) === -1) {
                                return callback(new Error('Wrong extension type'));
                            }
                            callback(null, true);
                        }
                    }).single('file');
        /** API path that will upload the files */
        app.post('/upload', function(req, res) {
            var exceltojson;
            upload(req,res,function(err){
                if(err){
                     res.json({error_code:1,err_desc:err});
                     return;
                }
                /** Multer gives us file info in req.file object */
                if(!req.file){
                    res.json({error_code:1,err_desc:"No file passed"});
                    return;
                }
                /** Check the extension of the incoming file and 
                 *  use the appropriate module
                 */
                if(req.file.originalname.split('.')[req.file.originalname.split('.').length-1] === 'xlsx'){
                    exceltojson = xlsxtojson;
                } else {
                    exceltojson = xlstojson;
                }
                try {
                    exceltojson({
                        input: req.file.path,
                        output: null, //since we don't need output.json
                        lowerCaseHeaders:true
                    }, function(err,result){
                        if(err) {
                            return res.json({error_code:1,err_desc:err, data: null});
                        } 
                        res.json({error_code:0,err_desc:null, data: result});
                    });
                } catch (e){
                    res.json({error_code:1,err_desc:"Corupted excel file"});
                }
            })
        }); 
        app.get('/',function(req,res){
            res.sendFile(__dirname + "/index.html");
        });
        app.listen('3000', function(){
            console.log('running on 3000...');
        });
    

    An array of List in c#

    // The letter "t" is usually letter "i"//
    
        for(t=0;t<x[t];t++)
        {
    
             printf(" %2d          || %7d \n ",t,x[t]);
        }
    

    Renaming files in a folder to sequential numbers

    Sorted by time, limited to jpg, leading zeroes and a basename (in case you likely want one):

    ls -t *.jpg | cat -n |                                           \
    while read n f; do mv "$f" "$(printf thumb_%04d.jpg $n)"; done
    

    (all on one line, without the \)

    How to use UIScrollView in Storyboard

    Note that within a UITableView, you can actually scroll the tableview by selecting a cell or an element in it and scrolling up or down with your trackpad.

    For a UIScrollView, I like Alex's suggestion, but I would recommend temporarily changing the view controller to freeform, increasing the root view's height, building your UI (steps 1-5), and then changing it back to the standard inferred size when you are done so that you don't have to hard code content sizes in as runtime attributes. If you do that you are opening yourself up to a lot of maintenance issues trying to support both 3.5" and 4" devices, as well as the possibility of increased screen resolutions in the future.

    Center form submit buttons HTML / CSS

    Input elements are inline by default. Add display:block to get the margins to apply. This will, however, break the buttons onto two separate lines. Use a wrapping <div> with text-align: center as suggested by others to get them on the same line.

    Serving favicon.ico in ASP.NET MVC

    I think that favicon.ico should be in root folder. It just belongs there.

    If you want to servere diferent icons - put it into controler. You can do that. If not - just leave it in the root folder.

    How do I resolve the "java.net.BindException: Address already in use: JVM_Bind" error?

    Restart the PC once, I think it will work. It started working in my case. One more thing can be done go to Task Manager and End the process.

    Screenshot for the reference.

    How can I capture the right-click event in JavaScript?

    Use the oncontextmenu event.

    Here's an example:

    <div oncontextmenu="javascript:alert('success!');return false;">
        Lorem Ipsum
    </div>
    

    And using event listeners (credit to rampion from a comment in 2011):

    el.addEventListener('contextmenu', function(ev) {
        ev.preventDefault();
        alert('success!');
        return false;
    }, false);
    

    Don't forget to return false, otherwise the standard context menu will still pop up.

    If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

    Difference between Relative path and absolute path in javascript

    What is the difference between Relative path and absolute path?

    One has to be calculated with respect to another URI. The other does not.

    Is there any performance issues occures for using these paths?

    Nothing significant.

    We will get any secure for the sites ?

    No

    Is there any way to converting absolute path to relative

    In really simplified terms: Working from left to right, try to match the scheme, hostname, then path segments with the URI you are trying to be relative to. Stop when you have a match.

    How to install SignTool.exe for Windows 10

    April 28th 2020

    I found it here:

    C:\Program Files (x86)\Windows Kits\10\App Certification Kit
    

    Java8: sum values from specific field of the objects in a list

    Try:

    int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();
    

    How to use execvp()

    The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

    For example:

    char *cmd = "ls";
    char *argv[3];
    argv[0] = "ls";
    argv[1] = "-la";
    argv[2] = NULL;
    
    execvp(cmd, argv); //This will run "ls -la" as if it were a command
    

    await is only valid in async function

    I had the same problem and the following block of code was giving the same error message:

    repositories.forEach( repo => {
            const commits = await getCommits(repo);
            displayCommit(commits);
    });
    

    The problem is that the method getCommits() was async but I was passing it the argument repo which was also produced by a Promise. So, I had to add the word async to it like this: async(repo) and it started working:

    repositories.forEach( async(repo) => {
            const commits = await getCommits(repo);
            displayCommit(commits);
    });
    

    How do I replicate a \t tab space in HTML?

    I need a code that has the same function as the /t escape character

    What function do you mean, creating a tabulator space?

    No such thing in HTML, you'll have to use HTML elements for that. (A <table> may make sense for tabular data, or a description list <dl> for definitions.)

    Type of expression is ambiguous without more context Swift

    I had this message when the type of a function parameter didn't fit. In my case it was a String instead of an URL.

    The network adapter could not establish the connection - Oracle 11g

    First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

    Configure Nginx with proxy_pass

    Give this a try...

    server {
        listen   80;
        server_name  dev.int.com;
        access_log off;
        location / {
            proxy_pass http://IP:8080;
            proxy_set_header    Host            $host;
            proxy_set_header    X-Real-IP       $remote_addr;
            proxy_set_header    X-Forwarded-for $remote_addr;
            port_in_redirect off;
            proxy_redirect   http://IP:8080/jira  /;
            proxy_connect_timeout 300;
        }
    
        location ~ ^/stash {
            proxy_pass http://IP:7990;
            proxy_set_header    Host            $host;
            proxy_set_header    X-Real-IP       $remote_addr;
            proxy_set_header    X-Forwarded-for $remote_addr;
            port_in_redirect off;
            proxy_redirect   http://IP:7990/  /stash;
            proxy_connect_timeout 300;
        }
    
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/local/nginx/html;
        }
    }
    

    :before and background-image... should it work?

    @michi; define height in your before pseudo class

    CSS:

    #videos-part:before{
        width: 16px;
        content: " ";
        background-image: url(/img/border-left3.png);
        position: absolute;
        left: -16px;
        top: -6px;
        height:20px;
    }
    

    How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

    You can use for example a PHP script for Google Cloud Messaging (GCM). Firebase, and its console, is just on top of GCM.

    I found this one on github: https://gist.github.com/prime31/5675017

    Hint: This PHP script results in a android notification.

    Therefore: Read this answer from Koot if you want to receive and show the notification in Android.

    The difference between the 'Local System' account and the 'Network Service' account?

    Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.

    First the actual accounts:

    • LocalService account (preferred)

      A limited service account that is very similar to Network Service and meant to run standard least-privileged services. However, unlike Network Service it accesses the network as an Anonymous user.

      • Name: NT AUTHORITY\LocalService
      • the account has no password (any password information you provide is ignored)
      • HKCU represents the LocalService user account
      • has minimal privileges on the local computer
      • presents anonymous credentials on the network
      • SID: S-1-5-19
      • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-19)

       

    • NetworkService account

      Limited service account that is meant to run standard privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).

      • NT AUTHORITY\NetworkService
      • the account has no password (any password information you provide is ignored)
      • HKCU represents the NetworkService user account
      • has minimal privileges on the local computer
      • presents the computer's credentials (e.g. MANGO$) to remote servers
      • SID: S-1-5-20
      • has its own profile under the HKEY_USERS registry key (HKEY_USERS\S-1-5-20)
      • If trying to schedule a task using it, enter NETWORK SERVICE into the Select User or Group dialog

       

    • LocalSystem account (dangerous, don't use!)

      Completely trusted account, more so than the administrator account. There is nothing on a single box that this account cannot do, and it has the right to access the network as the machine (this requires Active Directory and granting the machine account permissions to something)

      • Name: .\LocalSystem (can also use LocalSystem or ComputerName\LocalSystem)
      • the account has no password (any password information you provide is ignored)
      • SID: S-1-5-18
      • does not have any profile of its own (HKCU represents the default user)
      • has extensive privileges on the local computer
      • presents the computer's credentials (e.g. MANGO$) to remote servers

       

    Above when talking about accessing the network, this refers solely to SPNEGO (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as LocalService can still access the internet.

    The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).

    It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.

    In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using Local Service (not Local System which is basically the operating system).


    In Windows Server 2003 you cannot run a scheduled task as

    • NT_AUTHORITY\LocalService (aka the Local Service account), or
    • NT AUTHORITY\NetworkService (aka the Network Service account).

    That capability only was added with Task Scheduler 2.0, which only exists in Windows Vista/Windows Server 2008 and newer.

    A service running as NetworkService presents the machine credentials on the network. This means that if your computer was called mango, it would present as the machine account MANGO$:

    enter image description here

    Trust Anchor not found for Android SSL Connection

    I had the same problem while connecting from Android client to Kurento server. Kurento server use jks certificates, so I had to convert pem to it. As input for conversion I used cert.pem file and it lead to such errors. But if use fullchain.pem instead of cert.pem - all is OK.

    java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

    I have the same problem, i read the url with an properties file:

    String configFile = System.getenv("system.Environment");
            if (configFile == null || "".equalsIgnoreCase(configFile.trim())) {
                configFile = "dev.properties";
            }
            // Load properties 
            Properties properties = new Properties();
            properties.load(getClass().getResourceAsStream("/" + configFile));
           //read url from file
            apiUrl = properties.getProperty("url").trim();
                URL url = new URL(apiUrl);
                //throw exception here
        URLConnection conn = url.openConnection();
    

    dev.properties

    url = "https://myDevServer.com/dev/api/gate"
    

    it should be

    dev.properties

    url = https://myDevServer.com/dev/api/gate
    

    without "" and my problem is solved.

    According to oracle documentation

    • Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

    So it means it is not parsed inside the string.

    Simple way to query connected USB devices info in Python?

    I can think of a quick code like this.

    Since all USB ports can be accessed via /dev/bus/usb/< bus >/< device >

    For the ID generated, even if you unplug the device and reattach it [ could be some other port ]. It will be the same.

    import re
    import subprocess
    device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
    df = subprocess.check_output("lsusb")
    devices = []
    for i in df.split('\n'):
        if i:
            info = device_re.match(i)
            if info:
                dinfo = info.groupdict()
                dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
                devices.append(dinfo)
    print devices
    

    Sample output here will be:

    [
    {'device': '/dev/bus/usb/001/009', 'tag': 'Apple, Inc. Optical USB Mouse [Mitsumi]', 'id': '05ac:0304'},
    {'device': '/dev/bus/usb/001/001', 'tag': 'Linux Foundation 2.0 root hub', 'id': '1d6b:0002'},
    {'device': '/dev/bus/usb/001/002', 'tag': 'Intel Corp. Integrated Rate Matching Hub', 'id': '8087:0020'},
    {'device': '/dev/bus/usb/001/004', 'tag': 'Microdia ', 'id': '0c45:641d'}
    ]
    

    Code Updated for Python 3

    import re
    import subprocess
    device_re = re.compile(b"Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
    df = subprocess.check_output("lsusb")
    devices = []
    for i in df.split(b'\n'):
        if i:
            info = device_re.match(i)
            if info:
                dinfo = info.groupdict()
                dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
                devices.append(dinfo)
                
    print(devices)
    

    When to use RDLC over RDL reports?

    If you have a reporting services infrastructure available to you, use it. You will find RDL development to be a bit more pleasant. You can preview the report, easily setup parameters, etc.

    In Mongoose, how do I sort by date? (node.js)

    Been dealing with this issue today using Mongoose 3.5(.2) and none of the answers quite helped me solve this issue. The following code snippet does the trick

    Post.find().sort('-posted').find(function (err, posts) {
        // user posts array
    });
    

    You can send any standard parameters you need to find() (e.g. where clauses and return fields) but no callback. Without a callback it returns a Query object which you chain sort() on. You need to call find() again (with or without more parameters -- shouldn't need any for efficiency reasons) which will allow you to get the result set in your callback.

    Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

    Years later, but for what it's worth - This is simple to do.

    • Just RENAME the C:\xampp directory

    • Install the desired new version of XAMPP

    • Simply run the control panel script "xampp-control.exe" directly from within the xampp folder. (Ignore warnings about "must run from C:\xampp - those have nothing to do with multiple installations.)

    To switch between these versions of XAMPP, just rename the xampp directories as necessary, and re-run.

    Entity framework self referencing loop detected

    This happens because you're trying to serialize the EF object collection directly. Since department has an association to employee and employee to department, the JSON serializer will loop infinetly reading d.Employee.Departments.Employee.Departments etc...

    To fix this right before the serialization create an anonymous type with the props you want

    example (psuedo)code:

    departments.select(dep => new { 
        dep.Id, 
        Employee = new { 
            dep.Employee.Id, dep.Employee.Name 
        }
    });
    

    Global and local variables in R

    A bit more along the same lines

    attrs <- {}
    
    attrs.a <- 1
    
    f <- function(d) {
        attrs.a <- d
    }
    
    f(20)
    print(attrs.a)
    

    will print "1"

    attrs <- {}
    
    attrs.a <- 1
    
    f <- function(d) {
       attrs.a <<- d
    }
    
    f(20)
    print(attrs.a)
    

    Will print "20"

    Java: Convert String to TimeStamp

    I'm sure the solution is that your oldDateString is something like "2009-10-20". Obviously this does not contain any time data lower than days. If you format this string with your new formatter where should it get the minutes, seconds and milliseconds from?

    So the result is absolutely correct: 2009-10-20 00:00:00.000

    What you'll need to solve this, is the original timestamp (incl. time data) before your first formatting.

    What is the best (idiomatic) way to check the type of a Python variable?

    That should work - so no, there is nothing wrong with your code. However, it could also be done with a dict:

    {type(str()): do_something_with_a_string,
     type(dict()): do_something_with_a_dict}.get(type(x), errorhandler)()
    

    A bit more concise and pythonic wouldn't you say?


    Edit.. Heeding Avisser's advice, the code also works like this, and looks nicer:

    {str: do_something_with_a_string,
     dict: do_something_with_a_dict}.get(type(x), errorhandler)()
    

    List of strings to one string

    If you use .net 4.0 you can use a sorter way:

    String.Join<string>(String.Empty, los);
    

    JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

    I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.

    I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.

    html script src="" triggering redirection with button

    your folder name is scripts..

    and you are Referencing it like ../script/login.js

    Also make sure that script folder is in your project directory

    Thanks

    Android: Create spinner programmatically from array

    In Kotlin language you can do it in this way:

    val values = arrayOf(
        "cat",
        "dog",
        "chicken"
    )
    
    ArrayAdapter(
        this,
        android.R.layout.simple_spinner_item,
        values
    ).also {
        it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        spinner.adapter = it
    }
    

    Sleep function Visual Basic

    Since you are asking about .NET, you should change the parameter from Long to Integer. .NET's Integer is 32-bit. (Classic VB's integer was only 16-bit.)

    Declare Sub Sleep Lib "kernel32.dll" (ByVal Milliseconds As Integer)
    

    Really though, the managed method isn't difficult...

    System.Threading.Thread.CurrentThread.Sleep(5000)
    

    Be careful when you do this. In a forms application, you block the message pump and what not, making your program to appear to have hanged. Rarely is sleep a good idea.

    Android: Clear the back stack

    Try using

    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    

    and not

    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    

    How do I REALLY reset the Visual Studio window layout?

    If you've ever backed up your settings (Tools -> Import and Export Settings), you can restore the settings file to get back to a prior state. This is the only thing that I've found to work.

    How do I do an initial push to a remote repository with Git?

    @Josh Lindsey already answered perfectly fine. But I want to add some information since I often use ssh.

    Therefore just change:

    git remote add origin [email protected]:/path/to/my_project.git
    

    to:

    git remote add origin ssh://[email protected]/path/to/my_project
    

    Note that the colon between domain and path isn't there anymore.

    Python: Assign print output to a variable

    Please note, I wrote this answer based on Python 3.x. No worries you can assign print() statement to the variable like this.

    >>> var = print('some text')
    some text
    >>> var
    >>> type(var)
    <class 'NoneType'>
    

    According to the documentation,

    All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.

    The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

    That's why we cannot assign print() statement values to the variable. In this question you have ask (or any function). So print() also a function with the return value with None. So the return value of python function is None. But you can call the function(with parenthesis ()) and save the return value in this way.

    >>> var = some_function()
    

    So the var variable has the return value of some_function() or the default value None. According to the documentation about print(), All non-keyword arguments are converted to strings like str() does and written to the stream. Lets look what happen inside the str().

    Return a string version of object. If object is not provided, returns the empty string. Otherwise, the behavior of str() depends on whether encoding or errors is given, as follows.

    So we get a string object, then you can modify the below code line as follows,

    >>> var = str(some_function())
    

    or you can use str.join() if you really have a string object.

    Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

    change can be as follows,

    >>> var = ''.join(some_function())  # you can use this if some_function() really returns a string value
    

    SQL How to Select the most recent date item

    Assuming your RDBMS know window functions and CTE and USER_ID is the patient's id:

    WITH TT AS (
        SELECT *, ROW_NUMBER() OVER(PARTITION BY USER_ID ORDER BY DOCUMENT_DATE DESC) AS N
        FROM test_table
    )
    SELECT *
    FROM TT
    WHERE N = 1;
    

    I assumed you wanted to sort by DOCUMENT_DATE, you can easily change that if wanted. If your RDBMS doesn't know window functions, you'll have to do a join :

    SELECT *
    FROM test_table T1
    INNER JOIN (SELECT USER_ID, MAX(DOCUMENT_DATE) AS maxDate
                FROM test_table
                GROUP BY USER_ID) T2
        ON T1.USER_ID = T2.USER_ID
            AND T1.DOCUMENT_DATE = T2.maxDate;
    

    It would be good to tell us what your RDBMS is though. And this query selects the most recent date for every patient, you can add a condition for a given patient.

    What is a None value?

    Other answers have already explained meaning of None beautifully. However, I would still like to throw more light on this using an example.

    Example:

    def extendList(val, list=[]):
        list.append(val)
        return list
    
    list1 = extendList(10)
    list2 = extendList(123,[])
    list3 = extendList('a')
    
    print "list1 = %s" % list1
    print "list2 = %s" % list2
    print "list3 = %s" % list3
    

    Now try to guess output of above list. Well, the answer is surprisingly as below:

    list1 = [10, 'a']
    list2 = [123]
    list3 = [10, 'a']
    

    But Why?

    Many will mistakenly expect list1 to be equal to [10] and list3 to be equal to ['a'], thinking that the list argument will be set to its default value of [] each time extendList is called.

    However, what actually happens is that the new default list is created only once when the function is defined, and that same list is then used subsequently whenever extendList is invoked without a list argument being specified. This is because expressions in default arguments are calculated when the function is defined, not when it’s called.

    list1 and list3 are therefore operating on the same default list, whereas list2 is operating on a separate list that it created (by passing its own empty list as the value for the list parameter).


    'None' the savior: (Modify example above to produce desired behavior)

    def extendList(val, list=None):
        if list is None:
           list = []
        list.append(val)
        return list
    
    list1 = extendList(10)
    list2 = extendList(123,[])
    list3 = extendList('a')
    
    print "list1 = %s" % list1
    print "list2 = %s" % list2
    print "list3 = %s" % list3
    

    With this revised implementation, the output would be:

    list1 = [10]
    list2 = [123]
    list3 = ['a']
    

    Note - Example credit to toptal.com

    Type definition in object literal in TypeScript

    // Use ..
    
    const Per = {
      name: 'HAMZA',
      age: 20,
      coords: {
        tele: '09',
        lan: '190'
      },
      setAge(age: Number): void {
        this.age = age;
      },
      getAge(): Number {
        return age;
      }
    };
    const { age, name }: { age: Number; name: String } = Per;
    const {
      coords: { tele, lan }
    }: { coords: { tele: String; lan: String } } = Per;
    
    console.log(Per.getAge());
    

    Jackson JSON: get node name from json-tree

    Clarification Here:

    While this will work:

     JsonNode rootNode = objectMapper.readTree(file);
     Iterator<Map.Entry<String, JsonNode>> fields = rootNode.fields();
     while (fields.hasNext()) {
        Map.Entry<String, JsonNode> entry = fields.next();
        log.info(entry.getKey() + ":" + entry.getValue())
     }
    

    This will not:

    JsonNode rootNode = objectMapper.readTree(file);
    
    while (rootNode.fields().hasNext()) {
        Map.Entry<String, JsonNode> entry = rootNode.fields().next();
        log.info(entry.getKey() + ":" + entry.getValue())
    }
    

    So be careful to declare the Iterator as a variable and use that.

    Be sure to use the fasterxml library rather than codehaus.

    Change Project Namespace in Visual Studio

    Assuming this is for a C# project and assuming that you want to change the default namespace, you need to go to Project Properties, Application tab, and specify "Default Namespace".

    Default namespace is the namespace that Visual studio sets when you create a new class. Next time you do Right Click > Add > Class it would use the namespace you specified in the above step.

    Adding line break in C# Code behind page

       dt = abj.getDataTable(
    "select bookrecord.userid,usermaster.userName, "
                                                    +" book.bookname,bookrecord.fromdate, "
                                                    +" bookrecord.todate,bookrecord.bookstatus "
                                                    +" from book,bookrecord,usermaster " 
                                                    +" where bookrecord.bookid='"+ bookId +"' "
                                                    +" and usermaster.userId=bookrecord.userid "
                                                    +" and book.bookid='"+ bookId +"'");
    

    wait() or sleep() function in jquery?

    That'd be .delay().

    http://api.jquery.com/delay/

    If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.

    I want to vertical-align text in select box

    I ran into this problem exactly. My select options were vertically centered in webkit, but ff defaulted them to the top. After looking around I didn't really want to create a work around that was messy and ultimately didn't solve my problem.

    Solution: Javascript.

    if ($.browser.mozilla) {
                $('.styledSelect select').css( "padding-top","8px" );
            }
    

    This solves your problem very precisely. The only downside here is that I'm using jQuery, and if you aren't using jQuery on your project already, you may not want to include a js library for a one-off.

    Note: I don't recommend styling anything with js unless absolutely necessary. CSS should always be the primary solution for styling–think of jQuery (in this particular example) as the axe labeled "Break in case of Emergency".

    *UPDATE* This is an old post and since it appears people are still referencing this solution I should state (as mentioned in the comments) that since 1.9 this feature has been removed from jQuery. Please see the Modernizr project to perform feature detection in lieu of browser sniffing.

    How to read/process command line arguments?

    My solution is entrypoint2. Example:

    from entrypoint2 import entrypoint
    @entrypoint
    def add(file, quiet=True): 
        ''' This function writes report.
    
        :param file: write report to FILE
        :param quiet: don't print status messages to stdout
        '''
        print file,quiet
    

    help text:

    usage: report.py [-h] [-q] [--debug] file
    
    This function writes report.
    
    positional arguments:
      file         write report to FILE
    
    optional arguments:
      -h, --help   show this help message and exit
      -q, --quiet  don't print status messages to stdout
      --debug      set logging level to DEBUG
    

    What is so bad about singletons?

    The problems with singletons is the issue of increased scope and therefore coupling. There is no denying that there are some of situations where you do need access to a single instance, and it can be accomplished other ways.

    I now prefer to design around an inversion of control (IoC) container and allow the the lifetimes to be controlled by the container. This gives you the benefit of the classes that depend on the instance to be unaware of the fact that there is a single instance. The lifetime of the singleton can be changed in the future. Once such example I encountered recently was an easy adjustment from single threaded to multi-threaded.

    FWIW, if it a PIA when you try to unit test it then it's going to PIA when you try to debug, bug fix or enhance it.

    Getting The ASCII Value of a character in a C# string

    Here's an alternative since you don't like the cast to int:

    foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
        Console.Write(b.ToString());
    

    'this' implicitly has type 'any' because it does not have a type annotation

    The error is indeed fixed by inserting this with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

    foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS
    

    It should've been this:

    foo.on('error', function(this: Foo, err: any) {
    

    or this:

    foo.on('error', function(this: typeof foo, err: any) {
    

    A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

    Add support library to Android Studio project

    This is way more simpler with Maven dependency feature:

    1. Open File -> Project Structure... menu.
    2. Select Modules in the left pane, choose your project's main module in the middle pane and open Dependencies tab in the right pane.
    3. Click the plus sign in the right panel and select "Maven dependency" from the list. A Maven dependency dialog will pop up.
    4. Enter "support-v4" into the search field and click the icon with magnifying glass.
    5. Select "com.google.android:support-v4:r7@jar" from the drop-down list.
    6. Click "OK".
    7. Clean and rebuild your project.

    Hope this will help!

    Windows Batch Files: if else

    You have to do the following:

    if "%1" == "" (
        echo The variable is empty
    ) ELSE (
        echo The variable contains %1
    )
    

    How to find the last day of the month from date?

    There is also the built in PHP function cal_days_in_month()?

    "This function will return the number of days in the month of year for the specified calendar." http://php.net/manual/en/function.cal-days-in-month.

    echo cal_days_in_month(CAL_GREGORIAN, 11, 2009); 
    // = 30
    

    Grep and Python

    Concise and memory efficient:

    #!/usr/bin/env python
    # file: grep.py
    import re, sys
    
    map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))
    

    It works like egrep (without too much error handling), e.g.:

    cat input-file | grep.py "RE"
    

    And here is the one-liner:

    cat input-file | python -c "import re,sys;map(sys.stdout.write,(l for l in sys.stdin if re.search(sys.argv[1],l)))" "RE"
    

    How do you execute an arbitrary native command from a string?

    Invoke-Expression, also aliased as iex. The following will work on your examples #2 and #3:

    iex $command
    

    Some strings won't run as-is, such as your example #1 because the exe is in quotes. This will work as-is, because the contents of the string are exactly how you would run it straight from a Powershell command prompt:

    $command = 'C:\somepath\someexe.exe somearg'
    iex $command
    

    However, if the exe is in quotes, you need the help of & to get it running, as in this example, as run from the commandline:

    >> &"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"
    

    And then in the script:

    $command = '"C:\Program Files\Some Product\SomeExe.exe" "C:\some other path\file.ext"'
    iex "& $command"
    

    Likely, you could handle nearly all cases by detecting if the first character of the command string is ", like in this naive implementation:

    function myeval($command) {
        if ($command[0] -eq '"') { iex "& $command" }
        else { iex $command }
    }
    

    But you may find some other cases that have to be invoked in a different way. In that case, you will need to either use try{}catch{}, perhaps for specific exception types/messages, or examine the command string.

    If you always receive absolute paths instead of relative paths, you shouldn't have many special cases, if any, outside of the 2 above.

    HTML5 Local storage vs. Session storage

    Ya session storage and local storage are same in behaviour except one that is local storage will store the data until and unless the user delete the cache and cookies and session storage data will retain in the system until we close the session i,e until we close the session storage created window.

    How to repeat a char using printf?

    You can use the following technique:

    printf("%.*s", 5, "=================");
    

    This will print "=====" It works for me on Visual Studio, no reason it shouldn't work on all C compilers.

    javax.net.ssl.SSLException: Read error: ssl=0x9524b800: I/O error during system call, Connection reset by peer

    If using Nginx and getting a similar problem, then this might help:

    Scan your domain on this sslTesturl, and see if the connection is allowed for your device version.

    If lower version devices(like < Android 4.4.2 etc) are not able to connect due to TLS support, then try adding this to your Nginx config file,

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    

    How to remove all non-alpha numeric characters from a string in MySQL?

    Be careful, characters like ’ or » are considered as alpha by MySQL. It better to use something like :

    IF c BETWEEN 'a' AND 'z' OR c BETWEEN 'A' AND 'Z' OR c BETWEEN '0' AND '9' OR c = '-' THEN

    Pass multiple complex objects to a post/put Web API method

    Create one complex object to combine Content and Config in it as others mentioned, use dynamic and just do a .ToObject(); as:

    [HttpPost]
    public void StartProcessiong([FromBody] dynamic obj)
    {
       var complexObj= obj.ToObject<ComplexObj>();
       var content = complexObj.Content;
       var config = complexObj.Config;
    }
    

    How to specify Memory & CPU limit in docker compose version 3

    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M
        reservations:
          cpus: '0.0001'
          memory: 20M
    

    More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources

    In you specific case:

    version: "3"
    services:
      node:
        image: USER/Your-Pre-Built-Image
        environment:
          - VIRTUAL_HOST=localhost
        volumes:
          - logs:/app/out/
        command: ["npm","start"]
        cap_drop:
          - NET_ADMIN
          - SYS_ADMIN
        deploy:
          resources:
            limits:
              cpus: '0.001'
              memory: 50M
            reservations:
              cpus: '0.0001'
              memory: 20M
    
    volumes:
      - logs
    
    networks:
      default:
        driver: overlay
    

    Note:

    • Expose is not necessary, it will be exposed per default on your stack network.
    • Images have to be pre-built. Build within v3 is not possible
    • "Restart" is also deprecated. You can use restart under deploy with on-failure action
    • You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm

    Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:

    ports:
      - 80:80
    

    Remove padding from columns in Bootstrap 3

    Bootstrap 4 has a native class to do this : add the class .no-gutters to the parent .row

    How to check if a String contains any of some strings

    This is a "nicer solution" and quite simple

    if(new string[] { "A", "B", ... }.Any(s=>myString.Contains(s)))
    

    Download an SVN repository?

    For me DownloadSVN is the best SVN client no install no explore shell integration so no need to worry about system instability small and very light weight and it does a great job just recently i had a very bad experience with TortoiseSVN on my WindowsXP_x86:) luckily i found this great SVN client

    Find a file by name in Visual Studio Code

    I believe the action name is "workbench.action.quickOpen".

    Valid values for android:fontFamily and what they map to?

    Where do these values come from? The documentation for android:fontFamily does not list this information in any place

    These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

    In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

    Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

    <item name="android:fontFamily">sans-serif</item>
    

    Like the linked answer already stated, 12 variants are possible:

    Added in Android Jelly Bean (4.1) - API 16 :

    Regular (default):

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">normal</item> 
    

    Italic:

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">italic</item>
    

    Bold:

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold</item>
    

    Bold-italic:

    <item name="android:fontFamily">sans-serif</item>
    <item name="android:textStyle">bold|italic</item>
    

    Light:

    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">normal</item>
    

    Light-italic:

    <item name="android:fontFamily">sans-serif-light</item>
    <item name="android:textStyle">italic</item>
    

    Thin :

    <item name="android:fontFamily">sans-serif-thin</item>
    <item name="android:textStyle">normal</item>
    

    Thin-italic :

    <item name="android:fontFamily">sans-serif-thin</item>
    <item name="android:textStyle">italic</item>
    

    Condensed regular:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">normal</item>
    

    Condensed italic:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">italic</item>
    

    Condensed bold:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">bold</item>
    

    Condensed bold-italic:

    <item name="android:fontFamily">sans-serif-condensed</item>
    <item name="android:textStyle">bold|italic</item>
    

    Added in Android Lollipop (v5.0) - API 21 :

    Medium:

    <item name="android:fontFamily">sans-serif-medium</item>
    <item name="android:textStyle">normal</item>
    

    Medium-italic:

    <item name="android:fontFamily">sans-serif-medium</item>
    <item name="android:textStyle">italic</item>
    

    Black:

    <item name="android:fontFamily">sans-serif-black</item>
    <item name="android:textStyle">italic</item>
    

    For quick reference, this is how they all look like:

    Bitwise and in place of modulus operator

    Not using the bitwise-and (&) operator in binary, there is not. Sketch of proof:

    Suppose there were a value k such that x & k == x % (k + 1), but k != 2^n - 1. Then if x == k, the expression x & k seems to "operate correctly" and the result is k. Now, consider x == k-i: if there were any "0" bits in k, there is some i greater than 0 which k-i may only be expressed with 1-bits in those positions. (E.g., 1011 (11) must become 0111 (7) when 100 (4) has been subtracted from it, in this case the 000 bit becomes 100 when i=4.) If a bit from the expression of k must change from zero to one to represent k-i, then it cannot correctly calculate x % (k+1), which in this case should be k-i, but there is no way for bitwise boolean and to produce that value given the mask.

    Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

    "Server not found in Kerberos database" error can happen if you have registered the SPN to multiple users/computers.

    You can check that with:

    $ SetSPN -Q ServicePrincipalName
    ( SetSPN -Q HTTP/my.server.local@MYDOMAIN )
    

    matplotlib error - no module named tkinter

    For Linux

    Debian based distros:

    sudo apt-get install python3-tk
    

    RPM based distros:

    sudo yum install python3-tkinter
    

    For windows:

    For Windows, I think the problem is you didn't install complete Python package. Since Tkinter should be shipped with Python out of box. See: http://www.tkdocs.com/tutorial/install.html . Good python distributions for Windows can be found by the companies Anaconda or ActiveState.

    Test the python module

    python -c "import tkinter"
    

    p.s. I suggest installing ipython, which provides powerful shell and necessary packages as well.

    How do I format a string using a dictionary in python-3.x?

    Since the question is specific to Python 3, here's using the new f-string syntax, available since Python 3.6:

    >>> geopoint = {'latitude':41.123,'longitude':71.091}
    >>> print(f'{geopoint["latitude"]} {geopoint["longitude"]}')
    41.123 71.091
    

    Note the outer single quotes and inner double quotes (you could also do it the other way around).

    How to remove an app with active device admin enabled on Android?

    For Redmi users,

    Settings -> Password & security -> Privacy -> Special app access -> Device admin apps

    Click the deactivate the apps

    Get Month name from month number

    System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(4)
    

    This method return April

    If you need some special language, you can add:

    <system.web>
        <globalization culture="es-ES" uiCulture="es-ES"></globalization>
         <compilation debug="true"
    </system.web>
    

    Or your preferred language.

    For example, with es-ES culture:

    System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(4)
    

    Returns: Abril

    Returns: Abril (in spanish, because, we configured the culture as es-ES in our webconfig file, else, you will get April)

    That should work.

    How to count number of unique values of a field in a tab-delimited text file?

    Here is a bash script that fully answers the (revised) original question. That is, given any .tsv file, it provides the synopsis for each of the columns in turn. Apart from bash itself, it only uses standard *ix/Mac tools: sed tr wc cut sort uniq.

    #!/bin/bash
    # Syntax: $0 filename   
    # The input is assumed to be a .tsv file
    
    FILE="$1"
    
    cols=$(sed -n 1p $FILE | tr -cd '\t' | wc -c)
    cols=$((cols + 2 ))
    i=0
    for ((i=1; i < $cols; i++))
    do
      echo Column $i ::
      cut -f $i < "$FILE" | sort | uniq -c
      echo
    done
    

    How to append in a json file in Python?

    Assuming you have a test.json file with the following content:

    {"67790": {"1": {"kwh": 319.4}}}
    

    Then, the code below will load the json file, update the data inside using dict.update() and dump into the test.json file:

    import json
    
    a_dict = {'new_key': 'new_value'}
    
    with open('test.json') as f:
        data = json.load(f)
    
    data.update(a_dict)
    
    with open('test.json', 'w') as f:
        json.dump(data, f)
    

    Then, in test.json, you'll have:

    {"new_key": "new_value", "67790": {"1": {"kwh": 319.4}}}
    

    Hope this is what you wanted.

    Calculating how many days are between two dates in DB2?

    It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,

    So your Query will be

    select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';
    

    How do you performance test JavaScript code?

    You could use this: http://getfirebug.com/js.html. It has a profiler for JavaScript.

    Special characters like @ and & in cURL POST data

    cURL > 7.18.0 has an option --data-urlencode which solves this problem. Using this, I can simply send a POST request as

    curl -d name=john --data-urlencode passwd=@31&3*J https://www.mysite.com
    

    What is the difference between MacVim and regular Vim?

    unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

    How to draw circle in html page?

    There is not technically a way to draw a circle with HTML (there isn’t a <circle> HTML tag), but a circle can be drawn.

    The best way to draw one is to add border-radius: 50% to a tag such as div. Here’s an example:

    <div style="width: 50px; height: 50px; border-radius: 50%;">You can put text in here.....</div>
    

    Check for a substring in a string in Oracle without LIKE

    I'm guessing the reason you're asking is performance? There's the instr function. But that's likely to work pretty much the same behind the scenes.

    Maybe you could look into full text search.

    As last resorts you'd be looking at caching or precomputed columns/an indexed view.

    How to write header row with csv.DictWriter?

    A few options:

    (1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.

    (2) The documentation mentions "the underlying writer instance" ... so just use it (example at the end).

    dw.writer.writerow(dw.fieldnames)
    

    (3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer

    Writing data:

    w.writerow([d[k] for k in fieldnames])
    

    or

    w.writerow([d.get(k, restval) for k in fieldnames])
    

    Instead of the extrasaction "functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:

    wrong_fields = [k for k in rowdict if k not in self.fieldnames]
    

    ============

    >>> f = open('csvtest.csv', 'wb')
    >>> import csv
    >>> fns = 'foo bar zot'.split()
    >>> dw = csv.DictWriter(f, fns, restval='Huh?')
    # dw.writefieldnames(fns) -- no such animal
    >>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "C:\python26\lib\csv.py", line 144, in writerow
        return self.writer.writerow(self._dict_to_list(rowdict))
      File "C:\python26\lib\csv.py", line 141, in _dict_to_list
        return [rowdict.get(key, self.restval) for key in self.fieldnames]
    AttributeError: 'list' object has no attribute 'get'
    >>> dir(dw)
    ['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
    es', 'restval', 'writer', 'writerow', 'writerows']
    # eureka
    >>> dw.writer.writerow(dw.fieldnames)
    >>> dw.writerow({'foo':'oof'})
    >>> f.close()
    >>> open('csvtest.csv', 'rb').read()
    'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
    >>>
    

    Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

    This error happens if you did not set the password on install, in this case the mysql using unix-socket plugin.

    But if delete the plugin link from settings (table mysql.user) will other problem. This does not fix the problem and creates another problem. To fix the deleted link and set password ("PWD") do:

    1) Run with --skip-grant-tables as said above.

    If it doesnt works then add the string skip-grant-tables in section [mysqld] of /etc/mysql/mysql.conf.d/mysqld.cnf. Then do sudo service mysql restart.

    2) Run mysql -u root -p, then (change "PWD"):

    update mysql.user 
        set authentication_string=PASSWORD("PWD"), plugin="mysql_native_password" 
        where User='root' and Host='localhost';    
    flush privileges;
    
    quit
    then sudo service mysql restart. Check: mysql -u root -p.
    

    Before restart remove that string from file mysqld.cnf, if you set it there.

    @bl79 is the author of this answer, i've just reposted it, because it does help!

    How do you allow spaces to be entered using scanf?

    While you really shouldn't use scanf() for this sort of thing, because there are much better calls such as gets() or getline(), it can be done:

    #include <stdio.h>
    
    char* scan_line(char* buffer, int buffer_size);
    
    char* scan_line(char* buffer, int buffer_size) {
       char* p = buffer;
       int count = 0;
       do {
           char c;
           scanf("%c", &c); // scan a single character
           // break on end of line, string terminating NUL, or end of file
           if (c == '\r' || c == '\n' || c == 0 || c == EOF) {
               *p = 0;
               break;
           }
           *p++ = c; // add the valid character into the buffer
       } while (count < buffer_size - 1);  // don't overrun the buffer
       // ensure the string is null terminated
       buffer[buffer_size - 1] = 0;
       return buffer;
    }
    
    #define MAX_SCAN_LENGTH 1024
    
    int main()
    {
       char s[MAX_SCAN_LENGTH];
       printf("Enter a string: ");
       scan_line(s, MAX_SCAN_LENGTH);
       printf("got: \"%s\"\n\n", s);
       return 0;
    }
    

    How to break lines in PowerShell?

    If you are using just code like this below, you must put just a grave accent at the end of line `.

    docker run -d --name rabbitmq `
               -p 5672:5672 `
               -p 15672:15672 `
               --restart=always `
               --hostname rabbitmq-master `
               -v c:\docker\rabbitmq\data:/var/lib/rabbitmq `
               rabbitmq:latest
    

    Java - ignore exception and continue

    Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

    Toggle visibility property of div

    To clean this up a little bit and maintain a single line of code (like you would with a toggle()), you can use a ternary operator so your code winds up looking like this (also using jQuery):

    $('#video-over').css('visibility', $('#video-over').css('visibility') == 'hidden' ? 'visible' : 'hidden');
    

    How to replace all double quotes to single quotes using jquery?

    You can also use replaceAll(search, replaceWith) [MDN].

    Then, make sure you have a string by wrapping one type of quotes by a different type:

     'a "b" c'.replaceAll('"', "'")
     // result: "a 'b' c"
        
     'a "b" c'.replaceAll(`"`, `'`)
     // result: "a 'b' c"
    
     // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
     'a "b" c'.replaceAll(/\"/g, "'")
     // result: "a 'b' c"
    

    Important(!) if you choose regex:

    when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

    How to install CocoaPods?

    Here is All step with image. please follow it properly and i am sure you will not get any error.

    From How to install CocoaPods and setup with your Xcode project.


    First of all check you have to install command line or not.

    You can check this by opening Xcode, navigating the menu to

     Xcode > Preferences > Downloads > Components, finding Command Line Tools and select install/update.
    

    Commandline tool

    if you haven't find command line tool then you need to write this command in terminal. xcode-select --install

    and click on install

    if you have install command line tool. you need to select your Xcode directory (Sometimes this type of problems created due to different versions of Xcode available) follow this procedure.

    Open terminal and run this command:

    sudo gem install cocoapods
    

    Enter admin password. This could take a while. After few minutes it will show green message is cocoa pods installed successfully in your mac machine.

    If you are getting any error with Xcode 6 like developer path is missing. First run this command in terminal:

    sudo xcode-select -switch /Applications/Xcode6.app (or your XCodeName.app)

    Now you can setup Pod with your Xcode project.

    and now you have to install pod. follow this procedure.

    1. Open Terminal

    2. Change directory to your Xcode project root directory (where your ProjectName.xcodeproj file is placed).

    3. $ pod setup : (Setting up CocoaPods master repo)

    If successful, it shows : Setup completed (read-only access). So, you setup everything. Now Lets do something which is more visible…Yes ! Lets install libraries in your Xcode project.

    now you have to setup and update library related to pod in your project.

    Steps to add-remove-update libraries in pod:

    1. Open Terminal

    2. Change directory to your Xcode project root directory. If your terminal is already running then no need to do this, as you are already at same path.

    3. $ touch pod file

    4. $ open -e podfile (This should open a blank text file)

    5. Add your library names in that text file. You can add new names (lib name), remove any name or change the version e.g :

      pod ’Facebook-iOS-SDK’
      pod ’EGOTableViewPullRefresh’
      pod ’JSONKit’
      pod ‘MBProgressHUD
      

    NOTE: Use ( control + ” ) button to add single quote at both end of library name. It should be shown as straight vertical line. Without control button it shall be added as curly single quote which will give error while installation of file.

    1. Save and close this text file. Now libraries are setup and you have to install/update it

    2. Go to your terminal again and run this command: $ pod install (to install/update these libraries in pod).

    You should see output similar to the following:

    Updating spec repo `master’
    Installing Facebook-iOS-SDK
    Generating support files
    

    Setup completed.

    Note:-

    If you have followed this whole procedure correctly and step by step , then you can directly fire pod update command after selecting Xcode and then select your project path. and write your command pod update

    EDIT :-

    you can also check command line tool here.

    Command line tool in Location

    What is the !! (not not) operator in JavaScript?

    It's not a single operator, it's two. It's equivalent to the following and is a quick way to cast a value to boolean.

    val.enabled = !(!enable);
    

    Display HTML form values in same page after submit using Ajax

    display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.

    Make copy of an array

    For a null-safe copy of an array, you can also use an optional with the Object.clone() method provided in this answer.

    int[] arrayToCopy = {1, 2, 3};
    int[] copiedArray = Optional.ofNullable(arrayToCopy).map(int[]::clone).orElse(null);
    

    How to capture a backspace on the onkeydown event

    event.key === "Backspace" or "Delete"

    More recent and much cleaner: use event.key. No more arbitrary number codes!

    input.addEventListener('keydown', function(event) {
        const key = event.key; // const {key} = event; ES6+
        if (key === "Backspace" || key === "Delete") {
            return false;
        }
    });
    

    Mozilla Docs

    Supported Browsers

    How to style components using makeStyles and still have lifecycle methods in Material UI?

    I used withStyles instead of makeStyle

    EX :

    import { withStyles } from '@material-ui/core/styles';
    import React, {Component} from "react";
    
    const useStyles = theme => ({
            root: {
               flexGrow: 1,
             },
      });
    
    class App extends Component {
           render() {
                    const { classes } = this.props;
                    return(
                        <div className={classes.root}>
                           Test
                    </div>
                    )
              }
    } 
    
    export default withStyles(useStyles)(App)
    

    creating an array of structs in c++

    It works perfectly. I have gcc compiler C++11 ready. Try this and you'll see:

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
        int pause;
    
        struct Customer
        {
               int uid;
               string name;
        };
    
        Customer customerRecords[2];
        customerRecords[0] = {25, "Bob Jones"};
        customerRecords[1] = {26, "Jim Smith"};
        cout << customerRecords[0].uid << " " << customerRecords[0].name << endl;
        cout << customerRecords[1].uid << " " << customerRecords[1].name << endl;
        cin >> pause;
    return 0;
    }
    

    select unique rows based on single distinct column

    Since you don't care which id to return I stick with MAX id for each email to simplify SQL query, give it a try

    ;WITH ue(id)
     AS
     (
       SELECT MAX(id)
       FROM table
       GROUP BY email
     )
     SELECT * FROM table t
     INNER JOIN ue ON ue.id = t.id
    

    jQuery UI - Draggable is not a function?

    The cause to this error is usually because you're probably using a bootstrap framework and have already included a jquery file somewhere else may at the head or right above the closing body tag, in that case all you need to do is to include the jquery ui file wherever you have the jquery file or on both both places and you'll be fine...

      <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js" type="text/javascript"></script>
    

    just include the above jquery ui script wherever you are importing the jquery file along with other bootstrap dependencies.

    windows batch file rename

    I rename in code

    echo off
    
    setlocal EnableDelayedExpansion
    
    for %%a in (*.txt) do (
        REM echo %%a
        set x=%%a
        set mes=!x:~17,3!
    
        if !mes!==JAN (
            set mes=01
        )
    
        if !mes!==ENE (
            set mes=01
        )
    
        if !mes!==FEB (
            set mes=02
        )
    
        if !mes!==MAR (
            set mes=03
        )
    
        if !mes!==APR (
            set mes=04
        )
    
        if !mes!==MAY (
            set mes=05
        )
    
        if !mes!==JUN (
            set mes=06
        )
    
        if !mes!==JUL (
            set mes=07
        )
    
        if !mes!==AUG (
            set mes=08
        )
    
        if !mes!==SEP (
            set mes=09
        )
    
        if !mes!==OCT (
            set mes=10
        )
    
        if !mes!==NOV (
            set mes=11
        )
    
        if !mes!==DEC (
            set mes=12
        )
    
        ren %%a !x:~20,4!!mes!!x:~15,2!.txt 
    
        echo !x:~20,4!!mes!!x:~15,2!.txt 
    
    )
    

    Determining Referer in PHP

    The REFERER is sent by the client's browser as part of the HTTP protocol, and is therefore unreliable indeed. It might not be there, it might be forged, you just can't trust it if it's for security reasons.

    If you want to verify if a request is coming from your site, well you can't, but you can verify the user has been to your site and/or is authenticated. Cookies are sent in AJAX requests so you can rely on that.

    What does it mean by select 1 from table?

    This means that You want a value "1" as output or Most of the time used as Inner Queries because for some reason you want to calculate the outer queries based on the result of inner queries.. not all the time you use 1 but you have some specific values...

    This will statically gives you output as value 1.

    MVC ajax json post to controller action method

    Below is how I got this working.

    The Key point was: I needed to use the ViewModel associated with the view in order for the runtime to be able to resolve the object in the request.

    [I know that that there is a way to bind an object other than the default ViewModel object but ended up simply populating the necessary properties for my needs as I could not get it to work]

    [HttpPost]  
      public ActionResult GetDataForInvoiceNumber(MyViewModel myViewModel)  
      {            
         var invoiceNumberQueryResult = _viewModelBuilder.HydrateMyViewModelGivenInvoiceDetail(myViewModel.InvoiceNumber, myViewModel.SelectedCompanyCode);
         return Json(invoiceNumberQueryResult, JsonRequestBehavior.DenyGet);
      }
    

    The JQuery script used to call this action method:

    var requestData = {
             InvoiceNumber: $.trim(this.value),
             SelectedCompanyCode: $.trim($('#SelectedCompanyCode').val())
          };
    
    
          $.ajax({
             url: '/en/myController/GetDataForInvoiceNumber',
             type: 'POST',
             data: JSON.stringify(requestData),
             dataType: 'json',
             contentType: 'application/json; charset=utf-8',
             error: function (xhr) {
                alert('Error: ' + xhr.statusText);
             },
             success: function (result) {
                CheckIfInvoiceFound(result);
             },
             async: true,
             processData: false
          });
    

    window.onload vs document.onload

    In Chrome, window.onload is different from <body onload="">, whereas they are the same in both Firefox(version 35.0) and IE (version 11).

    You could explore that by the following snippet:

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <!--import css here-->
            <!--import js scripts here-->
    
            <script language="javascript">
    
                function bodyOnloadHandler() {
                    console.log("body onload");
                }
    
                window.onload = function(e) {
                    console.log("window loaded");
                };
            </script>
        </head>
    
        <body onload="bodyOnloadHandler()">
    
            Page contents go here.
    
        </body>
    </html>
    

    And you will see both "window loaded"(which comes firstly) and "body onload" in Chrome console. However, you will see just "body onload" in Firefox and IE. If you run "window.onload.toString()" in the consoles of IE & FF, you will see:

    "function onload(event) { bodyOnloadHandler() }"

    which means that the assignment "window.onload = function(e)..." is overwritten.

    reading a line from ifstream into a string variable

    Use the std::getline() from <string>.

     istream & getline(istream & is,std::string& str)
    

    So, for your case it would be:

    std::getline(read,x);
    

    adb remount permission denied, but able to access super user in shell -- android

    Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.

    How can I keep Bootstrap popovers alive while being hovered?

    Test with code snippet below:

    Small modification (From the solution provided by vikas) to suit my use case.

    1. Open popover on hover event for the popover button
    2. Keep popover open when hovering over the popover box
    3. Close popover on mouseleave for either the popover button, or the popover box.

    _x000D_
    _x000D_
    $(".pop").popover({
        trigger: "manual",
        html: true,
        animation: false
      })
      .on("mouseenter", function() {
        var _this = this;
        $(this).popover("show");
        $(".popover").on("mouseleave", function() {
          $(_this).popover('hide');
        });
      }).on("mouseleave", function() {
        var _this = this;
        setTimeout(function() {
          if (!$(".popover:hover").length) {
            $(_this).popover("hide");
          }
        }, 300);
      });
    _x000D_
    <!DOCTYPE html>
    <html>
    
    <head>
      <link data-require="bootstrap-css@*" data-semver="3.2.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" />
      <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script data-require="bootstrap@*" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>
    
      <link rel="stylesheet" href="style.css" />
    
    </head>
    
    <body>
      <h2 class='text-primary'>Another Great "KISS" Bootstrap Popover example!</h2>
      <p class='text-muted'>KISS = Keep It Simple S....</p>
    
      <p class='text-primary'>Goal:</p>
      <ul>
        <li>Open popover on hover event for the popover button</li>
        <li>Keep popover open when hovering over the popover box</li>
        <li>Close popover on mouseleave for either the popover button, or the popover box.</li>
      </ul>
    
      <button type="button" class="btn btn-danger pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
        data-original-title="" title="">
        HOVER OVER ME
        </button>
      <br><br>
      <button type="button" class="btn btn-info pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
        data-original-title="" title="">
        HOVER OVER ME... Again!
        </button><br><br>
      <button type="button" class="btn btn-success pop" data-container="body" data-toggle="popover" data-placement="right" data-content="Optional parameter: Skip if this was not requested<br>                                    A placement group is a logical grouping of instances within a single Availability                                     Zone. Using placement groups enables applications to get the full-bisection bandwidth                                     and low-latency network performance required for tightly coupled, node-to-node                                     communication typical of HPC applications.<br>                                    This only applies to cluster compute instances: cc2.8xlarge, cg1.4xlarge, cr1.8xlarge, hi1.4xlarge and hs1.8xlarge.<br>                                    More info: <a href=&quot;http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/placement-groups.html&quot; target=&quot;_blank&quot;>Click here...</a>"
        data-original-title="" title="">
        Okay one more time... !
        </button>
      <br><br>
      <p class='text-info'>Hope that helps you... Drove me crazy for a while</p>
      <script src="script.js"></script>
    </body>
    
    </html>
    _x000D_
    _x000D_
    _x000D_

    How to get a MemoryStream from a Stream in .NET?

    If you're modifying your class to accept a Stream instead of a filename, don't bother converting to a MemoryStream. Let the underlying Stream handle the operations:

    public class MyClass
    { 
        Stream _s;
    
        public MyClass(Stream s) { _s = s; }
    }
    

    But if you really need a MemoryStream for internal operations, you'll have to copy the data out of the source Stream into the MemoryStream:

    public MyClass(Stream stream)
    {
        _ms = new MemoryStream();
        CopyStream(stream, _ms);
    }
    
    // Merged From linked CopyStream below and Jon Skeet's ReadFully example
    public static void CopyStream(Stream input, Stream output)
    {
        byte[] buffer = new byte[16*1024];
        int read;
        while((read = input.Read (buffer, 0, buffer.Length)) > 0)
        {
            output.Write (buffer, 0, read);
        }
    }
    

    Custom "confirm" dialog in JavaScript?

    SweetAlert

    You should take a look at SweetAlert as an option to save some work. It's beautiful from the default state and is highly customizable.

    Confirm Example

    sweetAlert(
      {
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary file!",
        type: "warning",   
        showCancelButton: true,   
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!"
      }, 
      deleteIt()
    );
    

    Sample Alert

    Access maven properties defined in the pom

    Maven already has a solution to do what you want:

    Get MavenProject from just the POM.xml - pom parser?

    btw: first hit at google search ;)

    Model model = null;
    FileReader reader = null;
    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
    
    try {
         reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
         model = mavenreader.read(reader);
         model.setPomFile(pomfile);
    }catch(Exception ex){
         // do something better here
         ex.printStackTrace()
    }
    
    MavenProject project = new MavenProject(model);
    project.getProperties() // <-- thats what you need
    

    How to create a md5 hash of a string in C?

    Here's a complete example:

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #if defined(__APPLE__)
    #  define COMMON_DIGEST_FOR_OPENSSL
    #  include <CommonCrypto/CommonDigest.h>
    #  define SHA1 CC_SHA1
    #else
    #  include <openssl/md5.h>
    #endif
    
    char *str2md5(const char *str, int length) {
        int n;
        MD5_CTX c;
        unsigned char digest[16];
        char *out = (char*)malloc(33);
    
        MD5_Init(&c);
    
        while (length > 0) {
            if (length > 512) {
                MD5_Update(&c, str, 512);
            } else {
                MD5_Update(&c, str, length);
            }
            length -= 512;
            str += 512;
        }
    
        MD5_Final(digest, &c);
    
        for (n = 0; n < 16; ++n) {
            snprintf(&(out[n*2]), 16*2, "%02x", (unsigned int)digest[n]);
        }
    
        return out;
    }
    
        int main(int argc, char **argv) {
            char *output = str2md5("hello", strlen("hello"));
            printf("%s\n", output);
            free(output);
            return 0;
        }
    

    How to efficiently use try...catch blocks in PHP

    There is no any problem to write multiple lines of execution withing a single try catch block like below

    try{
    install_engine();
    install_break();
    }
    catch(Exception $e){
    show_exception($e->getMessage());
    }
    

    The moment any execption occure either in install_engine or install_break function the control will be passed to catch function. One more recommendation is to eat your exception properly. Which means instead of writing die('Message') it is always advisable to have exception process properly. You may think of using die() function in error handling but not in exception handling.

    When you should use multiple try catch block You can think about multiple try catch block if you want the different code block exception to display different type of exception or you are trying to throw any exception from your catch block like below:

    try{
        install_engine();
        install_break();
        }
        catch(Exception $e){
        show_exception($e->getMessage());
        }
    try{
    install_body();
    paint_body();
    install_interiour();
    }
    catch(Exception $e){
    throw new exception('Body Makeover faield')
    }
    

    Javascript parse float is ignoring the decimals after my comma

    As @JaredPar pointed out in his answer use parseFloat with replace

    var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));
    

    Just replacing the comma with a dot will fix, Unless it's a number over the thousands like 1.000.000,00 this way will give you the wrong digit. So you need to replace the comma remove the dots.

    // Remove all dot's. Replace the comma.
    var fullcost = parseFloat($("#fullcost").text().replace(/\./g,'').replace(',', '.'));
    

    By using two replaces you'll be able to deal with the data without receiving wrong digits in the output.

    WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

    For "polling" transport.

    Apache side:

    <VirtualHost *:80>
        ServerName mysite.com
        DocumentRoot /my/path
    
    
        ProxyRequests Off
    
        <Proxy *>
            Order deny,allow
            Allow from all
        </Proxy>
    
        ProxyPass /my-connect-3001 http://127.0.0.1:3001/socket.io
        ProxyPassReverse /my-connect-3001 http://127.0.0.1:3001/socket.io   
    </VirtualHost>
    

    Client side:

    var my_socket = new io.Manager(null, {
        host: 'mysite.com',
        path: '/my-connect-3001'
        transports: ['polling'],
    }).socket('/');
    

    SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

    You could convert your values into a 'Decimal' datetime and convert it then to a real datetime column:

    select cast(rtrim(year *10000+ month *100+ day) as datetime) as Date from DateTable
    

    See here as well for more info.

    How to manually include external aar package using new Gradle Android Build System

    Unfortunately none of the solutions here worked for me (I get unresolved dependencies). What finally worked and is the easiest way IMHO is: Highlight the project name from Android Studio then File -> New Module -> Import JAR or AAR Package. Credit goes to the solution in this post

    How do I read any request header in PHP

    You should find all HTTP headers in the $_SERVER global variable prefixed with HTTP_ uppercased and with dashes (-) replaced by underscores (_).

    For instance your X-Requested-With can be found in:

    $_SERVER['HTTP_X_REQUESTED_WITH']
    

    It might be convenient to create an associative array from the $_SERVER variable. This can be done in several styles, but here's a function that outputs camelcased keys:

    $headers = array();
    foreach ($_SERVER as $key => $value) {
        if (strpos($key, 'HTTP_') === 0) {
            $headers[str_replace(' ', '', ucwords(str_replace('_', ' ', strtolower(substr($key, 5)))))] = $value;
        }
    }
    

    Now just use $headers['XRequestedWith'] to retrieve the desired header.

    PHP manual on $_SERVER: http://php.net/manual/en/reserved.variables.server.php

    PHP - Fatal error: Unsupported operand types

    I had a similar error with the following code:-

    foreach($myvar as $key => $value){
        $query = "SELECT stuff
                FROM table
                WHERE col1 = '$criteria1'
                AND col2 = '$criteria2'";
    
        $result = mysql_query($query) or die('Could not execute query - '.mysql_error(). __FILE__. __LINE__. $query);               
        $point_values = mysql_fetch_assoc($result);
        $top_five_actions[$key] += $point_values; //<--- Problem Line       
    }
    

    It turned out that my $point_values variable was occasionally returning false which caused the problem so I fixed it by wrapping it in mysql_num_rows check:-

    if(mysql_num_rows($result) > 0) {
            $point_values = mysql_fetch_assoc($result);
            $top_five_actions[$key] += $point_values;
    }
    

    Not sure if this helps though?

    Cheers

    HTML / CSS How to add image icon to input type="button"?

    If you're using spritesheets this becomes impossible and the element must be wrapped.

    .btn{
        display: inline-block;
        background: blue;
        position: relative;
        border-radius: 5px;
    }
    .input, .btn:after{
        color: #fff;
    }
    .btn:after{
        position: absolute;
        content: '@';
        right: 0;
        width: 1.3em;
        height: 1em;
    }
    .input{
        background: transparent;
        color: #fff;
        border: 0;
        padding-right: 20px;
        cursor: pointer;
        position: relative;
        padding: 5px 20px 5px 5px;
        z-index: 1;
    }
    

    Check out this fiddle: http://jsfiddle.net/AJNnZ/

    Random number between 0 and 1 in python

    random.random() does exactly that

    >>> import random
    >>> for i in range(10):
    ...     print(random.random())
    ... 
    0.908047338626
    0.0199900075962
    0.904058545833
    0.321508119045
    0.657086320195
    0.714084413092
    0.315924955063
    0.696965958019
    0.93824013683
    0.484207425759
    

    If you want really random numbers, and to cover the range [0, 1]:

    >>> import os
    >>> int.from_bytes(os.urandom(8), byteorder="big") / ((1 << 64) - 1)
    0.7409674234050893
    

    Disable scrolling when touch moving certain element

    try overflow hidden on the thing you don't want to scroll while touch event is happening. e.g set overflow hidden on Start and set it back to auto on end.

    Did you try it ? I'd be interested to know if this would work.

    document.addEventListener('ontouchstart', function(e) {
        document.body.style.overflow = "hidden";
    }, false);
    
    document.addEventListener('ontouchmove', function(e) {
        document.body.style.overflow = "auto";
    }, false);
    

    Make a Bash alias that takes a parameter?

    Refining the answer above, you can get 1-line syntax like you can for aliases, which is more convenient for ad-hoc definitions in a shell or .bashrc files:

    bash$ myfunction() { mv "$1" "$1.bak" && cp -i "$2" "$1"; }
    
    bash$ myfunction original.conf my.conf
    

    Don't forget the semi-colon before the closing right-bracket. Similarly, for the actual question:

    csh% alias junk="mv \\!* ~/.Trash"
    
    bash$ junk() { mv "$@" ~/.Trash/; }
    

    Or:

    bash$ junk() { for item in "$@" ; do echo "Trashing: $item" ; mv "$item" ~/.Trash/; done; }
    

    Python Pandas Counting the Occurrences of a Specific value

    for finding a specific value of a column you can use the code below

    irrespective of the preference you can use the any of the method you like

    df.col_name.value_counts().Value_you_are_looking_for
    

    take example of the titanic dataset

    df.Sex.value_counts().male
    

    this gives a count of all male on the ship Although if you want to count a numerical data then you cannot use the above method because value_counts() is used only with series type of data hence fails So for that you can use the second method example

    the second method is

    #this is an example method of counting on a data frame
    df[(df['Survived']==1)&(df['Sex']=='male')].counts()
    

    this is not that efficient as value_counts() but surely will help if you want to count values of a data frame hope this helps

    javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

    It is working after adding to pom.xml following dependencies:

    <dependency>
       <groupId>javax.el</groupId>
       <artifactId>javax.el-api</artifactId>
       <version>2.2.4</version>
    </dependency>
    <dependency>
       <groupId>org.glassfish.web</groupId>
       <artifactId>javax.el</artifactId>
       <version>2.2.4</version>
    </dependency>
    

    Getting started with Hibernate Validator:

    Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages. When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container. In a Java SE environment, however, you have to add an implementation as dependency to your POM file. For instance you can add the following two dependencies to use the JSR 341 reference implementation:

    <dependency>
       <groupId>javax.el</groupId>
       <artifactId>javax.el-api</artifactId>
       <version>2.2.4</version>
    </dependency>
    <dependency>
       <groupId>org.glassfish.web</groupId>
       <artifactId>javax.el</artifactId>
       <version>2.2.4</version>
    </dependency>
    

    Float a div above page content

    The below code is working,

    <style>
        .PanelFloat {
            position: fixed;
            overflow: hidden;
            z-index: 2400;
            opacity: 0.70;
            right: 30px;
            top: 0px !important;
            -webkit-transition: all 0.5s ease-in-out;
            -moz-transition: all 0.5s ease-in-out;
            -ms-transition: all 0.5s ease-in-out;
            -o-transition: all 0.5s ease-in-out;
            transition: all 0.5s ease-in-out;
        }
    </style>
    
    <script>
     //The below script will keep the panel float on normal state
     $(function () {
            $(document).on('scroll', function () {
                //Multiplication value shall be changed based on user window
                $('#MyFloatPanel').css('top', 4 * ($(window).scrollTop() / 5));
            });
        });
     //To make the panel float over a bootstrap model which has z-index: 2300, so i specified custom value as 2400
     $(document).on('click', '.btnSearchView', function () {
          $('#MyFloatPanel').addClass('PanelFloat');
      });
    
      $(document).on('click', '.btnSearchClose', function () {
          $('#MyFloatPanel').removeClass('PanelFloat');
      });
     </script>
    
     <div class="col-lg-12 col-md-12">
       <div class="col-lg-8 col-md-8" >
        //My scrollable content is here
       </div>
       //This below panel will float while scrolling the above div content
       <div class="col-lg-4 col-md-4" id="MyFloatPanel">
        <div class="row">
         <div class="panel panel-default">
          <div class="panel-heading">Panel Head </div>
         <div class="panel-body ">//Your panel content</div>
       </div>
      </div>
     </div>
    </div>
    

    How can I go back/route-back on vue-router?

    If you're using Vuex you can use https://github.com/vuejs/vuex-router-sync

    Just initialize it in your main file with:

    import VuexRouterSync from 'vuex-router-sync';
    VuexRouterSync.sync(store, router);
    

    Each route change will update route state object in Vuex. You can next create getter to use the from Object in route state or just use the state (better is to use getters, but it's other story https://vuex.vuejs.org/en/getters.html), so in short it would be (inside components methods/values):

    this.$store.state.route.from.fullPath
    

    You can also just place it in <router-link> component:

    <router-link :to="{ path: $store.state.route.from.fullPath }"> 
      Back 
    </router-link>
    

    So when you use code above, link to previous path would be dynamically generated.

    Datagridview: How to set a cell in editing mode?

    Well, I would check if any of your columns are set as ReadOnly. I have never had to use BeginEdit, but maybe there is some legitimate use. Once you have done dataGridView1.Columns[".."].ReadOnly = False;, the fields that are not ReadOnly should be editable. You can use the DataGridView CellEnter event to determine what cell was entered and then turn on editing on those cells after you have passed editing from the first two columns to the next set of columns and turn off editing on the last two columns.

    Angular 6 Material mat-select change method removed

    The changed it from change to selectionChange.

    <mat-select (change)="doSomething($event)">
    

    is now

    <mat-select (selectionChange)="doSomething($event)">
    

    https://material.angular.io/components/select/api

    Get/pick an image from Android's built-in Gallery app programmatically

    here is my example, might not be as your case exactly.


    assuming that you get base64 format from your API provider, give it a file name and file extension, save it to certain location in the file system.

    public static void shownInBuiltInGallery(final Context ctx, String strBase64Image, final String strFileName, final String strFileExtension){
    
    new AsyncTask<String, String, File>() {
        @Override
        protected File doInBackground(String... strBase64Image) {
    
            Bitmap bmpImage = convertBase64StringToBitmap(strBase64Image[0], Base64.NO_WRAP);
    
            if(bmpImage == null) {
                cancel(true);
                return null;
            }
    
            byte[] byImage = null;
    
            if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_JPG) == 0) {
                byImage = convertToJpgByte(bmpImage); // convert bitmap to binary for latter use
            } else if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_PNG) == 0){
                byImage = convertToPngByte(bmpImage); // convert bitmap to binary for latter use
            } else if(strFileExtension.compareToIgnoreCase(FILE_EXTENSION_BMP) == 0){
                byImage = convertToBmpByte(bmpImage); // convert bitmap to binary for latter use
            } else {
                cancel(true);
                return null;
            }
    
            if(byImage == null) {
                cancel(true);
                return null;
            }
    
            File imageFolder = ctx.getExternalCacheDir();
    
            if(imageFolder.exists() == false){
                if(imageFolder.mkdirs() == false){
                    cancel(true);
                    return null;
                }
            }
    
            File imageFile = null;
    
            try {
                imageFile = File.createTempFile(strFileName, strFileExtension, imageFolder);
            } catch (IOException e){
                e.printStackTrace();
            }
    
            if(imageFile == null){
                cancel(true);
                return null;
            }
    
            if (imageFile.exists() == true) {
                if(imageFile.delete() == false){
                    cancel(true);
                    return null;
                }
            }
    
            FileOutputStream fos = null;
    
            try {
                fos = new FileOutputStream(imageFile.getPath());
                fos.write(byImage);
                fos.flush();
                fos.close();
            } catch (java.io.IOException e) {
                e.printStackTrace();
            } finally {
                fos = null;
            }
    
            return imageFile;
        }
    
        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
    
                String strAuthority = ctx.getPackageName() + ".provider";
                Uri uriImage = FileProvider.getUriForFile(ctx, strAuthority, file);
    
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(uriImage, "image/*");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                ctx.startActivity(intent);
    
        }
    }.execute(strBase64Image);}
    

    Don't forget to set up a proper file provider at first place in AndroidManifest.xml

            <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
    
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"/>
        </provider>
    

    where the file path is a xml in .../res/xml/file_path.xml

    <?xml version="1.0" encoding="utf-8"?>
    

    <external-files-path name="external_files" path="Accessory"/>
    
    <external-path name="ex_Download" path="Download/" />
    <external-path name="ex_Pictures" path="Pictures/" />
    
    <external-files-path name="my_Download" path="Download/" />
    <external-files-path name="my_Pictures" path="Pictures/" />
    <external-cache-path name="my_cache" path="." />
    
    <files-path name="private_Download" path="Download/" />
    <files-path name="private_Pictures" path="Pictures/" />
    <cache-path name="private_cache" path="." />
    


    Long story short, have file provider ready at first, pass Uri to Intent for known and accessible picture source, otherwise, save the picture in desired location and then pass the location (as Uri) to Intent.

    In PowerShell, how do I test whether or not a specific variable exists in global scope?

    Test the existence of variavle MyVariable. Returns boolean true or false.

    Test-Path variable:\MyVariable

    How to negate specific word in regex?

    The accepted answer is nice but is really a work-around for the lack of a simple sub-expression negation operator in regexes. This is why grep --invert-match exits. So in *nixes, you can accomplish the desired result using pipes and a second regex.

    grep 'something I want' | grep --invert-match 'but not these ones'
    

    Still a workaround, but maybe easier to remember.