Programs & Examples On #Deployment

A series of activities that makes a program available for use (usually in test or production environments)

How to manage local vs production settings in Django?

Instead of settings.py, use this layout:

.
+-- settings/
    +-- __init__.py  <= not versioned
    +-- common.py
    +-- dev.py
    +-- prod.py

common.py is where most of your configuration lives.

prod.py imports everything from common, and overrides whatever it needs to override:

from __future__ import absolute_import # optional, but I like it
from .common import *

# Production overrides
DEBUG = False
#...

Similarly, dev.py imports everything from common.py and overrides whatever it needs to override.

Finally, __init__.py is where you decide which settings to load, and it's also where you store secrets (therefore this file should not be versioned):

from __future__ import absolute_import
from .prod import *  # or .dev if you want dev

##### DJANGO SECRETS
SECRET_KEY = '(3gd6shenud@&57...'
DATABASES['default']['PASSWORD'] = 'f9kGH...'

##### OTHER SECRETS
AWS_SECRET_ACCESS_KEY = "h50fH..."

What I like about this solution is:

  1. Everything is in your versioning system, except secrets
  2. Most configuration is in one place: common.py.
  3. Prod-specific things go in prod.py, dev-specific things go in dev.py. It's simple.
  4. You can override stuff from common.py in prod.py or dev.py, and you can override anything in __init__.py.
  5. It's straightforward python. No re-import hacks.

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

How do I install package.json dependencies in the current directory using npm

Running:

npm install

from inside your app directory (i.e. where package.json is located) will install the dependencies for your app, rather than install it as a module, as described here. These will be placed in ./node_modules relative to your package.json file (it's actually slightly more complex than this, so check the npm docs here).

You are free to move the node_modules dir to the parent dir of your app if you want, because node's 'require' mechanism understands this. However, if you want to update your app's dependencies with install/update, npm will not see the relocated 'node_modules' and will instead create a new dir, again relative to package.json.

To prevent this, just create a symlink to the relocated node_modules from your app dir:

ln -s ../node_modules node_modules

The type initializer for 'CrystalDecisions.CrystalReports.Engine.ReportDocument' threw an exception

For one full day i searched online and i found a solution on my own. The same scenario, the application works fine in developer machine but when deployed it is throwing the exception "crystaldecisions.crystalreports.engine.reportdocument threw an exception" Details: sys.io.filenotfoundexcep crystaldecisions.reportappserver.commlayer version 13.0.2000 is missing

My IDE: MS VS 2010 Ultimate, CR V13.0.10

Solution:

  1. i set x86 for my application, then i set x64 for my setup application

  2. Prerequisite: i Placed the supporting CR runtime file CRRuntime_32bit_13_0_10.msi, CRRuntime_64bit_13_0_10.msi in the following directory C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bootstrapper\Packages\Crystal Reports for .NET Framework 4.0

  3. Include merge module file to the setup project. Here is version is not serious thing because i use 13.0.10 soft, 13.0.16 merge module file File i included: CRRuntime_13_0_16.msm This file is found one among the set msm files.

While installing this Merge module will add the necessary dll in the following dir C:\Program Files (x86)\SAP BusinessObjects\Crystal Reports for .NET Framework 4.0\Common\SAP BusinessObjects Enterprise XI 4.0\win32_x86\dotnet

dll file version will not cause any issues.

In your developer machine you confirm it same.

I need reputation points, if this answer is useful kindly mark it useful(+1)

What are some good SSH Servers for windows?

I've been using Bitvise SSH Server and it's really great. From install to administration it does it all through a GUI so you won't be putting together a sshd_config file. Plus if you use their client, Tunnelier, you get some bonus features (like mapping shares, port forwarding setup up server side, etc.) If you don't use their client it will still work with the Open Source SSH clients.

It's not Open Source and it costs $39.95, but I think it's worth it.

UPDATE 2009-05-21 11:10: The pricing has changed. The current price is $99.95 per install for commercial, but now free for non-commercial/personal use. Here is the current pricing.

IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section

This error message seems to come up in various situations.

In my case, on top of my application's Web.Config file I had an extra Web.Config file in the root folder (C:\Inetpub\www.root). Probably left there after some testing, I had forgotten all about it, and couldn't figure out what the problem was.

Removing it solved the problem for me.

Create a directly-executable cross-platform GUI app using Python

There's also PyGTK, which is basically a Python wrapper for the Gnome Toolkit. I've found it easier to wrap my mind around than Tkinter, coming from pretty much no knowledge of GUI programming previously. It works pretty well and has some good tutorials. Unfortunately there isn't an installer for Python 2.6 for Windows yet, and may not be for a while.

How to deploy correctly when using Composer's develop / production switch?

I think is better automate the process:

Add the composer.lock file in your git repository, make sure you use composer.phar install --no-dev when you release, but in you dev machine you could use any composer command without concerns, this will no go to production, the production will base its dependencies in the lock file.

On the server you checkout this specific version or label, and run all the tests before replace the app, if the tests pass you continue the deployment.

If the test depend on dev dependencies, as composer do not have a test scope dependency, a not much elegant solution could be run the test with the dev dependencies (composer.phar install), remove the vendor library, run composer.phar install --no-dev again, this will use cached dependencies so is faster. But that is a hack if you know the concept of scopes in other build tools

Automate this and forget the rest, go drink a beer :-)

PS.: As in the @Sven comment bellow, is not a good idea not checkout the composer.lock file, because this will make composer install work as composer update.

You could do that automation with http://deployer.org/ it is a simple tool.

Deploying Maven project throws java.util.zip.ZipException: invalid LOC header (bad signature)

I was facing this issue while deploying my ear to my local weblogic instance. Clearing the local repository and building the ear again resolved the issue for me.

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

How do I copy directories recursively with gulp?

The following works without flattening the folder structure:

gulp.src(['input/folder/**/*']).pipe(gulp.dest('output/folder'));

The '**/*' is the important part. That expression is a glob which is a powerful file selection tool. For example, for copying only .js files use: 'input/folder/**/*.js'

Causes of getting a java.lang.VerifyError

Well in my case, my project A had a dependency on another, say X(A was using some of the classes defined in X). So when I added X as a reference project in the build path of A , I got this error. However when I removed X as the referenced project and included X's jar as one of the libraries, the problem was solved.

Android Studio - local path doesn't exist

Please check the build.gradle file. if there is some operation about "applicationVariants.all" or the assignment to output.outputFile, means trying to change to name or location of the output file.

You can try to comment them out first then try again.

Deploy a project using Git push

I use two solutions for post-receive hook:

DEPLOY SOLUTION 1

#!/bin/bash 
#  /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)
# DEPLOY SOLUTION 1 

    export GIT_DIR=/git/repo-bare.git
    export GIT_BRANCH1=master
    export GIT_TARGET1=/var/www/html
    export GIT_BRANCH2=dev
    export GIT_TARGET2=/var/www/dev
    echo "GIT DIR:  $GIT_DIR/"
    echo "GIT TARGET1:  $GIT_TARGET1/"
    echo "GIT BRANCH1:  $GIT_BRANCH1/"
    echo "GIT TARGET2:  $GIT_TARGET2/"
    echo "GIT BRANCH2:  $GIT_BRANCH2/"
    echo ""

    cd $GIT_DIR/

while read oldrev newrev refname
do
    branch=$(git rev-parse --abbrev-ref $refname)
    BRANCH_REGEX='^${GIT_BRANCH1}.*$'
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET1/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        git checkout -f $branch
    fi

    BRANCH_REGEX='^${GIT_BRANCH2}.*$'
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET2/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        git checkout -f $branch
    fi
done

DEPLOY SOLUTION 2

#!/bin/bash 
#  /git-repo/hooks/post-receive - file content on server (chmod as 755 to be executed)
# DEPLOY SOLUTION 2

    export GIT_DIR=/git/repo-bare.git
    export GIT_BRANCH1=master
    export GIT_TARGET1=/var/www/html
    export GIT_BRANCH2=dev
    export GIT_TARGET2=/var/www/dev
    export GIT_TEMP_DIR1=/tmp/deploy1
    export GIT_TEMP_DIR2=/tmp/deploy2
    echo "GIT DIR:  $GIT_DIR/"
    echo "GIT TARGET1:  $GIT_TARGET1/"
    echo "GIT BRANCH1:  $GIT_BRANCH1/"
    echo "GIT TARGET2:  $GIT_TARGET2/"
    echo "GIT BRANCH2:  $GIT_BRANCH2/"
    echo "GIT TEMP DIR1:  $GIT_TEMP_DIR1/"
    echo "GIT TEMP DIR2:  $GIT_TEMP_DIR2/"
    echo ""

    cd $GIT_DIR/

while read oldrev newrev refname
do
    branch=$(git rev-parse --abbrev-ref $refname)
    BRANCH_REGEX='^${GIT_BRANCH1}.*$'
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET1/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        # DEPLOY SOLUTION 2: 
        cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR1; 
        export GIT_WORK_TREE=$GIT_TEMP_DIR1/.
        git checkout -f $branch
        export GIT_WORK_TREE=$GIT_TARGET1/.
        rsync $GIT_TEMP_DIR1/. -v -q --delete --delete-after -av $GIT_TARGET1/.
        rm -rf $GIT_TEMP_DIR1
    fi

    BRANCH_REGEX='^${GIT_BRANCH2}.*$'
    if [[ $branch =~ $BRANCH_REGEX ]] ; then
        export GIT_WORK_TREE=$GIT_TARGET2/.
        echo "Checking out branch: $branch";
        echo "Checking out to workdir: $GIT_WORK_TREE"; 

        # DEPLOY SOLUTION 2: 
        cd $GIT_DIR/; mkdir -p $GIT_TEMP_DIR2; 
        export GIT_WORK_TREE=$GIT_TEMP_DIR2/.
        git checkout -f $branch
        export GIT_WORK_TREE=$GIT_TARGET2/.
        rsync $GIT_TEMP_DIR2/. -v -q --delete --delete-after -av $GIT_TARGET2/.
        rm -rf $GIT_TEMP_DIR2
    fi
done

Both solutions are based on earlier solutions available in this thread.

Note, the BRANCH_REGEX='^${GIT_BRANCH1}.$' filters for the branch names matching "master" or "dev*" string, and deploys the work tree, if the pushed branch matches. This makes possible to deploy a dev version and master version to different places.

DEPLOY SOLUTION 1 removes only files, which are part of the repo, and was removed by a commit. It is faster than Deployment Solution 2.

DEPLOY SOLUTION 2 has the advantage, that it will remove any new files from the production directory, which was added on server side, no matter if it was added to the repo or not. It will be always clean dupe of the repo. It is slower than Deployment Solution 1.

Install a .NET windows service without InstallUtil.exe

You can always fall back to the good old WinAPI calls, although the amount of work involved is non-trivial. There is no requirement that .NET services be installed via a .NET-aware mechanism.

To install:

  • Open the service manager via OpenSCManager.
  • Call CreateService to register the service.
  • Optionally call ChangeServiceConfig2 to set a description.
  • Close the service and service manager handles with CloseServiceHandle.

To uninstall:

  • Open the service manager via OpenSCManager.
  • Open the service using OpenService.
  • Delete the service by calling DeleteService on the handle returned by OpenService.
  • Close the service and service manager handles with CloseServiceHandle.

The main reason I prefer this over using the ServiceInstaller/ServiceProcessInstaller is that you can register the service with your own custom command line arguments. For example, you might register it as "MyApp.exe -service", then if the user runs your app without any arguments you could offer them a UI to install/remove the service.

Running Reflector on ServiceInstaller can fill in the details missing from this brief explanation.

P.S. Clearly this won't have "the same effect as calling: InstallUtil MyService.exe" - in particular, you won't be able to uninstall using InstallUtil. But it seems that perhaps this wasn't an actual stringent requirement for you.

"Untrusted App Developer" message when installing enterprise iOS Application

In iOS 9.3.1 and up: Settings > General > Device Management

Can not deserialize instance of java.lang.String out of START_OBJECT token

You're mapping this JSON

{
    "id": 2,
    "socket": "0c317829-69bf-43d6-b598-7c0c550635bb",
    "type": "getDashboard",
    "data": {
        "workstationUuid": "ddec1caa-a97f-4922-833f-632da07ffc11"
    },
    "reply": true
}

that contains an element named data that has a JSON object as its value. You are trying to deserialize the element named workstationUuid from that JSON object into this setter.

@JsonProperty("workstationUuid")
public void setWorkstation(String workstationUUID) {

This won't work directly because Jackson sees a JSON_OBJECT, not a String.

Try creating a class Data

public class Data { // the name doesn't matter 
    @JsonProperty("workstationUuid")
    private String workstationUuid;
    // getter and setter
}

the switch up your method

@JsonProperty("data")
public void setWorkstation(Data data) {
    // use getter to retrieve it

Enterprise app deployment doesn't work on iOS 7.1

After reading this post I had still a problem with downloading my app. Problem was because of self signed SSL certificate.

I've found a solution for this problem. You need to upload your certificate file with extension '.crt' on the web and type address of it in your mobile safari. System ask you about adding your certificate to the list of trusted certificates. After this operation you will be able to install your ad-hoc app.

/usr/bin/codesign failed with exit code 1

One possible cause is that you doesn't have permission to write on the build directory.

Solution: Delete all build directory on your project folder and rebuild your application.

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

If you've already uploaded the key then try to remove the key and then re-upload it with a new key.

 heroku keys:remove //removes the existing key
 ssh-keygen -t rsa //generates a new key in ~/.ssh folder
 heroku keys:add    //uploads the new key, if no arguments r passed then the key generated                              
                    //in default directroy i.e., ~/.ssh/id_rsa is uploaded
 git push heroku

this should work.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Hot deployment is stable only for changes on static parts of the application (jsf, xhtml, etc.).

Here is a working solution, according to JBoss AS 7.1.1.Final:

  • Build your project.
  • Navigate to [JBOSS_HOME]/standalone/tmp/vfs.
  • Open the most recently modified folder named "deployment[some_alphanumeric_values]", i.e. "deployment344b1c870c8edbd".
  • Navigate to the specific view that you want to edit (usually, this is included into the packaged .war folder) and open it with a text editor (i.e. Notepad++).
  • Make the changes you want and save the file.
  • Refresh the respective page on your browser. The changes should be visible now.
  • When finished, don't forget to copy these changes to your actual development environment, rebuild and redeploy.

    System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

    I also had the same issue when I tried to install a Windows service, in my case I managed to resolved the issue by removing blank spaces in the folder path to the service .exe, below is the command worked for me in a command prompt

    cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

    Press ENTER to change working directory

    InstallUtil.exe C:\MyService\Release\ReminderService.exe

    Press ENTER

    Best way to deploy Visual Studio application that can run without installing

    It is possible and is deceptively easy:

    1. "Publish" the application (to, say, some folder on drive C), either from menu Build or from the project's properties ? Publish. This will create an installer for a ClickOnce application.
    2. But instead of using the produced installer, find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj).
    3. Zip that folder (leave out any *.vhost.* files and the app.publish folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.

    An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

    As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.

    It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.

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

    Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

    Install windows service without InstallUtil.exe

    This is a base service class (ServiceBase subclass) that can be subclassed to build a windows service that can be easily installed from the command line, without installutil.exe. This solution is derived from How to make a .NET Windows Service start right after the installation?, adding some code to get the service Type using the calling StackFrame

    public abstract class InstallableServiceBase:ServiceBase
    {
    
        /// <summary>
        /// returns Type of the calling service (subclass of InstallableServiceBase)
        /// </summary>
        /// <returns></returns>
        protected static Type getMyType()
        {
            Type t = typeof(InstallableServiceBase);
            MethodBase ret = MethodBase.GetCurrentMethod();
            Type retType = null;
            try
            {
                StackFrame[] frames = new StackTrace().GetFrames();
                foreach (StackFrame x in frames)
                {
                    ret = x.GetMethod();
    
                    Type t1 = ret.DeclaringType;
    
                    if (t1 != null && !t1.Equals(t) &&   !t1.IsSubclassOf(t))
                    {
    
    
                        break;
                    }
                    retType = t1;
                }
            }
            catch
            {
    
            }
            return retType;
        }
        /// <summary>
        /// returns AssemblyInstaller for the calling service (subclass of InstallableServiceBase)
        /// </summary>
        /// <returns></returns>
        protected static AssemblyInstaller GetInstaller()
        {
            Type t = getMyType();
            AssemblyInstaller installer = new AssemblyInstaller(
                t.Assembly, null);
            installer.UseNewContext = true;
            return installer;
        }
    
        private bool IsInstalled()
        {
            using (ServiceController controller =
                new ServiceController(this.ServiceName))
            {
                try
                {
                    ServiceControllerStatus status = controller.Status;
                }
                catch
                {
                    return false;
                }
                return true;
            }
        }
    
        private bool IsRunning()
        {
            using (ServiceController controller =
                new ServiceController(this.ServiceName))
            {
                if (!this.IsInstalled()) return false;
                return (controller.Status == ServiceControllerStatus.Running);
            }
        }
        /// <summary>
        /// protected method to be called by a public method within the real service
        /// ie: in the real service
        ///    new internal  void InstallService()
        ///    {
        ///        base.InstallService();
        ///    }
        /// </summary>
        protected void InstallService()
        {
            if (this.IsInstalled()) return;
    
            try
            {
                using (AssemblyInstaller installer = GetInstaller())
                {
    
                    IDictionary state = new Hashtable();
                    try
                    {
                        installer.Install(state);
                        installer.Commit(state);
                    }
                    catch
                    {
                        try
                        {
                            installer.Rollback(state);
                        }
                        catch { }
                        throw;
                    }
                }
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// protected method to be called by a public method within the real service
        /// ie: in the real service
        ///    new internal  void UninstallService()
        ///    {
        ///        base.UninstallService();
        ///    }
        /// </summary>
        protected void UninstallService()
        {
            if (!this.IsInstalled()) return;
    
            if (this.IsRunning()) {
                this.StopService();
            }
            try
            {
                using (AssemblyInstaller installer = GetInstaller())
                {
                    IDictionary state = new Hashtable();
                    try
                    {
                        installer.Uninstall(state);
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
            catch
            {
                throw;
            }
        }
    
        private void StartService()
        {
            if (!this.IsInstalled()) return;
    
            using (ServiceController controller =
                new ServiceController(this.ServiceName))
            {
                try
                {
                    if (controller.Status != ServiceControllerStatus.Running)
                    {
                        controller.Start();
                        controller.WaitForStatus(ServiceControllerStatus.Running,
                            TimeSpan.FromSeconds(10));
                    }
                }
                catch
                {
                    throw;
                }
            }
        }
    
        private void StopService()
        {
            if (!this.IsInstalled()) return;
            using (ServiceController controller =
                new ServiceController(this.ServiceName))
            {
                try
                {
                    if (controller.Status != ServiceControllerStatus.Stopped)
                    {
                        controller.Stop();
                        controller.WaitForStatus(ServiceControllerStatus.Stopped,
                             TimeSpan.FromSeconds(10));
                    }
                }
                catch
                {
                    throw;
                }
            }
        }
    }
    

    All you have to do is to implement two public/internal methods in your real service:

        new internal  void InstallService()
        {
            base.InstallService();
        }
        new internal void UninstallService()
        {
            base.UninstallService();
        }
    

    and then call them when you want to install the service:

        static void Main(string[] args)
        {
            if (Environment.UserInteractive)
            {
                MyService s1 = new MyService();
                if (args.Length == 1)
                {
                    switch (args[0])
                    {
                        case "-install":
                            s1.InstallService();
    
                            break;
                        case "-uninstall":
    
                            s1.UninstallService();
                            break;
                        default:
                            throw new NotImplementedException();
                    }
                }
    
    
            }
            else {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new MyService() 
                };
                ServiceBase.Run(MyService);            
            }
    
        }
    

    Git command to checkout any branch and overwrite local changes

    git reset and git clean can be overkill in some situations (and be a huge waste of time).

    If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch> is the best option.

    If you're like me, your other option was to clean and perform a --hard reset then recompile your project.

    Parser Error when deploy ASP.NET application

    In my case I missed the compile tag in the .csproj file

    <Compile Include="Global.asax.cs">
      <DependentUpon>Global.asax</DependentUpon>
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Compile>
    

    Run command on the Ansible host

    From the Ansible documentation:

    Delegation This isn’t actually rolling update specific but comes up frequently in those cases.

    If you want to perform a task on one host with reference to other hosts, use the ‘delegate_to’ keyword on a task. This is ideal for placing nodes in a load balanced pool, or removing them. It is also very useful for controlling outage windows. Be aware that it does not make sense to delegate all tasks, debug, add_host, include, etc always get executed on the controller. Using this with the ‘serial’ keyword to control the number of hosts executing at one time is also a good idea:

    ---
    
    - hosts: webservers
      serial: 5
    
      tasks:
    
      - name: take out of load balancer pool
        command: /usr/bin/take_out_of_pool {{ inventory_hostname }}
        delegate_to: 127.0.0.1
    
      - name: actual steps would go here
        yum:
          name: acme-web-stack
          state: latest
    
      - name: add back to load balancer pool
        command: /usr/bin/add_back_to_pool {{ inventory_hostname }}
        delegate_to: 127.0.0.1
    

    These commands will run on 127.0.0.1, which is the machine running Ansible. There is also a shorthand syntax that you can use on a per-task basis: ‘local_action’. Here is the same playbook as above, but using the shorthand syntax for delegating to 127.0.0.1:

    ---
    
    # ...
    
      tasks:
    
      - name: take out of load balancer pool
        local_action: command /usr/bin/take_out_of_pool {{ inventory_hostname }}
    
    # ...
    
      - name: add back to load balancer pool
        local_action: command /usr/bin/add_back_to_pool {{ inventory_hostname }}
    

    A common pattern is to use a local action to call ‘rsync’ to recursively copy files to the managed servers. Here is an example:

    ---
    # ...
      tasks:
    
      - name: recursively copy files from management server to target
        local_action: command rsync -a /path/to/files {{ inventory_hostname }}:/path/to/target/
    

    Note that you must have passphrase-less SSH keys or an ssh-agent configured for this to work, otherwise rsync will need to ask for a passphrase.

    How to specify maven's distributionManagement organisation wide?

    Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository in your settings.xml or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.

    A workaround is as follows. In the value:

    releases::default::https://YOUR_NEXUS_URL/releases
    

    you need to remove the default section, making it:

    releases::https://YOUR_NEXUS_URL/releases
    

    The prior version 2.8.2 does not have this bug.

    What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

    Well, like Dean said, you can look at the registry and do what he did. To check if he really has CLR .NET Framework installed, you should look for the MSCorEE.dll file in the %SystemRoot%\System32 directory.

    How do I update a Tomcat webapp without restarting the entire service?

    There are multiple easy ways.

    1. Just touch web.xml of any webapp.

      touch /usr/share/tomcat/webapps/<WEBAPP-NAME>/WEB-INF/web.xml
      

    You can also update a particular jar file in WEB-INF/lib and then touch web.xml, rather than building whole war file and deploying it again.

    1. Delete webapps/YOUR_WEB_APP directory, Tomcat will start deploying war within 5 seconds (assuming your war file still exists in webapps folder).

    2. Generally overwriting war file with new version gets redeployed by tomcat automatically. If not, you can touch web.xml as explained above.

    3. Copy over an already exploded "directory" to your webapps folder

    Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

    I had the same problem when trying to deploy, tomcat failed to restart as Tomcat instance was running. Close the IDE and check TASk Manager - kill any javaw process running, that solved the problem for me.

    How do I deploy Node.js applications as a single executable file?

    You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.

    #git submodule [--quiet] add [-b branch] [-f|--force]
    git submodule add /var/Node-repo.git common
    

    You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.

    #!/bin/sh
    #clone git repo
    git clone your-repo.git
    

    How can I deploy an iPhone application from Xcode to a real iPhone device?

    Free Provisioning after Xcode 7

    In order to test your app on a real device rather than pay the Apple Developer fee (or jailbreak your device), you can use the new free provisioning that Xcode 7 and iOS 9 supports.

    Here are the steps taken more or less from the documentation (which is pretty good, so give it a read):

    1. Add your Apple ID in Xcode

    Go to XCode > Preferences > Accounts tab > Add button (+) > Add Apple ID. See the docs for more help.

    enter image description here

    2. Click the General tab in the Project Navigator

    enter image description here

    3. Choose your Apple ID from the Team popup menu.

    enter image description here

    4. Connect your device and choose it in the scheme menu.

    enter image description here

    5. Click the Fix Issues button

    enter image description here

    If you get an error about the bundle name being invalid, change it to something unique.

    6. Run your app

    In Xcode, click the Build and run button.

    enter image description here

    7. Trust the app developer in the device settings

    After running your app, you will get a security error because the app you want to run is not from the App Store.

    enter image description here

    On your device, go to Settings > General > Profile > your-Apple-ID-name > Trust your-Apple-ID-name > Trust.

    8. Run your app on your device again.

    That's it. You can now run your own (or any other apps that you have the source code for) without having to dish out the $99 dollars. Thank you, Apple, for finally allowing this.

    FAIL - Application at context path /Hello could not be started

    Is EmailHandler really the full name of your servlet class, i.e. it's not in a package like com.something.EmailHandler? It has to be fully-qualified in web.xml.

    error: This is probably not a problem with npm. There is likely additional logging output above

    I already have the same problem . and I fix it using npm update & npm cache clean --force

    repository element was not specified in the POM inside distributionManagement element or in -DaltDep loymentRepository=id::layout::url parameter

    The issue is fixed by adding repository url under distributionManagement tab in main pom.xml.

    Jenkin maven goal : clean deploy -U -Dmaven.test.skip=true

    <distributionManagement>
        <repository>
            <id>releases</id>
            <url>http://domain:port/content/repositories/releases</url>
        </repository>
        <snapshotRepository>
            <id>snapshots</id>
            <url>http://domain:port/content/repositories/snapshots</url>
        </snapshotRepository>
    </distributionManagement>
    

    Android device chooser - My device seems offline

    Did you accept the fingerprint for your computer on the device ? When you attach your PC a prompt will be displayed on your phone/device to add this fingerprint/token and trust it.

    Error when deploying an artifact in Nexus

    I had this exact problem today and the problem was that the version I was trying to release:perform was already in the Nexus repo.

    In my case this was likely due to a network disconnect during an earlier invocation of release:perform. Even though I lost my connection, it appears the release succeeded.

    Heroku deployment error H10 (App crashed)

    I know this question is very old. I add new answer just in case there is someone who has the same issue on Rails 3.

    In my case, app started to crash on Heroku once "thin" gem was commented by accident on Gemfile.

    It worked again I added back that gem.

    Ant error when trying to build file, can't find tools.jar?

    I found that even though my path is set to JDK, the ant wants the tools.jar from jre folder. So just copy paste the tools.jar folder from JDK to jre.

    .war vs .ear file

    To make the project transport, deployment made easy. need to compressed into one file. JAR (java archive) group of .class files

    WAR (web archive) - each war represents one web application - use only web related technologies like servlet, jsps can be used. - can run on Tomcat server - web app developed by web related technologies only jsp servlet html js - info representation only no transactions.

    EAR (enterprise archive) - each ear represents one enterprise application - we can use anything from j2ee like ejb, jms can happily be used. - can run on Glassfish like server not on Tomcat server. - enterprise app devloped by any technology anything from j2ee like all web app plus ejbs jms etc. - does transactions with info representation. eg. Bank app, Telecom app

    How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

    I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

    After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

    What is path of JDK on Mac ?

    Which Mac version are you using? try these paths

     /System/Library/Frameworks/JavaVM.framework/ OR
     /usr/libexec/java_home
    

    This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X

    What is the difference between "expose" and "publish" in Docker?

    Short answer:

    • EXPOSE is a way of documenting
    • --publish (or -p) is a way of mapping a host port to a running container port

    Notice below that:

    • EXPOSE is related to Dockerfiles ( documenting )
    • --publish is related to docker run ... ( execution / run-time )

    Exposing and publishing ports

    In Docker networking, there are two different mechanisms that directly involve network ports: exposing and publishing ports. This applies to the default bridge network and user-defined bridge networks.

    • You expose ports using the EXPOSE keyword in the Dockerfile or the --expose flag to docker run. Exposing ports is a way of documenting which ports are used, but does not actually map or open any ports. Exposing ports is optional.

    • You publish ports using the --publish or --publish-all flag to docker run. This tells Docker which ports to open on the container’s network interface. When a port is published, it is mapped to an available high-order port (higher than 30000) on the host machine, unless you specify the port to map to on the host machine at runtime. You cannot specify the port to map to on the host machine when you build the image (in the Dockerfile), because there is no way to guarantee that the port will be available on the host machine where you run the image.

    from: Docker container networking

    Update October 2019: the above piece of text is no longer in the docs but an archived version is here: docs.docker.com/v17.09/engine/userguide/networking/#exposing-and-publishing-ports

    Maybe the current documentation is the below:

    Published ports

    By default, when you create a container, it does not publish any of its ports to the outside world. To make a port available to services outside of Docker, or to Docker containers which are not connected to the container's network, use the --publish or -p flag. This creates a firewall rule which maps a container port to a port on the Docker host.

    and can be found here: docs.docker.com/config/containers/container-networking/#published-ports

    Also,

    EXPOSE

    ...The EXPOSE instruction does not actually publish the port. It functions as a type of documentation between the person who builds the image and the person who runs the container, about which ports are intended to be published.

    from: Dockerfile reference






    Service access when EXPOSE / --publish are not defined:

    At @Golo Roden's answer it is stated that::

    "If you do not specify any of those, the service in the container will not be accessible from anywhere except from inside the container itself."

    Maybe that was the case at the time the answer was being written, but now it seems that even if you do not use EXPOSE or --publish, the host and other containers of the same network will be able to access a service you may start inside that container.

    How to test this:

    I've used the following Dockerfile. Basically, I start with ubuntu and install a tiny web-server:

    FROM ubuntu
    RUN apt-get update && apt-get install -y mini-httpd
    

    I build the image as "testexpose" and run a new container with:

    docker run --rm -it testexpose bash
    

    Inside the container, I launch a few instances of mini-httpd:

    root@fb8f7dd1322d:/# mini_httpd -p 80
    root@fb8f7dd1322d:/# mini_httpd -p 8080
    root@fb8f7dd1322d:/# mini_httpd -p 8090
    

    I am then able to use curl from the host or other containers to fetch the home page of mini-httpd.


    Further reading

    Very detailed articles on the subject by Ivan Pepelnjak:

    Python os.path.join on Windows

    To be even more pedantic, the most python doc consistent answer would be:

    mypath = os.path.join('c:', os.sep, 'sourcedir')
    

    Since you also need os.sep for the posix root path:

    mypath = os.path.join(os.sep, 'usr', 'lib')
    

    Java Generics With a Class & an Interface - Together

    You can't do it with "anonymous" type parameters (ie, wildcards that use ?), but you can do it with "named" type parameters. Simply declare the type parameter at method or class level.

    import java.util.List;
    interface A{}
    interface B{}
    public class Test<E extends B & A, T extends List<E>> {
        T t;
    }
    

    Insert multiple values using INSERT INTO (SQL Server 2005)

    The syntax you are using is new to SQL Server 2008:

    INSERT INTO [MyDB].[dbo].[MyTable]
           ([FieldID]
           ,[Description])
     VALUES
           (1000,N'test'),(1001,N'test2')
    

    For SQL Server 2005, you will have to use multiple INSERT statements:

    INSERT INTO [MyDB].[dbo].[MyTable]
           ([FieldID]
           ,[Description])
     VALUES
           (1000,N'test')
    
    INSERT INTO [MyDB].[dbo].[MyTable]
           ([FieldID]
           ,[Description])
     VALUES
           (1001,N'test2')
    

    One other option is to use UNION ALL:

    INSERT INTO [MyDB].[dbo].[MyTable]
           ([FieldID]
           ,[Description])
    SELECT 1000, N'test' UNION ALL
    SELECT 1001, N'test2'
    

    How to load data to hive from HDFS without removing the source file?

    from your question I assume that you already have your data in hdfs. So you don't need to LOAD DATA, which moves the files to the default hive location /user/hive/warehouse. You can simply define the table using the externalkeyword, which leaves the files in place, but creates the table definition in the hive metastore. See here: Create Table DDL eg.:

    create external table table_name (
      id int,
      myfields string
    )
    location '/my/location/in/hdfs';
    

    Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:

    row format delimited fields terminated by ','
    

    ORA-01008: not all variables bound. They are bound

    I'd a similar problem in a legacy application, but de "--" was string parameter.

    Ex.:

    Dim cmd As New OracleCommand("INSERT INTO USER (name, address, photo) VALUES ('User1', '--', :photo)", oracleConnection)
    Dim fs As IO.FileStream = New IO.FileStream("c:\img.jpg", IO.FileMode.Open)
    Dim br As New IO.BinaryReader(fs)
    cmd.Parameters.Add(New OracleParameter("photo", OracleDbType.Blob)).Value = br.ReadBytes(fs.Length)
    cmd.ExecuteNonQuery() 'here throws ORA-01008
    

    Changing address parameter value '--' to '00' or other thing, works.

    How to show progress bar while loading, using ajax

    I know that are already many answers written for this solution however I want to show another javascript method (dependent on JQuery) in which you simply need to include ONLY a single JS File without any dependency on CSS or Gif Images in your code and that will take care of all progress bar related animations that happens during Ajax Request. You need to simnply pass javascript function like this

    var objGlobalEvent = new RegisterGlobalEvents(true, "");
    

    Preview of Fiddle Loader Type

    Here is the working fiddle for the code. https://jsfiddle.net/vibs2006/c7wukc41/3/

    C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

    void Fun(int *Pointer)
    {
      //if you want to manipulate the content of the pointer:
      *Pointer=10;
      //Here we are changing the contents of Pointer to 10
    }
    

    * before the pointer means the content of the pointer (except in declarations!)

    & before the pointer (or any variable) means the address

    EDIT:

    int someint=15;
    //to call the function
    Fun(&someint);
    //or we can also do
    int *ptr;
    ptr=&someint;
    Fun(ptr);
    

    jQuery: Can I call delay() between addClass() and such?

    I know this this is a very old post but I've combined a few of the answers into a jQuery wrapper function that supports chaining. Hope it benefits someone:

    $.fn.queueAddClass = function(className) {
        this.queue('fx', function(next) {
            $(this).addClass(className);
            next();
        });
        return this;
    };
    

    And here's a removeClass wrapper:

    $.fn.queueRemoveClass = function(className) {
        this.queue('fx', function(next) {
            $(this).removeClass(className);
            next();
        });
        return this;
    };
    

    Now you can do stuff like this - wait 1sec, add .error, wait 3secs, remove .error:

    $('#div').delay(1000).queueAddClass('error').delay(2000).queueRemoveClass('error');

    Removing numbers from string

    Not sure if your teacher allows you to use filters but...

    filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")
    

    returns-

    'aaasdffgh'
    

    Much more efficient than looping...

    Example:

    for i in range(10):
      a.replace(str(i),'')
    

    jQuery Set Cursor Position in Text Area

    In IE to move cursor on some position this code is enough:

    var range = elt.createTextRange();
    range.move('character', pos);
    range.select();
    

    Can't load AMD 64-bit .dll on a IA 32-bit platform

    Try this:

    1. Download and install a 32-bit JDK.
    2. Go to eclipse click on your project (Run As ? Run Configurations...) under Java Application branch.
    3. Go to the JRE tab and select Alternate JRE. Click on Installed JRE button, add your 32-bit JRE and select.

    SELECT INTO USING UNION QUERY

    select *
    into new_table
    from table_A
    UNION
    Select * 
    From table_B
    

    This only works if Table_A and Table_B have the same schemas

    How do I fetch multiple columns for use in a cursor loop?

    Here is slightly modified version. Changes are noted as code commentary.

    BEGIN TRANSACTION
    
    declare @cnt int
    declare @test nvarchar(128)
    -- variable to hold table name
    declare @tableName nvarchar(255)
    declare @cmd nvarchar(500) 
    -- local means the cursor name is private to this code
    -- fast_forward enables some speed optimizations
    declare Tests cursor local fast_forward for
     SELECT COLUMN_NAME, TABLE_NAME
       FROM INFORMATION_SCHEMA.COLUMNS 
      WHERE COLUMN_NAME LIKE 'pct%' 
        AND TABLE_NAME LIKE 'TestData%'
    
    open Tests
    -- Instead of fetching twice, I rather set up no-exit loop
    while 1 = 1
    BEGIN
      -- And then fetch
      fetch next from Tests into @test, @tableName
      -- And then, if no row is fetched, exit the loop
      if @@fetch_status <> 0
      begin
         break
      end
      -- Quotename is needed if you ever use special characters
      -- in table/column names. Spaces, reserved words etc.
      -- Other changes add apostrophes at right places.
      set @cmd = N'exec sp_rename ''' 
               + quotename(@tableName) 
               + '.' 
               + quotename(@test) 
               + N''',''' 
               + RIGHT(@test,LEN(@test)-3) 
               + '_Pct''' 
               + N', ''column''' 
    
      print @cmd
    
      EXEC sp_executeSQL @cmd
    END
    
    close Tests 
    deallocate Tests
    
    ROLLBACK TRANSACTION
    --COMMIT TRANSACTION
    

    Bootstrap 3 Slide in Menu / Navbar on Mobile

    Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:

    _x000D_
    _x000D_
    $('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
      $navMenuCont = $($(this).data('target'));_x000D_
      $navMenuCont.animate({_x000D_
        'width': 'toggle'_x000D_
      }, 350);_x000D_
      $(".menu-overlay").fadeIn(500);_x000D_
    });_x000D_
    _x000D_
    $(".menu-overlay").click(function(event) {_x000D_
      $(".navbar-toggle").trigger("click");_x000D_
      $(".menu-overlay").fadeOut(500);_x000D_
    });_x000D_
    _x000D_
    // if ($(window).width() >= 767) {_x000D_
    //     $('ul.nav li.dropdown').hover(function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
    //     }, function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
    //     });_x000D_
    _x000D_
    //     $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
    //     }, function() {_x000D_
    //         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
    //     });_x000D_
    _x000D_
    _x000D_
    //     $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    //         event.preventDefault();_x000D_
    //         event.stopPropagation();_x000D_
    //         $(this).parent().siblings().removeClass('open');_x000D_
    //         $(this).parent().toggleClass('open');_x000D_
    //         $('b', this).toggleClass("caret caret-up");_x000D_
    //     });_x000D_
    // }_x000D_
    _x000D_
    // $(window).resize(function() {_x000D_
    //     if( $(this).width() >= 767) {_x000D_
    //         $('ul.nav li.dropdown').hover(function() {_x000D_
    //             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
    //         }, function() {_x000D_
    //             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
    //         });_x000D_
    //     }_x000D_
    // });_x000D_
    _x000D_
    var windowWidth = $(window).width();_x000D_
    if (windowWidth > 767) {_x000D_
      // $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
      //     event.preventDefault();_x000D_
      //     event.stopPropagation();_x000D_
      //     $(this).parent().siblings().removeClass('open');_x000D_
      //     $(this).parent().toggleClass('open');_x000D_
      //     $('b', this).toggleClass("caret caret-up");_x000D_
      // });_x000D_
    _x000D_
      $('ul.nav li.dropdown').hover(function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
      }, function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
      });_x000D_
    _x000D_
      $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
      }, function() {_x000D_
        $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
      });_x000D_
    _x000D_
    _x000D_
      $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
        event.preventDefault();_x000D_
        event.stopPropagation();_x000D_
        $(this).parent().siblings().removeClass('open');_x000D_
        $(this).parent().toggleClass('open');_x000D_
        // $('b', this).toggleClass("caret caret-up");_x000D_
      });_x000D_
    }_x000D_
    if (windowWidth < 767) {_x000D_
      $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
        event.preventDefault();_x000D_
        event.stopPropagation();_x000D_
        $(this).parent().siblings().removeClass('open');_x000D_
        $(this).parent().toggleClass('open');_x000D_
        // $('b', this).toggleClass("caret caret-up");_x000D_
      });_x000D_
    }_x000D_
    _x000D_
    // $('.dropdown a').append('Some text');
    _x000D_
    @media only screen and (max-width: 767px) {_x000D_
      #slide-navbar-collapse {_x000D_
        position: fixed;_x000D_
        top: 0;_x000D_
        left: 15px;_x000D_
        z-index: 999999;_x000D_
        width: 280px;_x000D_
        height: 100%;_x000D_
        background-color: #f9f9f9;_x000D_
        overflow: auto;_x000D_
        bottom: 0;_x000D_
        max-height: inherit;_x000D_
      }_x000D_
      .menu-overlay {_x000D_
        display: none;_x000D_
        background-color: #000;_x000D_
        bottom: 0;_x000D_
        left: 0;_x000D_
        opacity: 0.5;_x000D_
        filter: alpha(opacity=50);_x000D_
        /* IE7 & 8 */_x000D_
        position: fixed;_x000D_
        right: 0;_x000D_
        top: 0;_x000D_
        z-index: 49;_x000D_
      }_x000D_
      .navbar-fixed-top {_x000D_
        position: initial !important;_x000D_
      }_x000D_
      .navbar-nav .open .dropdown-menu {_x000D_
        background-color: #ffffff;_x000D_
      }_x000D_
      ul.nav.navbar-nav li {_x000D_
        border-bottom: 1px solid #eee;_x000D_
      }_x000D_
      .navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
      .navbar-nav .open .dropdown-menu>li>a {_x000D_
        padding: 10px 20px 10px 15px;_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    .dropdown-submenu {_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    .dropdown-submenu .dropdown-menu {_x000D_
      top: 0;_x000D_
      left: 100%;_x000D_
      margin-top: -1px;_x000D_
    }_x000D_
    _x000D_
    li.dropdown a {_x000D_
      display: block;_x000D_
      position: relative;_x000D_
    }_x000D_
    _x000D_
    li.dropdown>a:before {_x000D_
      content: "\f107";_x000D_
      font-family: FontAwesome;_x000D_
      position: absolute;_x000D_
      right: 6px;_x000D_
      top: 5px;_x000D_
      font-size: 15px;_x000D_
    }_x000D_
    _x000D_
    li.dropdown-submenu>a:before {_x000D_
      content: "\f107";_x000D_
      font-family: FontAwesome;_x000D_
      position: absolute;_x000D_
      right: 6px;_x000D_
      top: 10px;_x000D_
      font-size: 15px;_x000D_
    }_x000D_
    _x000D_
    ul.dropdown-menu li {_x000D_
      border-bottom: 1px solid #eee;_x000D_
    }_x000D_
    _x000D_
    .dropdown-menu {_x000D_
      padding: 0px;_x000D_
      margin: 0px;_x000D_
      border: none !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown.open {_x000D_
      border-bottom: 0px !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown-submenu.open {_x000D_
      border-bottom: 0px !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown-submenu>a {_x000D_
      font-weight: bold !important;_x000D_
    }_x000D_
    _x000D_
    li.dropdown>a {_x000D_
      font-weight: bold !important;_x000D_
    }_x000D_
    _x000D_
    .navbar-default .navbar-nav>li>a {_x000D_
      font-weight: bold !important;_x000D_
      padding: 10px 20px 10px 15px;_x000D_
    }_x000D_
    _x000D_
    li.dropdown>a:before {_x000D_
      content: "\f107";_x000D_
      font-family: FontAwesome;_x000D_
      position: absolute;_x000D_
      right: 6px;_x000D_
      top: 9px;_x000D_
      font-size: 15px;_x000D_
    }_x000D_
    _x000D_
    @media (min-width: 767px) {_x000D_
      li.dropdown-submenu>a {_x000D_
        padding: 10px 20px 10px 15px;_x000D_
      }_x000D_
      li.dropdown>a:before {_x000D_
        content: "\f107";_x000D_
        font-family: FontAwesome;_x000D_
        position: absolute;_x000D_
        right: 3px;_x000D_
        top: 12px;_x000D_
        font-size: 15px;_x000D_
      }_x000D_
    }
    _x000D_
    <!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
    _x000D_
      <head>_x000D_
        <title>Bootstrap Example</title>_x000D_
        <meta charset="utf-8">_x000D_
        <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
    _x000D_
      </head>_x000D_
    _x000D_
      <body>_x000D_
        <nav class="navbar navbar-default navbar-fixed-top">_x000D_
          <div class="container-fluid">_x000D_
            <!-- Brand and toggle get grouped for better mobile display -->_x000D_
            <div class="navbar-header">_x000D_
              <button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
                        <span class="sr-only">Toggle navigation</span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                        <span class="icon-bar"></span>_x000D_
                    </button>_x000D_
              <a class="navbar-brand" href="#">Brand</a>_x000D_
            </div>_x000D_
            <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
            <div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
              <ul class="nav navbar-nav">_x000D_
                <li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
                <li><a href="#">Link</a></li>_x000D_
                <li class="dropdown">_x000D_
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">Action</a></li>_x000D_
                    <li><a href="#">Another action</a></li>_x000D_
                    <li><a href="#">Something else here</a></li>_x000D_
                    <li><a href="#">Separated link</a></li>_x000D_
                    <li><a href="#">One more separated link</a></li>_x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li class="dropdown-submenu">_x000D_
                          <a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
                          <ul class="dropdown-menu">_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                            <li><a href="#">3rd level dropdown</a></li>_x000D_
                          </ul>_x000D_
                        </li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
                <li><a href="#">Link</a></li>_x000D_
              </ul>_x000D_
              <ul class="nav navbar-nav navbar-right">_x000D_
                <li><a href="#">Link</a></li>_x000D_
                <li class="dropdown">_x000D_
                  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">Action</a></li>_x000D_
                    <li><a href="#">Another action</a></li>_x000D_
                    <li><a href="#">Something else here</a></li>_x000D_
                    <li><a href="#">Separated link</a></li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </div>_x000D_
            <!-- /.navbar-collapse -->_x000D_
          </div>_x000D_
          <!-- /.container-fluid -->_x000D_
        </nav>_x000D_
        <div class="menu-overlay"></div>_x000D_
        <div class="col-md-12">_x000D_
          <h1>Resize the window to see the result</h1>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
          <p>_x000D_
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
            ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
            dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
            condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
          </p>_x000D_
        </div>_x000D_
    _x000D_
      </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    Reference JS fiddle

    Is there a REAL performance difference between INT and VARCHAR primary keys?

    At HauteLook, we changed many of our tables to use natural keys. We did experience a real-world increase in performance. As you mention, many of our queries now use less joins which makes the queries more performant. We will even use a composite primary key if it makes sense. That being said, some tables are just easier to work with if they have a surrogate key.

    Also, if you are letting people write interfaces to your database, a surrogate key can be helpful. The 3rd party can rely on the fact that the surrogate key will change only in very rare circumstances.

    VBA Count cells in column containing specified value

    Do you mean you want to use a formula in VBA? Something like:

    Dim iVal As Integer
    iVal = Application.WorksheetFunction.COUNTIF(Range("A1:A10"),"Green")
    

    should work.

    Is it possible to use the SELECT INTO clause with UNION [ALL]?

    SELECT * INTO tmpFerdeen FROM 
    (SELECT top(100)*  
    FROM Customers 
    UNION All 
    SELECT top(100)*  
    FROM CustomerEurope 
    UNION All 
    SELECT top(100)*  
    FROM CustomerAsia 
    UNION All 
    SELECT top(100)*  
    FROM CustomerAmericas) AS Blablabal
    

    This "Blablabal" is necessary

    sql insert into table with select case values

    You have the alias inside of the case, it needs to be outside of the END:

    Insert into TblStuff (FullName,Address,City,Zip)
    Select
      Case
        When Middle is Null 
        Then Fname + LName
        Else Fname +' ' + Middle + ' '+ Lname
      End as FullName,
      Case
        When Address2 is Null Then Address1
        else Address1 +', ' + Address2 
      End as  Address,
      City as City,
      Zip as Zip
    from tblImport
    

    R: invalid multibyte string

    If you want an R solution, here's a small convenience function I sometimes use to find where the offending (multiByte) character is lurking. Note that it is the next character to what gets printed. This works because print will work fine, but substr throws an error when multibyte characters are present.

    find_offending_character <- function(x, maxStringLength=256){  
      print(x)
      for (c in 1:maxStringLength){
        offendingChar <- substr(x,c,c)
        #print(offendingChar) #uncomment if you want the indiv characters printed
        #the next character is the offending multibyte Character
      }    
    }
    
    string_vector <- c("test", "Se\x96ora", "works fine")
    
    lapply(string_vector, find_offending_character)
    

    I fix that character and run this again. Hope that helps someone who encounters the invalid multibyte string error.

    How to declare strings in C

    This link should satisfy your curiosity.

    Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.

    But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.

    TypeError: 'str' object is not callable (Python)

    I had yet another issue with the same error!

    Turns out I had created a property on a model, but was stupidly calling that property with parentheses.

    Hope this helps someone!

    Can vue-router open a link in a new tab?

    For those who are wondering the answer is no. See related issue on github.

    Q: Can vue-router open link in new tab progammaticaly

    A: No. use a normal link.

    How to Convert double to int in C?

    I suspect you don't actually have that problem - I suspect you've really got:

    double a = callSomeFunction();
    // Examine a in the debugger or via logging, and decide it's 3669.0
    
    // Now cast
    int b = (int) a;
    // Now a is 3668
    

    What makes me say that is that although it's true that many decimal values cannot be stored exactly in float or double, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)

    I strongly suspect that your double value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.

    Assuming your double type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly

    3668.99999999999954525264911353588104248046875
    

    So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.

    How to time Java program execution speed

    You can use Stopwatch

    import com.google.common.base.Stopwatch;
    
    Stopwatch timer = Stopwatch.createStarted();
    //lines to be executed
    System.out.println("Execution time= " + timer.stop());
    

    How do I tell if a variable has a numeric value in Perl?

    I found this interesting though

    if ( $value + 0 eq $value) {
        # A number
        push @args, $value;
    } else {
        # A string
        push @args, "'$value'";
    }
    

    How to force the browser to reload cached CSS and JavaScript files

    If you are using jQuery, there is an option called cache that will append a random number.

    This is not a complete answer I know, but it might save you some time.

    Adding files to a GitHub repository

    You can use Git GUI on Windows, see instructions:

    1. Open the Git Gui (After installing the Git on your computer).

    enter image description here

    1. Clone your repository to your local hard drive:

    enter image description here

    1. After cloning, GUI opens, choose: "Rescan" for changes that you made:

    enter image description here

    1. You will notice the scanned files:

    enter image description here

    1. Click on "Stage Changed":

    enter image description here

    1. Approve and click "Commit":

    enter image description here

    1. Click on "Push":

    enter image description here

    1. Click on "Push":

    enter image description here

    1. Wait for the files to upload to git:

    enter image description here

    enter image description here

    What special characters must be escaped in regular expressions?

    Sometimes simple escaping is not possible with the characters you've listed. For example, using a backslash to escape a bracket isn't going to work in the left hand side of a substitution string in sed, namely

    sed -e 's/foo\(bar/something_else/'
    

    I tend to just use a simple character class definition instead, so the above expression becomes

    sed -e 's/foo[(]bar/something_else/'
    

    which I find works for most regexp implementations.

    BTW Character classes are pretty vanilla regexp components so they tend to work in most situations where you need escaped characters in regexps.

    Edit: After the comment below, just thought I'd mention the fact that you also have to consider the difference between finite state automata and non-finite state automata when looking at the behaviour of regexp evaluation.

    You might like to look at "the shiny ball book" aka Effective Perl (sanitised Amazon link), specifically the chapter on regular expressions, to get a feel for then difference in regexp engine evaluation types.

    Not all the world's a PCRE!

    Anyway, regexp's are so clunky compared to SNOBOL! Now that was an interesting programming course! Along with the one on Simula.

    Ah the joys of studying at UNSW in the late '70's! (-:

    How to hide app title in android?

    use

    <activity android:name=".ActivityName" 
              android:theme="@android:style/Theme.NoTitleBar">
    

    jQuery removeClass wildcard

    An alternative way of approaching this problem is to use data attributes, which are by nature unique.

    You'd set the colour of an element like: $el.attr('data-color', 'red');

    And you'd style it in css like: [data-color="red"]{ color: tomato; }

    This negates the need for using classes, which has the side-effect of needing to remove old classes.

    decimal vs double! - Which one should I use and when?

    I think that the main difference beside bit width is that decimal has exponent base 10 and double has 2

    http://software-product-development.blogspot.com/2008/07/net-double-vs-decimal.html

    git status shows fatal: bad object HEAD

    I solved this by copying the branch data (with the errors) to my apple laptop local git folder.

    Somehow in the terminal and when running: git status, tells me more specific data where the error occurs. If you look under the errors, hopefully you see a list of folders with error. In my case GIT showed the folder which was responsible for the error. Deleting that folder and commiting the branche, I succeeded. git status was working again the other devices updating by git pull; everything working again on every machine.

    Hopefully this will work for you also.

    Android Room - simple select query - Cannot access database on the main thread

    With lambda its easy to run with AsyncTask

     AsyncTask.execute(() -> //run your query here );
    

    How do I declare a global variable in VBA?

    The question is really about scope, as the other guy put it.

    In short, consider this "module":

    Public Var1 As variant     'Var1 can be used in all
                               'modules, class modules and userforms of 
                               'thisworkbook and will preserve any values
                               'assigned to it until either the workbook
                               'is closed or the project is reset.
    
    Dim Var2 As Variant        'Var2 and Var3 can be used anywhere on the
    Private Var3 As Variant    ''current module and will preserve any values
                               ''they're assigned until either the workbook
                               ''is closed or the project is reset.
    
    Sub MySub()                'Var4 can only be used within the procedure MySub
        Dim Var4 as Variant    ''and will only store values until the procedure 
    End Sub                    ''ends.
    
    Sub MyOtherSub()           'You can even declare another Var4 within a
        Dim Var4 as Variant    ''different procedure without generating an
    End Sub                    ''error (only possible confusion). 
    

    You can check out this MSDN reference for more on variable declaration and this other Stack Overflow Question for more on how variables go out of scope.

    Two other quick things:

    1. Be organized when using workbook level variables, so your code doesn't get confusing. Prefer Functions (with proper data types) or passing arguments ByRef.
    2. If you want a variable to preserve its value between calls, you can use the Static statement.

    Get the full URL in PHP

    Simply use:

    $uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
    

    Add hover text without javascript like we hover on a user's reputation

    Use the title attribute, for example:

    _x000D_
    _x000D_
    <div title="them's hoverin' words">hover me</div>
    _x000D_
    _x000D_
    _x000D_

    or:

    _x000D_
    _x000D_
    <span title="them's hoverin' words">hover me</span>
    _x000D_
    _x000D_
    _x000D_

    checking memory_limit in PHP

    Here is another simpler way to check that.

    $memory_limit = return_bytes(ini_get('memory_limit'));
    if ($memory_limit < (64 * 1024 * 1024)) {
        // Memory insufficient      
    }
    
    /**
    * Converts shorthand memory notation value to bytes
    * From http://php.net/manual/en/function.ini-get.php
    *
    * @param $val Memory size shorthand notation string
    */
    function return_bytes($val) {
        $val = trim($val);
        $last = strtolower($val[strlen($val)-1]);
        $val = substr($val, 0, -1);
        switch($last) {
            // The 'G' modifier is available since PHP 5.1.0
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }
        return $val;
    }
    

    Alternative to header("Content-type: text/xml");

    Now I see what you are doing. You cannot send output to the screen then change the headers. If you are trying to create an XML file of map marker and download them to display, they should be in separate files.

    Take this

    <?php
    require("database.php");
    function parseToXML($htmlStr)
    {
    $xmlStr=str_replace('<','&lt;',$htmlStr);
    $xmlStr=str_replace('>','&gt;',$xmlStr);
    $xmlStr=str_replace('"','&quot;',$xmlStr);
    $xmlStr=str_replace("'",'&#39;',$xmlStr);
    $xmlStr=str_replace("&",'&amp;',$xmlStr);
    return $xmlStr;
    }
    // Opens a connection to a MySQL server
    $connection=mysql_connect (localhost, $username, $password);
    if (!$connection) {
      die('Not connected : ' . mysql_error());
    }
    // Set the active MySQL database
    $db_selected = mysql_select_db($database, $connection);
    if (!$db_selected) {
      die ('Can\'t use db : ' . mysql_error());
    }
    // Select all the rows in the markers table
    $query = "SELECT * FROM markers WHERE 1";
    $result = mysql_query($query);
    if (!$result) {
      die('Invalid query: ' . mysql_error());
    }
    header("Content-type: text/xml");
    // Start XML file, echo parent node
    echo '<markers>';
    // Iterate through the rows, printing XML nodes for each
    while ($row = @mysql_fetch_assoc($result)){
      // ADD TO XML DOCUMENT NODE
      echo '<marker ';
      echo 'name="' . parseToXML($row['name']) . '" ';
      echo 'address="' . parseToXML($row['address']) . '" ';
      echo 'lat="' . $row['lat'] . '" ';
      echo 'lng="' . $row['lng'] . '" ';
      echo 'type="' . $row['type'] . '" ';
      echo '/>';
    }
    // End XML file
    echo '</markers>';
    ?>
    

    and place it in phpsqlajax_genxml.php so your javascript can download the XML file. You are trying to do too many things in the same file.

    How do I sort a dictionary by value?

    Starting from Python 3.6, dict objects are now ordered by insertion order. It's officially in the specs of Python 3.7.

    >>> words = {"python": 2, "blah": 4, "alice": 3}
    >>> dict(sorted(words.items(), key=lambda x: x[1]))
    {'python': 2, 'alice': 3, 'blah': 4}
    

    Before that, you had to use OrderedDict.

    Python 3.7 documentation says:

    Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was implementation detail of CPython from 3.6.

    The project cannot be built until the build path errors are resolved.

    Go to > Right CLick on your project folder > Build Path > Configure Build Path > Libraries Tab > remove project and external dependencies > apply & close

    Now, Gradle refresh your project.

    Why is IoC / DI not common in Python?

    I agree with @Jorg in the point that DI/IoC is possible, easier and even more beautiful in Python. What's missing is the frameworks supporting it, but there are a few exceptions. To point a couple of examples that come to my mind:

    • Django comments let you wire your own Comment class with your custom logic and forms. [More Info]

    • Django let you use a custom Profile object to attach to your User model. This is not completely IoC but is a good approach. Personally I'd like to replace the hole User model as the comments framework does. [More Info]

    JSON - Iterate through JSONArray

    for(int i = 0; i < getArray.size(); i++){
          Object object = getArray.get(i);
          // now do something with the Object
    }
    

    You need to check for the type:

    The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]

    In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names() to retrieve the individual keys.

    Regular expression include and exclude special characters

    For the allowed characters you can use

    ^[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$
    

    to validate a complete string that should consist of only allowed characters. Note that - is at the end (because otherwise it'd be a range) and a few characters are escaped.

    For the invalid characters you can use

    [<>'"/;`%]
    

    to check for them.

    To combine both into a single regex you can use

    ^(?=[a-zA-Z0-9~@#$^*()_+=[\]{}|\\,.?: -]*$)(?!.*[<>'"/;`%])
    

    but you'd need a regex engine that allows lookahead.

    DBMS_OUTPUT.PUT_LINE not printing

    this statement

    DBMS_OUTPUT.PUT_LINE('a.firstName' || 'a.lastName');

    means to print the string as it is.. remove the quotes to get the values to be printed.So the correct syntax is

    DBMS_OUTPUT.PUT_LINE(a.firstName || a.lastName);
    

    Efficient way to update all rows in a table

    Might not work you for, but a technique I've used a couple times in the past for similar circumstances.

    created updated_{table_name}, then select insert into this table in batches. Once finished, and this hinges on Oracle ( which I don't know or use ) supporting the ability to rename tables in an atomic fashion. updated_{table_name} becomes {table_name} while {table_name} becomes original_{table_name}.

    Last time I had to do this was for a heavily indexed table with several million rows that absolutely positively could not be locked for the duration needed to make some serious changes to it.

    Java swing application, close one window and open another when button is clicked

    Use this.dispose for current window to close and next_window.setVisible(true) to show next window behind button property ActionPerformed , Example is shown below in pic for your help.

    enter image description here

    How to update all MySQL table rows at the same time?

    You can try this,

    UPDATE *tableName* SET *field1* = *your_data*, *field2* = *your_data* ... WHERE 1 = 1;
    

    Well in your case if you want to update your online_status to some value, you can try this,

    UPDATE thisTable SET online_status = 'Online' WHERE 1 = 1;
    

    Hope it helps. :D

    Finding the max value of an attribute in an array of objects

    Here is the shortest solution (One Liner) ES6:

    Math.max(...values.map(o => o.y));
    

    how to load CSS file into jsp

    You can write like that. This is for whenever you change context path you don't need to modify your jsp file.

    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/styles.css" />
    

    How can I create 2 separate log files with one log4j config file?

    Modify your log4j.properties file accordingly:

    log4j.rootLogger=TRACE,stdout
    ...
    log4j.logger.debugLog=TRACE,debugLog
    log4j.logger.reportsLog=DEBUG,reportsLog
    

    Change the log levels for each logger depending to your needs.

    node.js Error: connect ECONNREFUSED; response from server

    I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...

    How to call URL action in MVC with javascript function?

    Within your onDropDownChange handler, just make a jQuery AJAX call, passing in any data you need to pass up to your URL. You can handle successful and failure calls with the success and error options. In the success option, use the data contained in the data argument to do whatever rendering you need to do. Remember these are asynchronous by default!

    function onDropDownChange(e) {
        var url = '/Home/Index/' + e.value;
        $.ajax({
          url: url,
          data: {}, //parameters go here in object literal form
          type: 'GET',
          datatype: 'json',
          success: function(data) { alert('got here with data'); },
          error: function() { alert('something bad happened'); }
        });
    }
    

    jQuery's AJAX documentation is here.

    Can I rollback a transaction I've already committed? (data loss)

    No, you can't undo, rollback or reverse a commit.

    STOP THE DATABASE!

    (Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

    If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

    You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

    If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

    Urgent mitigation

    Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

    Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

    Ways some data could've survived

    If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

    Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

    Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

    Recovery

    You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

    I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

    See: pg_dirtyread on GitHub.

    I've removed what I'd written in this section as it's obsoleted by that tool.

    See also PostgreSQL row storage fundamentals

    Prevention

    See my blog entry Preventing PostgreSQL database corruption.


    On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

    How can I create Min stl priority_queue?

    One Way to solve this problem is, push the negative of each element in the priority_queue so the largest element will become the smallest element. At the time of making pop operation, take the negation of each element.

    #include<bits/stdc++.h>
    using namespace std;
    
    int main(){
        priority_queue<int> pq;
        int i;
    
    // push the negative of each element in priority_queue, so the largest number will become the smallest number
    
        for (int i = 0; i < 5; i++)
        {
            cin>>j;
            pq.push(j*-1);
        }
    
        for (int i = 0; i < 5; i++)
        {
            cout<<(-1)*pq.top()<<endl;
            pq.pop();
        }
    }
    

    How can I search for a commit message on GitHub?

    Update (2017/01/05):

    GitHub has published an update that allows you now to search within commit messages from within their UI. See blog post for more information.


    I had the same question and contacted someone GitHub yesterday:

    Since they switched their search engine to Elasticsearch it's not possible to search for commit messages using the GitHub UI. But that feature is on the team's wishlist.

    Unfortunately there's no release date for that function right now.

    Recover sa password

    The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

    If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

    Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

    You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

    As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

    I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

    And some other resources:

    Google Geocoding API - REQUEST_DENIED

    It's suck Google don't let you that your service is not enabled by this account. Try to enable it first. Go here https://console.developers.google.com/project and create a new project with place service activated this may solve your problem.

    Makefile - missing separator

    You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

    PROG = semsearch
    all: $(PROG)
    %: %.c
            gcc -o $@ $< -lpthread
    
    clean:
            rm $(PROG)
    

    Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

    PROG = semsearch
    all: $(PROG)
    %: %.c ; gcc -o $@ $< -lpthread
    
    clean: ; rm $(PROG)
    

    ExecJS and could not find a JavaScript runtime

    In your Gem file, write

    gem 'execjs'
    gem 'therubyracer'
    

    and then run

    bundle install
    

    Everything works fine for me :)

    Converting string format to datetime in mm/dd/yyyy

    I did like this

    var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);
    

    Conditional Count on a field

    SELECT  Priority, COALESCE(cnt, 0)
    FROM    (
            SELECT  1 AS Priority
            UNION ALL
            SELECT  2 AS Priority
            UNION ALL
            SELECT  3 AS Priority
            UNION ALL
            SELECT  4 AS Priority
            UNION ALL
            SELECT  5 AS Priority
            ) p
    LEFT JOIN
            (
            SELECT  Priority, COUNT(*) AS cnt
            FROM    jobs
            GROUP BY
                    Priority
            ) j
    ON      j.Priority = p.Priority
    

    Google Chrome redirecting localhost to https

    Piggybacking off Adiyat Mubarak

    Could not hard refresh as it was just refreshing on https. Follows some of the same steps.

    1. Open chrome developer tools (ctrl + shift + i)
    2. Network Tab at the top
    3. Click Disable cache checkbox at the top (right under network tab for me).
    4. Refresh page (while the developer tools is still open)
    

    Change the maximum upload file size

    You can also use ini_set function (only for PHP version below 5.3):

    ini_set('post_max_size', '64M');
    ini_set('upload_max_filesize', '64M');
    

    Like @acme said, in php 5.3 and above this settings are PHP_INI_PERDIR directives so they can't be set using ini_set. You can use user.ini instead.

    Call multiple functions onClick ReactJS

    Calling multiple functions on onClick for any element, you can create a wrapper function, something like this.

    wrapperFunction = () => {
        //do something
        function 1();
        //do something
        function 2();
        //do something
        function 3();
    }
    

    These functions can be defined as a method on the parent class and then called from the wrapper function.

    You may have the main element which will cause the onChange like this,

    <a href='#' onClick={this.wrapperFunction}>Some Link</a>
    

    How to disable gradle 'offline mode' in android studio?

    On Windows:-

    Go to File -> Settings.

    And open the 'Build,Execution,Deployment'. Then open the

    Build Tools -> Gradle

    Then uncheck -> Offline work on the right.

    Click the OK button.

    Then Rebuild the Project.

    On Mac OS:-

    go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image

    [For Mac go 1

    enter image description here

    Save results to csv file with Python

    You can close files not csv.writer object, it should be:

    f = open(fileName, "wb")
    writer = csv.writer(f)
    String[] entries = "first*second*third".split("*");
    writer.writerows(entries)
    f.close()
    

    How do I install pip on macOS or OS X?

    Install python3 first, then use pip3 to install packages.

    brew install python
    

    python3 will be installed, and pip is shipped with it. To use pip to install some package, run the following

    pip3 install package
    

    Notice it's pip3 because you want to use python3.

    Node.js check if path is file or directory

    Seriously, question exists five years and no nice facade?

    function is_dir(path) {
        try {
            var stat = fs.lstatSync(path);
            return stat.isDirectory();
        } catch (e) {
            // lstatSync throws an error if path doesn't exist
            return false;
        }
    }
    

    How to write lists inside a markdown table?

    Not that I know of, because all markdown references I am aware of, like this one, mention:

    Cell content must be on one line only

    You can try it with that Markdown Tables Generator (whose example looks like the one you mention in your question, so you may be aware of it already).

    Pandoc

    If you are using Pandoc’s markdown (which extends John Gruber’s markdown syntax on which the GitHub Flavored Markdown is based) you can use either grid_tables:

    +---------------+---------------+--------------------+
    | Fruit         | Price         | Advantages         |
    +===============+===============+====================+
    | Bananas       | $1.34         | - built-in wrapper |
    |               |               | - bright color     |
    +---------------+---------------+--------------------+
    | Oranges       | $2.10         | - cures scurvy     |
    |               |               | - tasty            |
    +---------------+---------------+--------------------+
    

    or multiline_tables.

    -------------------------------------------------------------
     Centered   Default           Right Left
      Header    Aligned         Aligned Aligned
    ----------- ------- --------------- -------------------------
       First    row                12.0 Example of a row that
                                        spans multiple lines.
    
      Second    row                 5.0 Here's another one. Note
                                        the blank line between
                                        rows.
    -------------------------------------------------------------
    

    Is there a Boolean data type in Microsoft SQL Server like there is in MySQL?

    Use the Bit datatype. It has values 1 and 0 when dealing with it in native T-SQL

    SOAP request to WebService with java

    I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

    Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

    Change callSoapWebService method first line to following.

    SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

    I hope it will be helpful to others.

    How to enable support of CPU virtualization on Macbook Pro?

    CPU Virtualization is enabled by default on all MacBooks with compatible CPUs (i7 is compatible). You can try to reset PRAM if you think it was disabled somehow, but I doubt it.

    I think the issue might be in the old version of OS. If your MacBook is i7, then you better upgrade OS to something newer.

    Creating a div element inside a div element in javascript

    'b' should be in capital letter in document.getElementById modified code jsfiddle

    function test()
    {
    
    var element = document.createElement("div");
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));
    document.getElementById('lc').appendChild(element);
     //document.body.appendChild(element);
     }
    

    CSS text-align: center; is not centering things

    To make a inline-block element align center horizontally in its parent, add text-align:center to its parent.

    builtins.TypeError: must be str, not bytes

    The outfile should be in binary mode.

    outFile = open('output.xml', 'wb')
    

    "ORA-01438: value larger than specified precision allowed for this column" when inserting 3

    NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

    NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

    More info at the Oracle docs.

    Passing just a type as a parameter in C#

    There are two common approaches. First, you can pass System.Type

    object GetColumnValue(string columnName, Type type)
    {
        // Here, you can check specific types, as needed:
    
        if (type == typeof(int)) { // ...
    

    This would be called like: int val = (int)GetColumnValue(columnName, typeof(int));

    The other option would be to use generics:

    T GetColumnValue<T>(string columnName)
    {
        // If you need the type, you can use typeof(T)...
    

    This has the advantage of avoiding the boxing and providing some type safety, and would be called like: int val = GetColumnValue<int>(columnName);

    Error - replacement has [x] rows, data has [y]

    The answer by @akrun certainly does the trick. For future googlers who want to understand why, here is an explanation...

    The new variable needs to be created first.

    The variable "valueBin" needs to be already in the df in order for the conditional assignment to work. Essentially, the syntax of the code is correct. Just add one line in front of the code chuck to create this name --

    df$newVariableName <- NA
    

    Then you continue with whatever conditional assignment rules you have, like

    df$newVariableName[which(df$oldVariableName<=250)] <- "<=250"
    

    I blame whoever wrote that package's error message... The debugging was made especially confusing by that error message. It is irrelevant information that you have two arrays in the df with different lengths. No. Simply create the new column first. For more details, consult this post https://www.r-bloggers.com/translating-weird-r-errors/

    clearInterval() not working

    The setInterval function returns an integer value, which is the id of the "timer instance" that you've created.

    It is this integer value that you need to pass to clearInterval

    e.g:

    var timerID = setInterval(fontChange,500);
    

    and later

    clearInterval(timerID);
    

    VB.NET - Click Submit Button on Webbrowser page

      Private Sub bt_continue_Click(sender As Object, e As EventArgs) Handles bt_continue.Click
        wb_apple.Document.GetElementById("phoneNumber").Focus()
        wb_apple.Document.GetElementById("phoneNumber").InnerText = tb_phonenumber.Text
        wb_apple.Document.GetElementById("reservationCode").Focus()
        wb_apple.Document.GetElementById("reservationCode").InnerText = tb_regcode.Text
        'SendKeys.Send("{Tab}{Tab}{Tab}")
        'For Each Element As HtmlElement In wb_apple.Document.GetElementsByTagName("a")
        'If Element.OuterHtml.Contains("iReserve.sms.submitButtonLabel") Then
        'Element.InvokeMember("click")
        'Exit For
        ' End If
        'Next Element
        wb_apple.Document.GetElementById("smsPageForm").Focus()
        wb_apple.Document.GetElementById("smsPageForm").InvokeMember("submit")
    
    End Sub
    

    How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

    You probably just need to see the ASCII and EXTENDED ASCII character sets. As far as I know any of these are allowed in a char/varchar field.

    If you use nchar/nvarchar then it's pretty much any character in any unicode set in the world.

    enter image description here

    enter image description here

    Get ALL User Friends Using Facebook Graph API - Android

    In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

    In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

    The /me/friendlists endpoint and user_friendlists permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.

    If you want to access a list of non-app-using friends, there are two options:

    1. If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.

    2. If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.

    In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends permission).

    For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.

    Show/Hide Table Rows using Javascript classes

    Below is my Script which show/hide table row with id "agencyrow".

    <script type="text/javascript">
    
                            function showhiderow() {
                                if (document.getElementById("<%=RadioButton1.ClientID %>").checked == true) {
    
                                    document.getElementById("agencyrow").style.display = '';
                                } else {
    
                                    document.getElementById("agencyrow").style.display = 'none';
                                }
    
    
                            }
        </script> 
    

    Just call function showhiderow()upon radiobutton onClick event

    How can I get the URL of the current tab from a Google Chrome extension?

    For those using the context menu api, the docs are not immediately clear on how to obtain tab information.

      chrome.contextMenus.onClicked.addListener(function(info, tab) {
        console.log(info);
        return console.log(tab);
      });
    

    https://developer.chrome.com/extensions/contextMenus

    NodeJS / Express: what is "app.use"?

    app.use is Application level middleware

    Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

    you can use to check all requests, for example, you want to check token/access token you need to write a middleware by using app.use to check the token in the request.

    This example shows a middleware function with no mount path. The function is executed every time the app receives a request.

    var app = express()
    
    app.use(function (req, res, next) {
      console.log('Time:', Date.now())
      next()
    })
    

    reference from https://expressjs.com/en/guide/using-middleware.html

    simple way to display data in a .txt file on a webpage?

    That's the code I use:

    <?php   
        $path="C:/foopath/";
        $file="foofile.txt";
    
        //read file contents
        $content="
            <h2>$file</h2>
                <code>
                    <pre>".htmlspecialchars(file_get_contents("$path/$file"))."</pre>
                </code>";
    
        //display
        echo $content;
    ?>
    

    Keep in mind that if the user can modify $path or $file (for example via $_GET or $_POST), he/she will be able to see all your source files (danger!)

    display:inline vs display:block

    Display:block It very much behaves the same way as 'p' tags and it takes up the entire row and there can't be any element next to it until it's floated. Display:inline It's just uses as much space as required and allows other elements to be aligned alongside itself.

    Use these properties in case of forms and you will get a better understanding.

    No newline after div?

    This works like magic, use it in the CSS file on the div you want to have on the new line:

    .div_class {
        clear: left;
    }
    

    Or declare it in the html:

    <div style="clear: left">
         <!-- Content... -->
    </div>
    

    Convert Set to List without creating new List

    I found this working fine and useful to create a List from a Set.

    ArrayList < String > L1 = new ArrayList < String > ();
    L1.addAll(ActualMap.keySet());
    for (String x: L1) {
        System.out.println(x.toString());
    }
    

    gnuplot - adjust size of key/legend

    To adjust the length of the samples:

    set key samplen X
    

    (default is 4)

    To adjust the vertical spacing of the samples:

    set key spacing X
    

    (default is 1.25)

    and (for completeness), to adjust the fontsize:

    set key font "<face>,<size>"
    

    (default depends on the terminal)

    And of course, all these can be combined into one line:

    set key samplen 2 spacing .5 font ",8"
    

    Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

    Does Index of Array Exist

    The answers here are straightforward but only apply to a 1 dimensional array. For multi-dimensional arrays, checking for null is a straightforward way to tell if the element exists. Example code here checks for null. Note the try/catch block is [probably] overkill but it makes the block bomb-proof.

    public ItemContext GetThisElement(int row,
        int col)
    {
        ItemContext ctx = null;
        if (rgItemCtx[row, col] != null)
        {
            try
            {
              ctx = rgItemCtx[row, col];
            }
            catch (SystemException sex)
            {
              ctx = null;
              // perhaps do something with sex properties
            }
        }
    
        return (ctx);
    }
    

    How to use Monitor (DDMS) tool to debug application

    1 use eclipse bar to install a Mat plug-in to analyze, is a good choice. Studio Memory provides the Monitor 2.Android studio to display the memory occupancy of the application in real time.

    How to select where ID in Array Rails ActiveRecord without exception

    You can also use it in named_scope if You want to put there others conditions

    for example include some other model:

    named_scope 'get_by_ids', lambda { |ids| { :include => [:comments], :conditions => ["comments.id IN (?)", ids] } }

    Case-insensitive search in Rails model

    There are lots of great answers here, particularly @oma's. But one other thing you could try is to use custom column serialization. If you don't mind everything being stored lowercase in your db then you could create:

    # lib/serializers/downcasing_string_serializer.rb
    module Serializers
      class DowncasingStringSerializer
        def self.load(value)
          value
        end
    
        def self.dump(value)
          value.downcase
        end
      end
    end
    

    Then in your model:

    # app/models/my_model.rb
    serialize :name, Serializers::DowncasingStringSerializer
    validates_uniqueness_of :name, :case_sensitive => false
    

    The benefit of this approach is that you can still use all the regular finders (including find_or_create_by) without using custom scopes, functions, or having lower(name) = ? in your queries.

    The downside is that you lose casing information in the database.

    Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

    its work for me SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.format(new Date));

    Disable/Enable Submit Button until all forms have been filled

    Just add an else then:

    function checkform()
    {
        var f = document.forms["theform"].elements;
        var cansubmit = true;
    
        for (var i = 0; i < f.length; i++) {
            if (f[i].value.length == 0) cansubmit = false;
        }
    
        if (cansubmit) {
            document.getElementById('submitbutton').disabled = false;
        }
        else {
            document.getElementById('submitbutton').disabled = 'disabled';
        }
    }
    

    How to get the nvidia driver version from the command line?

    If you need to get that in a program with Python on a Linux system for reproducibility:

    with open('/proc/driver/nvidia/version') as f:
        version = f.read().strip()
    print(version)
    

    gives:

    NVRM version: NVIDIA UNIX x86_64 Kernel Module  384.90  Tue Sep 19 19:17:35 PDT 2017
    GCC version:  gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.5) 
    

    Unsupported method: BaseConfig.getApplicationIdSuffix()

    For Android Studio 3 I need to update two files to fix the error:--

    1. app/build.gradle

    buildscript {
        repositories {
            jcenter()
            mavenCentral()
            maven {
                url 'https://maven.google.com/'
                name 'Google'
            }
        }
    
        dependencies {
            classpath 'com.android.tools.build:gradle:3.0.1'
        }
    }
    

    2. app/gradle/wrapper/gradle-wrapper.properties

    distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip
    

    Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

    I got the very same error when trying to access the child FragmentManager before the fragment was fully initialized (i.e. attached to the Activity or at least onCreateView() called). Else the FragmentManager gets initialized with a null Activity causing the aforementioned exception.

    ProgressDialog in AsyncTask

    This question is already answered and most of the answers here are correct but they don't solve one major issue with config changes. Have a look at this article https://androidresearch.wordpress.com/2013/05/10/dealing-with-asynctask-and-screen-orientation/ if you would like to write a async task in a better way.

    usr/bin/ld: cannot find -l<nameOfTheLibrary>

    Here is Ubuntu information of my laptop.

    lsb_release -a
    No LSB modules are available.
    Distributor ID: Ubuntu
    Description:    Ubuntu 18.04.2 LTS
    Release:    18.04
    Codename:   bionic
    

    I use locate to find the .so files for boost_filesystem and boost_system

    locate libboost_filesystem
    locate libboost_system
    

    Then link .so files to /usr/lib and rename to .so

    sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_filesystem.so.1.65.1 /usr/lib/libboost_filesystem.so
    sudo ln -s /usr/lib/x86_64-linux-gnu/libboost_system.so.1.65.1 /usr/lib/libboost_system.so
    

    Done! R package velocyto.R was successfully installed!

    Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

    We use IBM Rational Application Developer (RAD) and had the same problem.

    ErrorMessage:

    Access restriction: The type 'JAXWSProperties' is not API (restriction on required library 'C:\IBM\RAD95\jdk\jre\lib\rt.jar')

    Solution:

    go to java build path and under Library tab, remove JRE System Library. Then again Add Library --> JRE System Library

    jquery.ajax Access-Control-Allow-Origin

    http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

    refer the above link for more details on Cross domain resource sharing.

    you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

    sample below:

    ajax call:

    $(document).ready(function () {
            $.ajax({
                crossDomain: true,
                type:"GET",
                contentType: "application/json; charset=utf-8",
                async:false,
                url: "<your middle man service url here>/GetQuote?callback=?",
                data: { symbol: 'ctsh' },
                dataType: "jsonp",                
                jsonpCallback: 'fnsuccesscallback'
            });
        });
    

    service (asmx) which will return jsonp:

    [WebMethod]
        [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
        public void GetQuote(String symbol,string callback)
        {          
    
            WebProxy myProxy = new WebProxy("<proxy url here>", true);
    
            myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
            StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
            SQ.Proxy = myProxy;
            String result = SQ.GetQuote(symbol);
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();
            sb.Append(callback + "(");
            sb.Append(js.Serialize(result));
            sb.Append(");");
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Write(sb.ToString());
            Context.Response.End();         
        }
    

    How to run shell script file using nodejs?

    you can go:

    var cp = require('child_process');
    

    and then:

    cp.exec('./myScript.sh', function(err, stdout, stderr) {
      // handle err, stdout, stderr
    });
    

    to run a command in your $SHELL.
    Or go

    cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
      // handle err, stdout, stderr
    });
    

    to run a file WITHOUT a shell.
    Or go

    cp.execFile();
    

    which is the same as cp.exec() but doesn't look in the $PATH.

    You can also go

    cp.fork('myJS.js', function(err, stdout, stderr) {
      // handle err, stdout, stderr
    });
    

    to run a javascript file with node.js, but in a child process (for big programs).

    EDIT

    You might also have to access stdin and stdout with event listeners. e.g.:

    var child = cp.spawn('./myScript.sh', [args]);
    child.stdout.on('data', function(data) {
      // handle stdout as `data`
    });
    

    How to add image that is on my computer to a site in css or html?

    This worked for my purposes. Pretty basic and simple, but it did what I needed (which was to get a personal photo of mine onto the internet so I could use its URL).

    1. Go to photos.google.com and open any image that you wish to embed in your website.

    2. Tap the Share Icon and then choose "Get Link" to generate a shareable link for that image.

    3. Go to j.mp/EmbedGooglePhotos, paste that link and it will instantly generate the embed code for that picture.

    4. Open your website template, paste the generated code and save. The image will now serve directly from your Google Photos account.

    Check this video tutorial out if you have trouble.

    How to convert enum names to string in c

    There is no simple way to achieves this directly. But P99 has macros that allow you to create such type of function automatically:

     P99_DECLARE_ENUM(color, red, green, blue);
    

    in a header file, and

     P99_DEFINE_ENUM(color);
    

    in one compilation unit (.c file) should then do the trick, in that example the function then would be called color_getname.

    How to remove last n characters from every element in the R vector

    Similar to @Matthew_Plourde using gsub

    However, using a pattern that will trim to zero characters i.e. return "" if the original string is shorter than the number of characters to cut:

    cs <- c("foo_bar","bar_foo","apple","beer","so","a")
    gsub('.{0,3}$', '', cs)
    # [1] "foo_" "bar_" "ap"   "b"    ""    ""
    

    Difference is, {0,3} quantifier indicates 0 to 3 matches, whereas {3} requires exactly 3 matches otherwise no match is found in which case gsub returns the original, unmodified string.

    N.B. using {,3} would be equivalent to {0,3}, I simply prefer the latter notation.

    See here for more information on regex quantifiers: https://www.regular-expressions.info/refrepeat.html

    SQL Query to concatenate column values from multiple rows in Oracle

    In the select where you want your concatenation, call a SQL function.

    For example:

    select PID, dbo.MyConcat(PID)
       from TableA;
    

    Then for the SQL function:

    Function MyConcat(@PID varchar(10))
    returns varchar(1000)
    as
    begin
    
    declare @x varchar(1000);
    
    select @x = isnull(@x +',', @x, @x +',') + Desc
      from TableB
        where PID = @PID;
    
    return @x;
    
    end
    

    The Function Header syntax might be wrong, but the principle does work.

    favicon not working in IE

    Check the response headers for your favicon. They must not include "Cache-Control: no-cache".

    You can check this from the command line using:

    curl -I http://example.com/favicon.ico
    

    or

    wget --server-response --spider http://example.com/favicon.ico
    

    (or use some other tool that will show you response headers)

    If you see "Cache-Control: no-cache" in there, adjust your server configuration to either remove that header from the favicon response or set a max-age.

    file_put_contents: Failed to open stream, no such file or directory

    There is definitly a problem with the destination folder path.

    Your above error message says, it wants to put the contents to a file in the directory /files/grantapps/, which would be beyond your vhost, but somewhere in the system (see the leading absolute slash )

    You should double check:

    • Is the directory /home/username/public_html/files/grantapps/ really present.
    • Contains your loop and your file_put_contents-Statement the absolute path /home/username/public_html/files/grantapps/

    How to change menu item text dynamically in Android

    I needed to change the menu icon for the fragment. I altered Charles’s answer to this question a bit for the fragment:

        private Menu top_menu;
    
        //...
        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
           setHasOptionsMenu(true);
           //...
           rootview = inflater.inflate(R.layout.first_content,null);
        }
    
        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            inflater.inflate(R.menu.fragment_menu, menu);
            this.top_menu = menu;
        }
    
    
        // my procedure
        private void updateIconMenu() {
             if(top_menu!= null) {
                 MenuItem nav_undo = top_menu.findItem(R.id.action_undo);
                 nav_undo.setIcon( R.drawable.back);
             }
        }
    

    Mercurial stuck "waiting for lock"

    I had the same problem. Got the following message when I tried to commit:

    waiting for lock on working directory of <MyProject> held by '...'
    

    hg debuglock showed this:

    lock:  free
    wlock:  (66722s)
    

    So I did the following command, and that fixed the problem for me:

    hg debuglocks -W
    

    Using Win7 and TortoiseHg 4.8.7.

    Best way to serialize/unserialize objects in JavaScript?

    I wrote serialijse because I faced the same problem as you.

    you can find it at https://github.com/erossignon/serialijse

    It can be used in nodejs or in a browser and can serve to serialize and deserialize a complex set of objects from one context (nodejs) to the other (browser) or vice-versa.

    var s = require("serialijse");
    
    
    var assert = require("assert");
    
    
    // testing serialization of a simple javascript object with date
    function testing_javascript_serialization_object_with_date() {
    
        var o = {
            date: new Date(),
            name: "foo"
        };
        console.log(o.name, o.date.toISOString());
    
        // JSON will fail as JSON doesn't preserve dates
        try {
            var jstr = JSON.stringify(o);
            var jo = JSON.parse(jstr);
            console.log(jo.name, jo.date.toISOString());
        } catch (err) {
            console.log(" JSON has failed to preserve Date during stringify/parse ");
            console.log("  and has generated the following error message", err.message);
        }
        console.log("");
    
    
    
        var str = s.serialize(o);
        var so = s.deserialize(str);
        console.log(" However Serialijse knows how to preserve date during serialization/deserialization :");
        console.log(so.name, so.date.toISOString());
        console.log("");
    }
    testing_javascript_serialization_object_with_date();
    
    
    // serializing a instance of a class
    function testing_javascript_serialization_instance_of_a_class() {
    
        function Person() {
            this.firstName = "Joe";
            this.lastName = "Doe";
            this.age = 42;
        }
    
        Person.prototype.fullName = function () {
            return this.firstName + " " + this.lastName;
        };
    
    
        // testing serialization using  JSON.stringify/JSON.parse
        var o = new Person();
        console.log(o.fullName(), " age=", o.age);
    
        try {
            var jstr = JSON.stringify(o);
            var jo = JSON.parse(jstr);
            console.log(jo.fullName(), " age=", jo.age);
    
        } catch (err) {
            console.log(" JSON has failed to preserve the object class ");
            console.log("  and has generated the following error message", err.message);
        }
        console.log("");
    
        // now testing serialization using serialijse  serialize/deserialize
        s.declarePersistable(Person);
        var str = s.serialize(o);
        var so = s.deserialize(str);
    
        console.log(" However Serialijse knows how to preserve object classes serialization/deserialization :");
        console.log(so.fullName(), " age=", so.age);
    }
    testing_javascript_serialization_instance_of_a_class();
    
    
    // serializing an object with cyclic dependencies
    function testing_javascript_serialization_objects_with_cyclic_dependencies() {
    
        var Mary = { name: "Mary", friends: [] };
        var Bob = { name: "Bob", friends: [] };
    
        Mary.friends.push(Bob);
        Bob.friends.push(Mary);
    
        var group = [ Mary, Bob];
        console.log(group);
    
        // testing serialization using  JSON.stringify/JSON.parse
        try {
            var jstr = JSON.stringify(group);
            var jo = JSON.parse(jstr);
            console.log(jo);
    
        } catch (err) {
            console.log(" JSON has failed to manage object with cyclic deps");
            console.log("  and has generated the following error message", err.message);
        }
    
        // now testing serialization using serialijse  serialize/deserialize
        var str = s.serialize(group);
        var so = s.deserialize(str);
        console.log(" However Serialijse knows to manage object with cyclic deps !");
        console.log(so);
        assert(so[0].friends[0] == so[1]); // Mary's friend is Bob
    }
    testing_javascript_serialization_objects_with_cyclic_dependencies();
    

    Map and Reduce in .NET

    The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.

    From the following article: http://codecube.net/2009/02/mapreduce-in-c-using-linq/

    the GroupBy method is acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.

    var wordOccurrences = words
                    .GroupBy(w => w)
                    .Select(intermediate => new
                    {
                        Word = intermediate.Key,
                        Frequency = intermediate.Sum(w => 1)
                    })
                    .Where(w => w.Frequency > 10)
                    .OrderBy(w => w.Frequency);
    

    For the distributed portion, you could check out DryadLINQ: http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx

    Flexbox not working in Internet Explorer 11

    According to Flexbugs:

    In IE 10-11, min-height declarations on flex containers work to size the containers themselves, but their flex item children do not seem to know the size of their parents. They act as if no height has been set at all.

    Here are a couple of workarounds:

    1. Always fill the viewport + scrollable <aside> and <section>:

    _x000D_
    _x000D_
    html {
      height: 100%;
    }
    
    body {
      display: flex;
      flex-direction: column;
      height: 100%;
      margin: 0;
    }
    
    header,
    footer {
      background: #7092bf;
    }
    
    main {
      flex: 1;
      display: flex;
    }
    
    aside, section {
      overflow: auto;
    }
    
    aside {
      flex: 0 0 150px;
      background: #3e48cc;
    }
    
    section {
      flex: 1;
      background: #9ad9ea;
    }
    _x000D_
    <header>
      <p>header</p>
    </header>
    
    <main>
      <aside>
        <p>aside</p>
      </aside>
      <section>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
      </section>
    </main>
    
    <footer>
      <p>footer</p>
    </footer>
    _x000D_
    _x000D_
    _x000D_

    2. Fill the viewport initially + normal page scroll with more content:

    _x000D_
    _x000D_
    html {
      height: 100%;
    }
    
    body {
      display: flex;
      flex-direction: column;
      height: 100%;
      margin: 0;
    }
    
    header,
    footer {
      background: #7092bf;
    }
    
    main {
      flex: 1 0 auto;
      display: flex;
    }
    
    aside {
      flex: 0 0 150px;
      background: #3e48cc;
    }
    
    section {
      flex: 1;
      background: #9ad9ea;
    }
    _x000D_
    <header>
      <p>header</p>
    </header>
    
    <main>
      <aside>
        <p>aside</p>
      </aside>
      <section>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
        <p>content</p>
      </section>
    </main>
    
    <footer>
      <p>footer</p>
    </footer>
    _x000D_
    _x000D_
    _x000D_

    What is the difference between DTR/DSR and RTS/CTS flow control?

    The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

    Java, How to add library files in netbeans?

    For Netbeans 2020 September version. JDK 11

    (Suggesting this for Gradle project only)

    1. create libs folder in src/main/java folder of the project

    2. copy past all library jars in there

    3. open build.gradle in files tab of project window in project's root

    4. correct main class (mine is mainClassName = 'uz.ManipulatorIkrom')

    5. and in dependencies add next string:

    apply plugin: 'java' 
    apply plugin: 'jacoco' 
    apply plugin: 'application'
    description = 'testing netbeans'
    mainClassName = 'uz.ManipulatorIkrom' //4th step
    repositories {
        jcenter()
    }
    dependencies {
        implementation fileTree(dir: 'src/main/java/libs', include: '*.jar') //5th step   
    }
    

    6. save, clean-build and then run the app

    View contents of database file in Android Studio

    Open the Device File Explore Terminal at the Bottom of the Android Studio.

    Open The folder named Data , then inside Data again open the Folder Data .

    Open the folder data

    Scroll Down the list of folders and find the folder with your.package.name. Open folder your.package.name > Database. You get your.databaseName. Right Click your.databaseName and Save as to C:/your/Computer/Directory.

    Go to C:/your/Computer/Directory open your.databaseName with DB SQLite

    enter image description here

    update package.json version automatically

    With Husky:

    {
      "name": "demo-project",
      "version": "0.0.3",
      "husky": {
        "hooks": {
          "pre-commit": "npm --no-git-tag-version version patch && git add ."
        }
      }
    }
    

    How to detect scroll direction

    This one deserves an update - nowadays we have the wheel event :

    _x000D_
    _x000D_
    $(function() {_x000D_
    _x000D_
    $(window).on('wheel', function(e) {_x000D_
    _x000D_
     var delta = e.originalEvent.deltaY;_x000D_
    _x000D_
     if (delta > 0) $('body').text('down');_x000D_
     else $('body').text('up');_x000D_
    _x000D_
     return false; // this line is only added so the whole page won't scroll in the demo_x000D_
    });_x000D_
    });
    _x000D_
    body {_x000D_
      font-size: 22px;_x000D_
      text-align: center;_x000D_
      color: white;_x000D_
      background: grey;_x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    Support has been pretty good on modern browsers for quite a while already :

    • Chrome 31+
    • Firefox 17+
    • IE9+
    • Opera 18+
    • Safari 7+

    https://developer.mozilla.org/en-US/docs/Web/Events/wheel

    If deeper browser support is required, probably best to use mousewheel.js instead of messing about :

    https://plugins.jquery.com/mousewheel/

    _x000D_
    _x000D_
    $(function() {_x000D_
    _x000D_
    $(window).mousewheel(function(turn, delta) {_x000D_
    _x000D_
     if (delta > 0) $('body').text('up');_x000D_
     else $('body').text('down');_x000D_
    _x000D_
     return false; // this line is only added so the whole page won't scroll in the demo_x000D_
    });_x000D_
    });
    _x000D_
    body {_x000D_
      font-size: 22px;_x000D_
      text-align: center;_x000D_
      color: white;_x000D_
      background: grey;_x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    Comparing Arrays of Objects in JavaScript

    Please try this one:

    function used_to_compare_two_arrays(a, b)
    {
      // This block will make the array of indexed that array b contains a elements
      var c = a.filter(function(value, index, obj) {
        return b.indexOf(value) > -1;
      });
    
      // This is used for making comparison that both have same length if no condition go wrong 
      if (c.length !== a.length) {
        return 0;
      } else{
        return 1;
      }
    }
    

    Set the value of a variable with the result of a command in a Windows batch file

    Set "dateTime="
    For /F %%A In ('powershell get-date -format "{yyyyMMdd_HHmm}"') Do Set "dateTime=%%A"
    echo %dateTime%
    pause
    

    enter image description here Official Microsoft docs for for command

    Algorithm to calculate the number of divisors of a given number

    I disagree that the sieve of Atkin is the way to go, because it could easily take longer to check every number in [1,n] for primality than it would to reduce the number by divisions.

    Here's some code that, although slightly hackier, is generally much faster:

    import operator
    # A slightly efficient superset of primes.
    def PrimesPlus():
      yield 2
      yield 3
      i = 5
      while True:
        yield i
        if i % 6 == 1:
          i += 2
        i += 2
    # Returns a dict d with n = product p ^ d[p]
    def GetPrimeDecomp(n):
      d = {}
      primes = PrimesPlus()
      for p in primes:
        while n % p == 0:
          n /= p
          d[p] = d.setdefault(p, 0) + 1
        if n == 1:
          return d
    def NumberOfDivisors(n):
      d = GetPrimeDecomp(n)
      powers_plus = map(lambda x: x+1, d.values())
      return reduce(operator.mul, powers_plus, 1)
    

    ps That's working python code to solve this problem.

    List directory in Go

    Starting with Go 1.16, you can use the os.ReadDir function.

    func ReadDir(name string) ([]DirEntry, error)

    It reads a given directory and returns a DirEntry slice that contains the directory entries sorted by filename.

    It's an optimistic function, so that, when an error occurs while reading the directory entries, it tries to return you a slice with the filenames up to the point before the error.

    package main
    
    import (
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        files, err := os.ReadDir(".")
        if err != nil {
            log.Fatal(err)
        }
    
        for _, file := range files {
            fmt.Println(file.Name())
        }
    }
    

    Background

    Go 1.16 (Q1 2021) will propose, with CL 243908 and CL 243914 , the ReadDir function, based on the FS interface:

    // An FS provides access to a hierarchical file system.
    //
    // The FS interface is the minimum implementation required of the file system.
    // A file system may implement additional interfaces,
    // such as fsutil.ReadFileFS, to provide additional or optimized functionality.
    // See io/fsutil for details.
    type FS interface {
        // Open opens the named file.
        //
        // When Open returns an error, it should be of type *PathError
        // with the Op field set to "open", the Path field set to name,
        // and the Err field describing the problem.
        //
        // Open should reject attempts to open names that do not satisfy
        // ValidPath(name), returning a *PathError with Err set to
        // ErrInvalid or ErrNotExist.
        Open(name string) (File, error)
    }
    

    That allows for "os: add ReadDir method for lightweight directory reading":
    See commit a4ede9f:

    // ReadDir reads the contents of the directory associated with the file f
    // and returns a slice of DirEntry values in directory order.
    // Subsequent calls on the same file will yield later DirEntry records in the directory.
    //
    // If n > 0, ReadDir returns at most n DirEntry records.
    // In this case, if ReadDir returns an empty slice, it will return an error explaining why.
    // At the end of a directory, the error is io.EOF.
    //
    // If n <= 0, ReadDir returns all the DirEntry records remaining in the directory.
    // When it succeeds, it returns a nil error (not io.EOF).
    func (f *File) ReadDir(n int) ([]DirEntry, error) 
    
    // A DirEntry is an entry read from a directory (using the ReadDir method).
    type DirEntry interface {
        // Name returns the name of the file (or subdirectory) described by the entry.
        // This name is only the final element of the path, not the entire path.
        // For example, Name would return "hello.go" not "/home/gopher/hello.go".
        Name() string
        
        // IsDir reports whether the entry describes a subdirectory.
        IsDir() bool
        
        // Type returns the type bits for the entry.
        // The type bits are a subset of the usual FileMode bits, those returned by the FileMode.Type method.
        Type() os.FileMode
        
        // Info returns the FileInfo for the file or subdirectory described by the entry.
        // The returned FileInfo may be from the time of the original directory read
        // or from the time of the call to Info. If the file has been removed or renamed
        // since the directory read, Info may return an error satisfying errors.Is(err, ErrNotExist).
        // If the entry denotes a symbolic link, Info reports the information about the link itself,
        // not the link's target.
        Info() (FileInfo, error)
    }
    

    src/os/os_test.go#testReadDir() illustrates its usage:

        file, err := Open(dir)
        if err != nil {
            t.Fatalf("open %q failed: %v", dir, err)
        }
        defer file.Close()
        s, err2 := file.ReadDir(-1)
        if err2 != nil {
            t.Fatalf("ReadDir %q failed: %v", dir, err2)
        }
    

    Ben Hoyt points out in the comments to Go 1.16 os.ReadDir:

    os.ReadDir(path string) ([]os.DirEntry, error), which you'll be able to call directly without the Open dance.
    So you can probably shorten this to just os.ReadDir, as that's the concrete function most people will call.

    See commit 3d913a9 (Dec. 2020):

    os: add ReadFile, WriteFile, CreateTemp (was TempFile), MkdirTemp (was TempDir) from io/ioutil

    io/ioutil was a poorly defined collection of helpers.

    Proposal #40025 moved out the generic I/O helpers to io. This CL for proposal #42026 moves the OS-specific helpers to os, making the entire io/ioutil package deprecated.

    os.ReadDir returns []DirEntry, in contrast to ioutil.ReadDir's []FileInfo.
    (Providing a helper that returns []DirEntry is one of the primary motivations for this change.)

    Error 0x80005000 and DirectoryServices

    It's a permission problem.

    When you run the console app, that app runs with your credentials, e.g. as "you".

    The WCF service runs where? In IIS? Most likely, it runs under a separate account, which is not permissioned to query Active Directory.

    You can either try to get the WCF impersonation thingie working, so that your own credentials get passed on, or you can specify a username/password on creating your DirectoryEntry:

    DirectoryEntry directoryEntry = 
        new DirectoryEntry("LDAP://someserver.contoso.com/DC=contoso,DC=com", 
                           userName, password);
    

    OK, so it might not be the credentials after all (that's usually the case in over 80% of the cases I see).

    What about changing your code a little bit?

    DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry);
    directorySearcher.Filter = string.Format("(&(objectClass=user)(objectCategory=user) (sAMAccountName={0}))", username);
    
    directorySearcher.PropertiesToLoad.Add("msRTCSIP-PrimaryUserAddress");
    
    var result = directorySearcher.FindOne();
    
    if(result != null)
    {
       if(result.Properties["msRTCSIP-PrimaryUserAddress"] != null)
       {
          var resultValue = result.Properties["msRTCSIP-PrimaryUserAddress"][0];
       }
    }
    

    My idea is: why not tell the DirectorySearcher right off the bat what attribute you're interested in? Then you don't need to do another extra step to get the full DirectoryEntry from the search result (should be faster), and since you told the directory searcher to find that property, it's certainly going to be loaded in the search result - so unless it's null (no value set), then you should be able to retrieve it easily.

    Marc

    max value of integer

    In C range for __int32 is –2147483648 to 2147483647. See here for full ranges.

    unsigned short 0 to 65535
    signed short –32768 to 32767
    unsigned long 0 to 4294967295
    signed long –2147483648 to 2147483647
    

    There are no guarantees that an 'int' will be 32 bits, if you want to use variables of a specific size, particularly when writing code that involves bit manipulations, you should use the 'Standard Integer Types'.

    In Java

    The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

    Changing variable names with Python for loops

    You could access your class's __dict__ attribute:

    for i in range(3)
         self.__dict__['group%d' % i]=self.getGroup(selected, header+i)
    

    But why can't you just use an array named group?

    How do I calculate someone's age in Java?

    Calendar now = Calendar.getInstance();
    Calendar dob = Calendar.getInstance();
    dob.setTime(...);
    if (dob.after(now)) {
      throw new IllegalArgumentException("Can't be born in the future");
    }
    int year1 = now.get(Calendar.YEAR);
    int year2 = dob.get(Calendar.YEAR);
    int age = year1 - year2;
    int month1 = now.get(Calendar.MONTH);
    int month2 = dob.get(Calendar.MONTH);
    if (month2 > month1) {
      age--;
    } else if (month1 == month2) {
      int day1 = now.get(Calendar.DAY_OF_MONTH);
      int day2 = dob.get(Calendar.DAY_OF_MONTH);
      if (day2 > day1) {
        age--;
      }
    }
    // age is now correct
    

    How to set cursor position in EditText?

    How to resolve the cursor position issue which is automatically moving to the last position after formatting in US Mobile like (xxx) xxx-xxxx in Android.

    private String oldText = "";
    private int lastCursor;
    private EditText mEtPhone;
    
    @Override
        public void afterTextChanged(Editable s) {
    String cleanString = AppUtil.cleanPhone(s.toString());
    
    String format = cleanString.length() < 11 ? cleanString.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3") :
                    cleanString.substring(0, 10).replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1) $2-$3");
    
    
    boolean isDeleted = format.length() < oldText.length();
    
            try {
    
                int cur = AppUtil.getPointer(lastCursor, isDeleted ? s.toString() : format, oldText, isDeleted);
                mEtPhone.setSelection(cur > 0 ? cur : format.length());
    
            }catch (Exception e){
                e.printStackTrace();
                mEtPhone.setSelection(format.length());
            }
    
            mEtPhone.addTextChangedListener(this);
    
        }
    
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
            oldText = s.toString();
            lastCursor = start;
        }
    

    Define the below method to any Activityclass in my case Activity name is AppUtil and access it globally

    public static int getPointer(int index, String newString, String oldText, boolean isDeleted){
    
            int diff = Math.abs(newString.length() - oldText.length());
    
            return diff > 1 ? isDeleted ? index - diff : index  + diff : isDeleted ? index : index + 1;
        }
    
    public static String cleanPhone(String phone){
    
            if(TextUtils.isEmpty(phone))
                return "";
    
            StringBuilder sb = new StringBuilder();
            for(char c : phone.toCharArray()){
                if(Character.isDigit(c))
                    sb.append(c);
            }
            return sb.toString();
        }
    

    And if you want to set any specific position

    edittext.setSelection(position);
    

    XmlWriter to Write to a String Instead of to a File

    As Richard said, StringWriter is the way forward. There's one snag, however: by default, StringWriter will advertise itself as being in UTF-16. Usually XML is in UTF-8. You can fix this by subclassing StringWriter;

    public class Utf8StringWriter : StringWriter
    {
        public override Encoding Encoding
        {
             get { return Encoding.UTF8; }
        }
    }
    

    This will affect the declaration written by XmlWriter. Of course, if you then write the string out elsewhere in binary form, make sure you use an encoding which matches whichever encoding you fix for the StringWriter. (The above code always assumes UTF-8; it's trivial to make a more general version which accepts an encoding in the constructor.)

    You'd then use:

    using (TextWriter writer = new Utf8StringWriter())
    {
        using (XmlWriter xmlWriter = XmlWriter.Create(writer))
        {
            ...
        }
        return writer.ToString();
    }
    

    Print all properties of a Python Class

    Here is full code. The result is exactly what you want.

    class Animal(object):
        def __init__(self):
            self.legs = 2
            self.name = 'Dog'
            self.color= 'Spotted'
            self.smell= 'Alot'
            self.age  = 10
            self.kids = 0
    
    if __name__ == '__main__':
        animal = Animal()
        temp = vars(animal)
        for item in temp:
            print item , ' : ' , temp[item]
            #print item , ' : ', temp[item] ,
    

    Height of status bar in Android

    Yes when i try it with View it provides the result of 25px. Here is the whole code :

    public class SpinActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            LinearLayout lySpin = new LinearLayout(this);
            lySpin.setOrientation(LinearLayout.VERTICAL);       
            lySpin.post(new Runnable()
            {
                public void run()
                {
                    Rect rect = new Rect();
                    Window window = getWindow();
                    window.getDecorView().getWindowVisibleDisplayFrame(rect);
                    int statusBarHeight = rect.top;
                    int contentViewTop = 
                        window.findViewById(Window.ID_ANDROID_CONTENT).getTop();
                    int titleBarHeight = contentViewTop - statusBarHeight;
                    System.out.println("TitleBarHeight: " + titleBarHeight 
                        + ", StatusBarHeight: " + statusBarHeight);
                }
            }
        }
    }
    

    How can I submit a form using JavaScript?

    I will leave the way I do to submit the form without using the name tag inside the form:

    HTML

    <button type="submit" onClick="placeOrder(this.form)">Place Order</button>
    

    JavaScript

    function placeOrder(form){
        form.submit();
    }
    

    How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

    As the answers are a bit old, I will put my solution (what worked for me), it can be helpful for somebody else... I took my solution from the official documentation of Apache, no work-around.

    1/ in gradle:

    dependencies {
    ...
    // This is the maintained version from apache.
    compile group: 'cz.msebera.android', name: 'httpclient', version: '4.4.1.1'
    }
    

    2/ in the rest of the app replace the org.apache.http by cz.msebera.android.httpclient and all your imports (dependencies) will be fixed. you can just do ctrl+shift+R and replace it in the whole project.

    Git error: src refspec master does not match any

    You've created a new repository and added some files to the index, but you haven't created your first commit yet. After you've done:

     git add a_text_file.txt 
    

    ... do:

     git commit -m "Initial commit."
    

    ... and those errors should go away.

    IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

    It sounds like your table has no key. You should be able to simply try the INSERT: if it’s a duplicate then the key constraint will bite and the INSERT will fail. No worries: you just need to ensure the application doesn't see/ignores the error. When you say 'primary key' you presumably mean IDENTITY value. That's all very well but you also need a key constraint (e.g. UNIQUE) on your natural key.

    Also, I wonder whether your procedure is doing too much. Consider having separate procedures for 'create' and 'read' actions respectively.

    How can you integrate a custom file browser/uploader with CKEditor?

    I have posted one small tutorial about integrating the FileBrowser available in old FCKEditor into CKEditor.

    http://www.mixedwaves.com/2010/02/integrating-fckeditor-filemanager-in-ckeditor/

    It contains step by step instructions for doing so and its pretty simple. I hope anybody in search of this will find this tutorial helpful.

    Placing an image to the top right corner - CSS

    Position the div relatively, and position the ribbon absolutely inside it. Something like:

    #content {
      position:relative;
    }
    
    .ribbon {
      position:absolute;
      top:0;
      right:0;
    }
    

    MATLAB - multiple return values from a function?

    I think Octave only return one value which is the first return value, in your case, 'array'.

    And Octave print it as "ans".

    Others, 'listp','freep' were not printed.

    Because it showed up within the function.

    Try this out:

    [ A, B, C] = initialize( 4 )
    

    And the 'array','listp','freep' will print as A, B and C.

    How to get longitude and latitude of any address?

    I came up with the following which takes account of rubbish passed in and file_get_contents failing....

    function get_lonlat(  $addr  ) {
        try {
                $coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
                $e=json_decode($coordinates);
                // call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
                if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
                // $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
                if ( $coordinates == false   ||  $err_res ==  true  ) {
                    $a = array( 'lat'=>0,'lng'=>0);
                    $coordinates  = new stdClass();
                    foreach (  $a  as $key => $value)
                    {
                        $coordinates->$key = $value;
                    }
                } else {
                    // call to google ok so just return longitude/latitude.
                    $coordinates = $e;
    
                    $coordinates  =  $coordinates->results[0]->geometry->location;
                }
    
                return $coordinates;
        }
        catch (Exception $e) {
        }
    

    then to get the cords: where $pc is the postcode or address.... $address = get_lonlat( $pc ); $l1 = $address->lat; $l2 = $address->lng;

    How do I create 7-Zip archives with .NET?

    I used the sdk.

    eg:

    using SevenZip.Compression.LZMA;
    private static void CompressFileLZMA(string inFile, string outFile)
    {
       SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();
    
       using (FileStream input = new FileStream(inFile, FileMode.Open))
       {
          using (FileStream output = new FileStream(outFile, FileMode.Create))
          {
              coder.Code(input, output, -1, -1, null);
              output.Flush();
          }
       }
    }
    

    "configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

    sudo nginx -t should test all files and return errors and warnings locations

    Getting the first and last day of a month, using a given DateTime object

    If you only care about the date

    var firstDay = new DateTime(date.Year, date.Month, 1, 0, 0, 0, date.Kind);
    var lastDay = new DateTime(date.Year, date.Month, 1, 0, 0, 0, date.Kind).AddMonths(1).AddDays(-1);
    

    If you want to preserve time

    var firstDay = new DateTime(date.Year, date.Month, 1, date.Hour, date.Minute, date.Second, date.Kind);
    var lastDay = new DateTime(date.Year, date.Month, 1, date.Hour, date.Minute, date.Second, date.Kind).AddMonths(1).AddDays(-1);
    

    The number of method references in a .dex file cannot exceed 64k API 17

    **

    For Unity Game Developers

    **

    If anyone comes here because this error showed up in their Unity project, Go to File->Build Settings -> Player Settings -> Player. go to Publishing Settings and under the Build tab, enable "Custom Launcher Gradle Template". a path will be shown under that text. go to the path and add multiDexEnabled true like this:

    defaultConfig {
        minSdkVersion **MINSDKVERSION**
        targetSdkVersion **TARGETSDKVERSION**
        applicationId '**APPLICATIONID**'
        ndk {
            abiFilters **ABIFILTERS**
        }
        versionCode **VERSIONCODE**
        versionName '**VERSIONNAME**'
        multiDexEnabled true
    }
    

    insert datetime value in sql database with c#

    INSERT INTO <table> (<date_column>) VALUES ('1/1/2010 12:00')
    

    How to get a resource id with a known resource name?

    It will be something like:

    R.drawable.resourcename

    Make sure you don't have the Android.R namespace imported as it can confuse Eclipse (if that's what you're using).

    If that doesn't work, you can always use a context's getResources method ...

    Drawable resImg = this.context.getResources().getDrawable(R.drawable.resource);
    

    Where this.context is intialised as an Activity, Service or any other Context subclass.

    Update:

    If it's the name you want, the Resources class (returned by getResources()) has a getResourceName(int) method, and a getResourceTypeName(int)?

    Update 2:

    The Resources class has this method:

    public int getIdentifier (String name, String defType, String defPackage) 
    

    Which returns the integer of the specified resource name, type & package.

    How can you find out which process is listening on a TCP or UDP port on Windows?

    Netstat:

    • -a displays all connection and listening ports
    • -b displays executables
    • -n stop resolve hostnames (numerical form)
    • -o owning process

      netstat -bano | findstr "7002"
      
      netstat -ano > ano.txt 
      

    The Currports tool helps to search and filter

    Check if a string within a list contains a specific string with Linq

    Thast should be easy enough

    if( myList.Any( s => s.Contains(stringToCheck))){
      //do your stuff here
    }
    

    Rotate and translate

    There is no need for that, as you can use css 'writing-mode' with values 'vertical-lr' or 'vertical-rl' as desired.

    .item {
      writing-mode: vertical-rl;
    }
    

    CSS:writing-mode

    Drop shadow on a div container?

    you might want to try this. Seems to be pretty easy and works on IE6 and Moz atleast.

    <div id ="show" style="background-color:Silver;width:100px;height:100px;visibility:visible;border-bottom:outset 1px black;border-right:outset 1px black;" ></div>
    

    The general syntax is : border-[postion]:[border-style] [border-width] [border-color] | inherit

    The list of available [border-style]s are :

    • dashed
    • dotted
    • double
    • groove
    • hidden
    • inset
    • none
    • outset
    • ridge
    • solid
    • inherit

    ggplot combining two plots from different data.frames

    The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

    Like this:

    ggplot() + 
    geom_line(data=Data1, aes(x=A, y=B), color='green') + 
    geom_line(data=Data2, aes(x=C, y=D), color='red')
    

    instead of

    ggplot(data=Data1, aes(x=A, y=B), color='green') + 
    geom_line() + 
    geom_line(data=Data2, aes(x=C, y=D), color='red')
    

    More info here

    Saving and Reading Bitmaps/Images from Internal memory in Android

    // mutiple image retrieve

     File folPath = new File(getIntent().getStringExtra("folder_path"));
     File[] imagep = folPath.listFiles();
    
     for (int i = 0; i < imagep.length ; i++) {
         imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
     }
     imagesAdapter.notifyDataSetChanged();
    

    How to align text below an image in CSS?

    Best way is to wrap the Image and Paragraph text with a DIV and assign a class.

    Example:

    <div class="image1">
        <div class="imgWrapper">
            <img src="images/img1.png" width="250" height="444" alt="Screen 1"/>
            <p>It's my first Image</p>
        </div>
        ...
        ...
        ...
        ...
    </div>
    

    server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

    Another cause of this problem might be that your clock might be off. Certificates are time sensitive.

    To check the current system time:

    date -R
    

    You might consider installing NTP to automatically sync the system time with trusted internet timeservers from the global NTP pool. For example, to install on Debian/Ubuntu:

    apt-get install ntp
    

    Using Mockito's generic "any()" method

    This should work

    import static org.mockito.ArgumentMatchers.any;
    import static org.mockito.Mockito.verify;
    
    verify(bar).DoStuff(any(Foo[].class));
    

    How do I remove javascript validation from my eclipse project?

    I actually like MY JavaScript files to be validated, but I definitely don't want to validate and deal with trivial warnings with third party libraries.

    That's why I think that turning off validation all together is too drastic. Fortunately with Eclipse, you can selectively remove some JavaScript sources from validation.

    1. Right-click your project.
    2. Navigate to: Properties ? JavaScript ? Include Path
    3. Select Source tab. (It looks identical to Java Build Path Source tab.)
    4. Expand JavaScript source folder.
    5. Highlight Excluded pattern.
    6. Press the Edit button.
    7. Press the Add button next to Exclusion patterns box.
    8. You may either type Ant-style wildcard pattern, or click Browse button to mention the JavaScript source by name.

    The information about JavaScript source inclusion/exclusion is saved into .settings/.jsdtscope file. Do not forget to add it to your SCM.

    Here is how configuration looks with jQuery files removed from validation:

    Eclipse - Project Properties - JavaScript - Include Path

    How to sort multidimensional array by column?

    You can use the sorted method with a key.

    sorted(a, key=lambda x : x[1])
    

    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);
    

    LEFT JOIN only first row

    Here is my answer using the group by clause.

    SELECT *
    FROM feeds f
    LEFT JOIN 
    (
        SELECT artist_id, feed_id
        FROM feeds_artists
        GROUP BY artist_id, feed_id 
    ) fa ON fa.feed_id = f.id
    LEFT JOIN artists a ON a.artist_id = fa.artist_id
    

    JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

    You did not include jquery library. In jsfiddle its already there. Just include this line in your head section.

     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    

    How to dismiss a Twitter Bootstrap popover by clicking outside?

    You can also use event bubbling to remove the popup from the DOM. It is a bit dirty, but works fine.

    $('body').on('click touchstart', '.popover-close', function(e) {
      return $(this).parents('.popover').remove();
    });
    

    In your html add the .popover-close class to the content inside the popover that should close the popover.

    Compiling with g++ using multiple cores

    People have mentioned make but bjam also supports a similar concept. Using bjam -jx instructs bjam to build up to x concurrent commands.

    We use the same build scripts on Windows and Linux and using this option halves our build times on both platforms. Nice.

    How many characters can you store with 1 byte?

    The syntax of TINYINT data type is TINYINT(M),

    where M indicates the maximum display width (used only if your MySQL client supports it).

    The (m) indicates the column width in SELECT statements; however, it doesn't control the accepted range of numbers for that field.

    A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 >bits, BIT(64). For a boolean values, BIT(1) is pretty common.

    TINYINT()

    Refresh image with a new one at the same url

    I've seen a lot of variation in answers for how to do this, so I thought I'd summarize them here (plus add a 4th method of my own invention):


    (1) Add a unique cache-busting query parameter to the URL, such as:

    newImage.src = "image.jpg?t=" + new Date().getTime();
    

    Pros: 100% reliable, quick & easy to understand and implement.

    Cons: Bypasses caching altogether, meaning unnecessary delays and bandwidth use whenever the image doesn't change between views. Will potentially fill browser cache (and any intermediate caches) with many, many copies of exactly the same image! Also, requires modifying image URL.

    When to use: Use when image is constantly changing, such as for a live webcam feed. If you use this method, make sure to serve the images themselves with Cache-control: no-cache HTTP headers!!! (Often this can be set up using a .htaccess file). Otherwise you'll be progressively filling caches up with old versions of the image!


    (2) Add query parameter to the URL that changes only when the file does, e.g.:

    echo '<img src="image.jpg?m=' . filemtime('image.jpg') . '">';
    

    (That's PHP server-side code, but the important point here is just that a ?m=[file last-modified time] querystring is appended to the filename).

    Pros: 100% reliable, quick & easy to understand and implement, and preserves caching advantages perfectly.

    Cons: Requires modifying the image URL. Also, a little more work for the server - it has to get access to the file-last-modified time. Also, requires server-side information, so not suitable for a purely client-side-only solution to check for a refreshed image.

    When to use: When you want to cache images, but may need to update them at the server end from time to time without changing the filename itself. AND when you can easily ensure that the correct querystring is added to every image instance in your HTML.


    (3) Serve your images with the header Cache-control: max-age=0, must-revalidate, and add a unique memcache-busting fragment identifier to the URL, such as:

    newImage.src = "image.jpg#" + new Date().getTime();
    

    The idea here is that the cache-control header puts images in the browser cache, but immediately markes them stale, so that and every time they are re-displayed the browser must check with the server to see if they've changed. This ensures that the browser's HTTP cache always returns the latest copy of the image. However, browsers will often re-use an in-memory copy of an image if they have one, and not even check their HTTP cache in that case. To prevent this, a fragment identifier is used: Comparison of in-memory image src's includes the fragment identifier, but it gets stripped of before querying the HTTP cache. (So, e.g., image.jpg#A and image.jpg#B might both be displayed from the image.jpg entry in the browser's HTTP cache, but image.jpg#B would never be displayed using in-memory retained image data from when image.jpg#A was last displayed).

    Pros: Makes proper use of HTTP caching mechanisms, and uses cached images if they haven't changed. Works for servers that choke on a querystring added to a static image URL (since servers never see fragment identifiers - they're for the browsers' own use only).

    Cons: Relies on somewhat dubious (or at least poorly documented) behaviour of browsers, in regard to images with fragment identifiers in their URLs (However, I've tested this successfully in FF27, Chrome33, and IE11). Does still send a revalidation request to the server for every image view, which may be overkill if images only change rarely and/or latency is a big issue (since you need to wait for the revalidation response even when the cached image is still good). Requires modifying image URLs.

    When to use: Use when images may change frequently, or need to be refreshed intermittently by the client without server-side script involvement, but where you still want the advantage of caching. For example, polling a live webcam that updates an image irregularly every few minutes. Alternatively, use instead of (1) or (2) if your server doesn't allow querystrings on static image URLs.


    (4) Forcibly refresh a particular image using Javascript, by first loading it into a hidden <iframe> and then calling location.reload(true) on the iframe's contentWindow.

    The steps are:

    • Load the image to be refreshed into a hidden iframe. This is just a setup step - it can be done long in advance the actual refresh, if desired. It doesn't even matter if the image fails to load at this stage!

    • Once that's done, blank out all copies of that image on your page(s) or anywhere in any DOM nodes (even off-page ones stored in javascript variables). This is necessary because the browser may otherwise display the image from a stale in-memory copy (IE11 especially does this): You need to ensure all in-memory copies are cleared, before refreshing the HTTP cache. If other javascript code is running asynchronously, you may also need to prevent that code from creating new copies of the to-be-refreshed image in the meantime.

    • Call iframe.contentWindow.location.reload(true). The true forces a cache bypass, reloading directly from the server and overwriting the existing cached copy.

    • Once it's finished re-loading, restore the blanked images. They should now display the fresh version from the server!

    For same-domain images, you can load the image into the iframe directly. For cross-domain images, you have to instead load a HTML page from your domain that contains the image in an <img> tag, otherwise you'll get an "Access Denied" error when trying to call iframe.contentWindow.reload(...).

    Pros: Works just like the image.reload() function you wish the DOM had! Allows images to by cached normally (even with in-the-future expiry dates if you want them, thus avoiding frequent revalidation). Allows you to refresh a particular image without altering the URLs for that image on the current page, or on any other pages, using only client-side code.

    Cons: Relies on Javascript. Not 100% guaranteed to work properly in every browser (I've tested this successfully in FF27, Chrome33, and IE11 though). Very complicated relative to the other methods.

    When to use: When you have a collection of basically static images that you'd like cached, but you still need to be able to update them occasionally and get immediate visual feedback that the update took place. (Especially when just refreshing the whole browser page wouldn't work, as in some web apps built on AJAX for example). And when methods (1)-(3) aren't feasible because (for whatever reason) you can't change all the URLs that might potentially display the image you need to have updated. (Note that using those 3 methods the image will be refreshed, but if another page then tries to displays that image without the appropriate querystring or fragment identifier, it may show an older version instead).

    The details of implementing this in a fairy robust and flexible manner are given below:

    Let's assume your website contains a blank 1x1 pixel .gif at the URL path /img/1x1blank.gif, and also has the following one-line PHP script (only required for applying forced refresh to cross-domain images, and can be rewritten in any server-side scripting language, of course) at the URL path /echoimg.php:

    <img src="<?=htmlspecialchars(@$_GET['src'],ENT_COMPAT|ENT_HTML5,'UTF-8')?>">
    

    Then, here's a realistic implementation of how you might do all this in Javascript. It looks a bit complicated, but there's a lot of comments, and the important function is just forceImgReload() - the first two just blank and un-blank images, and should be designed to work efficiently with your own HTML, so code them as works best for you; much of the complications in them may be unnecessary for your website:

    // This function should blank all images that have a matching src, by changing their src property to /img/1x1blank.gif.
    // ##### You should code the actual contents of this function according to your page design, and what images there are on them!!! #####
    // Optionally it may return an array (or other collection or data structure) of those images affected.
    // This can be used by imgReloadRestore() to restore them later, if that's an efficient way of doing it (otherwise, you don't need to return anything).
    // NOTE that the src argument here is just passed on from forceImgReload(), and MAY be a relative URI;
    // However, be aware that if you're reading the src property of an <img> DOM object, you'll always get back a fully-qualified URI,
    // even if the src attribute was a relative one in the original HTML.  So watch out if trying to compare the two!
    // NOTE that if your page design makes it more efficient to obtain (say) an image id or list of ids (of identical images) *first*, and only then get the image src,
    // you can pass this id or list data to forceImgReload() along with (or instead of) a src argument: just add an extra or replacement parameter for this information to
    // this function, to imgReloadRestore(), to forceImgReload(), and to the anonymous function returned by forceImgReload() (and make it overwrite the earlier parameter variable from forceImgReload() if truthy), as appropriate.
    function imgReloadBlank(src)
    {
      // ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
      // ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
      // ##### document.getElementById("myImage").src = "/img/1x1blank.gif";
    
      var blankList = [],
          fullSrc = /* Fully qualified (absolute) src - i.e. prepend protocol, server/domain, and path if not present in src */,
          imgs, img, i;
    
      for each (/* window accessible from this one, i.e. this window, and child frames/iframes, the parent window, anything opened via window.open(), and anything recursively reachable from there */)
      {
        // get list of matching images:
        imgs = theWindow.document.body.getElementsByTagName("img");
        for (i = imgs.length; i--;) if ((img = imgs[i]).src===fullSrc)  // could instead use body.querySelectorAll(), to check both tag name and src attribute, which would probably be more efficient, where supported
        {
          img.src = "/img/1x1blank.gif";  // blank them
          blankList.push(img);            // optionally, save list of blanked images to make restoring easy later on
        }
      }
    
      for each (/* img DOM node held only by javascript, for example in any image-caching script */) if (img.src===fullSrc)
      {
        img.src = "/img/1x1blank.gif";   // do the same as for on-page images!
        blankList.push(img);
      }
    
      // ##### If necessary, do something here that tells all accessible windows not to create any *new* images with src===fullSrc, until further notice,
      // ##### (or perhaps to create them initially blank instead and add them to blankList).
      // ##### For example, you might have (say) a global object window.top.blankedSrces as a propery of your topmost window, initially set = {}.  Then you could do:
      // #####
      // #####     var bs = window.top.blankedSrces;
      // #####     if (bs.hasOwnProperty(src)) bs[src]++; else bs[src] = 1;
      // #####
      // ##### And before creating a new image using javascript, you'd first ensure that (blankedSrces.hasOwnProperty(src)) was false...
      // ##### Note that incrementing a counter here rather than just setting a flag allows for the possibility that multiple forced-reloads of the same image are underway at once, or are overlapping.
    
      return blankList;   // optional - only if using blankList for restoring back the blanked images!  This just gets passed in to imgReloadRestore(), it isn't used otherwise.
    }
    
    
    
    
    // This function restores all blanked images, that were blanked out by imgReloadBlank(src) for the matching src argument.
    // ##### You should code the actual contents of this function according to your page design, and what images there are on them, as well as how/if images are dimensioned, etc!!! #####
    function imgReloadRestore(src,blankList,imgDim,loadError);
    {
      // ##### Everything here is provisional on the way the pages are designed, and what images they contain; what follows is for example purposes only!
      // ##### For really simple pages containing just a single image that's always the one being refreshed, this function could be as simple as just the one line:
      // ##### document.getElementById("myImage").src = src;
    
      // ##### if in imgReloadBlank() you did something to tell all accessible windows not to create any *new* images with src===fullSrc until further notice, retract that setting now!
      // ##### For example, if you used the global object window.top.blankedSrces as described there, then you could do:
      // #####
      // #####     var bs = window.top.blankedSrces;
      // #####     if (bs.hasOwnProperty(src)&&--bs[src]) return; else delete bs[src];  // return here means don't restore until ALL forced reloads complete.
    
      var i, img, width = imgDim&&imgDim[0], height = imgDim&&imgDim[1];
      if (width) width += "px";
      if (height) height += "px";
    
      if (loadError) {/* If you want, do something about an image that couldn't load, e.g: src = "/img/brokenImg.jpg"; or alert("Couldn't refresh image from server!"); */}
    
      // If you saved & returned blankList in imgReloadBlank(), you can just use this to restore:
    
      for (i = blankList.length; i--;)
      {
        (img = blankList[i]).src = src;
        if (width) img.style.width = width;
        if (height) img.style.height = height;
      }
    }
    
    
    
    
    // Force an image to be reloaded from the server, bypassing/refreshing the cache.
    // due to limitations of the browser API, this actually requires TWO load attempts - an initial load into a hidden iframe, and then a call to iframe.contentWindow.location.reload(true);
    // If image is from a different domain (i.e. cross-domain restrictions are in effect, you must set isCrossDomain = true, or the script will crash!
    // imgDim is a 2-element array containing the image x and y dimensions, or it may be omitted or null; it can be used to set a new image size at the same time the image is updated, if applicable.
    // if "twostage" is true, the first load will occur immediately, and the return value will be a function
    // that takes a boolean parameter (true to proceed with the 2nd load (including the blank-and-reload procedure), false to cancel) and an optional updated imgDim.
    // This allows you to do the first load early... for example during an upload (to the server) of the image you want to (then) refresh.
    function forceImgReload(src, isCrossDomain, imgDim, twostage)
    {
      var blankList, step = 0,                                // step: 0 - started initial load, 1 - wait before proceeding (twostage mode only), 2 - started forced reload, 3 - cancelled
          iframe = window.document.createElement("iframe"),   // Hidden iframe, in which to perform the load+reload.
          loadCallback = function(e)                          // Callback function, called after iframe load+reload completes (or fails).
          {                                                   // Will be called TWICE unless twostage-mode process is cancelled. (Once after load, once after reload).
            if (!step)  // initial load just completed.  Note that it doesn't actually matter if this load succeeded or not!
            {
              if (twostage) step = 1;  // wait for twostage-mode proceed or cancel; don't do anything else just yet
              else { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); }  // initiate forced-reload
            }
            else if (step===2)   // forced re-load is done
            {
              imgReloadRestore(src,blankList,imgDim,(e||window.event).type==="error");    // last parameter checks whether loadCallback was called from the "load" or the "error" event.
              if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
            }
          }
      iframe.style.display = "none";
      window.parent.document.body.appendChild(iframe);    // NOTE: if this is done AFTER setting src, Firefox MAY fail to fire the load event!
      iframe.addEventListener("load",loadCallback,false);
      iframe.addEventListener("error",loadCallback,false);
      iframe.src = (isCrossDomain ? "/echoimg.php?src="+encodeURIComponent(src) : src);  // If src is cross-domain, script will crash unless we embed the image in a same-domain html page (using server-side script)!!!
      return (twostage
        ? function(proceed,dim)
          {
            if (!twostage) return;
            twostage = false;
            if (proceed)
            {
              imgDim = (dim||imgDim);  // overwrite imgDim passed in to forceImgReload() - just in case you know the correct img dimensions now, but didn't when forceImgReload() was called.
              if (step===1) { step = 2; blankList = imgReloadBlank(src); iframe.contentWindow.location.reload(true); }
            }
            else
            {
              step = 3;
              if (iframe.contentWindow.stop) iframe.contentWindow.stop();
              if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
            }
          }
        : null);
    }
    

    Then, to force a refresh of an image located on the same domain as your page, you can just do:

    forceImgReload("myimage.jpg");
    

    To refresh an image from somewhere else (cross-domain):

    forceImgReload("http://someother.server.com/someimage.jpg", true);
    

    A more advanced application might be to reload an image after uploading a new version to your server, preparing the initial stage of the reload process simultaneous with the upload, to minimize the visible reload delay to the user. If you're doing the upload via AJAX, and the server is returning a very simple JSON array [success, width, height] then your code might look something like this:

    // fileForm is a reference to the form that has a the <input typ="file"> on it, for uploading.
    // serverURL is the url at which the uploaded image will be accessible from, once uploaded.
    // The response from uploadImageToServer.php is a JSON array [success, width, height]. (A boolean and two ints).
    function uploadAndRefreshCache(fileForm, serverURL)
    {
      var xhr = new XMLHttpRequest(),
          proceedWithImageRefresh = forceImgReload(serverURL, false, null, true);
      xhr.addEventListener("load", function(){ var arr = JSON.parse(xhr.responseText); if (!(arr&&arr[0])) { proceedWithImageRefresh(false); doSomethingOnUploadFailure(...); } else { proceedWithImageRefresh(true,[arr[1],ar[2]]); doSomethingOnUploadSuccess(...); }});
      xhr.addEventListener("error", function(){ proceedWithImageRefresh(false); doSomethingOnUploadError(...); });
      xhr.addEventListener("abort", function(){ proceedWithImageRefresh(false); doSomethingOnUploadAborted(...); });
      // add additional event listener(s) to track upload progress for graphical progress bar, etc...
      xhr.open("post","uploadImageToServer.php");
      xhr.send(new FormData(fileForm));
    }
    

    A final note: Although this topic is about images, it potentially applies to other kinds of files or resources also. For example, preventing the use of stale script or css files, or perhaps even refreshing updated PDF documents (using (4) only if set up to open in-browser). Method (4) might require some changes to the above javascript, in these cases.

    Remove All Event Listeners of Specific Type

    That is not possible without intercepting addEventListener calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the feature wasn't implemented.

    The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.

    Note: This will also remove listeners on element's children.

    var el = document.getElementById('el-id'),
        elClone = el.cloneNode(true);
    
    el.parentNode.replaceChild(elClone, el);
    

    Pass a variable to a PHP script running from the command line

    There are four main alternatives. Both have their quirks, but Method 4 has many advantages from my view.


    ./script is a shell script starting by #!/usr/bin/php


    Method 1: $argv

    ./script hello wo8844rld
    // $argv[0] = "script", $argv[1] = "hello", $argv[2] = "wo8844rld"
    

    ?? Using $argv, the parameter order is critical.


    Method 2: getopt()

    ./script -p7 -e3
    // getopt("p::")["p"] = "7", getopt("e::")["e"] = "3"
    

    It's hard to use in conjunction of $argv, because:

    ?? The parsing of options will end at the first non-option found, anything that follows is discarded.

    ?? Only 26 parameters as the alphabet.


    Method 3: Bash Global variable

    P9="xptdr" ./script
    // getenv("P9") = "xptdr"
    // $_SERVER["P9"] = "xptdr"
    

    Those variables can be used by other programs running in the same shell.

    They are blown when the shell is closed, but not when the PHP program is terminated. We can set them permanent in file ~/.bashrc!


    Method 4: STDIN pipe and stream_get_contents()

    Some piping examples:


    Feed a string:

    ./script <<< "hello wo8844rld"
    // stream_get_contents(STDIN) = "hello wo8844rld"
    

    Feed a string using bash echo:

    echo "hello wo8844rld" | ./script
    // explode(" ",stream_get_contents(STDIN)) ...
    

    Feed a file content:

    ./script < ~/folder/Special_params.txt
    // explode("\n",stream_get_contents(STDIN)) ...
    

    Feed an array of values:

    ./script <<< '["array entry","lol"]'
    // var_dump( json_decode(trim(stream_get_contents(STDIN))) );
    

    Feed JSON content from a file:

    echo params.json | ./script
    // json_decode(stream_get_contents(STDIN)) ...
    

    It might work similarly to fread() or fgets(), by reading the STDIN.


    Bash-Scripting Guide

    Setting graph figure size

    I managed to get a good result with the following sequence (run Matlab twice at the beginning):

    h = gcf; % Current figure handle
    set(h,'Resize','off');
    set(h,'PaperPositionMode','manual');
    set(h,'PaperPosition',[0 0 9 6]);
    set(h,'PaperUnits','centimeters');
    set(h,'PaperSize',[9 6]); % IEEE columnwidth = 9cm
    set(h,'Position',[0 0 9 6]);
    % xpos, ypos must be set
    txlabel = text(xpos,ypos,'$$[\mathrm{min}]$$','Interpreter','latex','FontSize',9);
    
    % Dump colored encapsulated PostScript
    print('-depsc2','-loose', 'signals');
    

    How to get Node.JS Express to listen only on localhost?

    You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

    Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

    var express = require('express');
    var http = require('http');
    
    var app = express();
    var server = http.createServer(app);
    
    app.get('/', function(req, res) {
        res.send("Hello World!");
    });
    
    server.listen(3000, 'localhost');
    server.on('listening', function() {
        console.log('Express server started on port %s at %s', server.address().port, server.address().address);
    });
    

    This works just fine in nodejs v0.6+ and Express v3.0+.

    Shuffling a list of objects

    import random
    
    class a:
        foo = "bar"
    
    a1 = a()
    a2 = a()
    a3 = a()
    a4 = a()
    b = [a1,a2,a3,a4]
    
    random.shuffle(b)
    print(b)
    

    shuffle is in place, so do not print result, which is None, but the list.

    Datagrid binding in WPF

    Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

    <DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
        <DataGrid.Columns>                
            <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
            <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
       </DataGrid.Columns>
    </DataGrid>
    

    (This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

    Where do I configure log4j in a JUnit test class?

    I use system properties in log4j.xml:

    ...
    <param name="File" value="${catalina.home}/logs/root.log"/>
    ...
    

    and start tests with:

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.16</version>
        <configuration>
            <systemProperties>
                <property>
                    <name>catalina.home</name>
                    <value>${project.build.directory}</value>
                </property>
            </systemProperties>
        </configuration>
    </plugin>
    

    Best way to check for "empty or null value"

    To check for null and empty:

    coalesce(string, '') = ''
    

    To check for null, empty and spaces (trim the string)

    coalesce(TRIM(string), '') = ''
    

    Angular2 router (@angular/router), how to set default route?

    I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7

    It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts

    routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
               {path: '', 
               children: [{
                 path:'home',
                 loadChildren :'lazy module path'      
               }]
    
             }];
    
     routes configured at HomeModule
     const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
                 {path: 'default', component: MyPageComponent},
                ]
    
     instead of 
     const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
                       {path: 'default', component: MyPageComponent},
                    ]
    

    change cursor from block or rectangle to line?

    please Press fn +ins key together

    Sourcetree - undo unpushed commits

    If you select the log entry to which you want to revert to then you can click on "Reset to this commit". Only use this option if you didn't push the reverse commit changes. If you're worried about losing the changes then you can use the soft mode which will leave a set of uncommitted changes (what you just changed). Using the mixed resets the working copy but keeps those changes, and a hard will just get rid of the changes entirely. Here's some screenshots:

    enter image description here

    macro run-time error '9': subscript out of range

    "Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

    How to select the first element with a specific attribute using XPath

    /bookstore/book[@location='US'][1] works only with simple structure.

    Add a bit more structure and things break.

    With-

    <bookstore>
     <category>
      <book location="US">A1</book>
      <book location="FIN">A2</book>
     </category>
     <category>
      <book location="FIN">B1</book>
      <book location="US">B2</book>
     </category>
    </bookstore> 
    

    /bookstore/category/book[@location='US'][1] yields

    <book location="US">A1</book>
    <book location="US">B2</book>
    

    not "the first node that matches a more complicated condition". /bookstore/category/book[@location='US'][2] returns nothing.

    With parentheses you can get the result the original question was for:

    (/bookstore/category/book[@location='US'])[1] gives

    <book location="US">A1</book>
    

    and (/bookstore/category/book[@location='US'])[2] works as expected.

    What's the difference between struct and class in .NET?

    Structure vs Class

    A structure is a value type so it is stored on the stack, but a class is a reference type and is stored on the heap.

    A structure doesn't support inheritance, and polymorphism, but a class supports both.

    By default, all the struct members are public but class members are by default private in nature.

    As a structure is a value type, we can't assign null to a struct object, but it is not the case for a class.

    Laravel: How do I parse this json data in view blade?

    You can use json decode then you get php array,and use that value as your own way

    <?php 
    $leads = json_decode($leads, true);
    dd($leads);
    

    What is the significance of 1/1/1753 in SQL Server?

    Your great great great great great great great grandfather should upgrade to SQL Server 2008 and use the DateTime2 data type, which supports dates in the range: 0001-01-01 through 9999-12-31.

    how to configuring a xampp web server for different root directory

    If you are running xampp on linux based image, to change root directory open:

    /opt/lampp/etc/httpd.conf
    

    Change default document root: DocumentRoot "/opt/lampp/htdocs" and <Directory "/opt/lampp/htdocs"

    to your folder DocumentRoot "/opt/lampp/htdocs/myFolder" and <Directory "/opt/lampp/htdocs/myFolder">

    How to add a class to body tag?

    $('body').toggleClass("className");
    

    perfectly works

    Forward declaration of a typedef in C++

    Like @BillKotsias, I used inheritance, and it worked for me.

    I changed this mess (which required all the boost headers in my declaration *.h)

    #include <boost/accumulators/accumulators.hpp>
    #include <boost/accumulators/statistics.hpp>
    #include <boost/accumulators/statistics/stats.hpp>
    #include <boost/accumulators/statistics/mean.hpp>
    #include <boost/accumulators/statistics/moment.hpp>
    #include <boost/accumulators/statistics/min.hpp>
    #include <boost/accumulators/statistics/max.hpp>
    
    typedef boost::accumulators::accumulator_set<float,
     boost::accumulators::features<
      boost::accumulators::tag::median,
      boost::accumulators::tag::mean,
      boost::accumulators::tag::min,
      boost::accumulators::tag::max
     >> VanillaAccumulator_t ;
    std::unique_ptr<VanillaAccumulator_t> acc;
    

    into this declaration (*.h)

    class VanillaAccumulator;
    std::unique_ptr<VanillaAccumulator> acc;
    

    and the implementation (*.cpp) was

    #include <boost/accumulators/accumulators.hpp>
    #include <boost/accumulators/statistics.hpp>
    #include <boost/accumulators/statistics/stats.hpp>
    #include <boost/accumulators/statistics/mean.hpp>
    #include <boost/accumulators/statistics/moment.hpp>
    #include <boost/accumulators/statistics/min.hpp>
    #include <boost/accumulators/statistics/max.hpp>
    
    class VanillaAccumulator : public
      boost::accumulators::accumulator_set<float,
        boost::accumulators::features<
          boost::accumulators::tag::median,
          boost::accumulators::tag::mean,
          boost::accumulators::tag::min,
          boost::accumulators::tag::max
    >>
    {
    };
    

    Difference between checkout and export in SVN

    Any chance the build process is looking into the subdirectories and including something it shouldn't? BTW, you can do a legal checkout, then remove the .svn and all it contains. That should give you the same as an export. Try compiling that, before and after removing the metadata, as it were.

    Add JVM options in Tomcat

    Set it in the JAVA_OPTS variable in [path to tomcat]/bin/catalina.sh. Under windows there is a console where you can set it up or you use the catalina.bat.

    JAVA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
    

    Bootstrap 4 navbar color

    I got it. This is very simple. Using the class bg you can achieve this easily.

    Let me show you:

    <nav class="navbar navbar-expand-lg navbar-dark navbar-full bg-primary"></nav>
    

    This gives you the default blue navbar

    If you want to change your favorite color, then simply use the style tag within the nav:

    <nav class="navbar navbar-expand-lg navbar-dark navbar-full" style="background-color: #FF0000">
    

    How to run C program on Mac OS X using Terminal?

    to compile c-program in macos simply follow below steps

    using cd command in terminal go to your c-program location
    then type the command present below
    make filename
    then type
    ./filename

    How can I retrieve the remote git address of a repo?

    If you have the name of the remote, you will be able with git 2.7 (Q4 2015), to use the new git remote get-url command:

    git remote get-url origin
    

    (nice pendant of git remote set-url origin <newurl>)

    See commit 96f78d3 (16 Sep 2015) by Ben Boeckel (mathstuf).
    (Merged by Junio C Hamano -- gitster -- in commit e437cbd, 05 Oct 2015)

    remote: add get-url subcommand

    Expanding insteadOf is a part of ls-remote --url and there is no way to expand pushInsteadOf as well.
    Add a get-url subcommand to be able to query both as well as a way to get all configured urls.

    Set icon for Android application

    Define the icon for android application

    <application android:icon="drawable resource">
    .... 
    </application> 
    

    https://developer.android.com/guide/topics/manifest/application-element.html


    If your app available across large range of devices

    You should create separate icons for all generalized screen densities, including low-, medium-, high-, and extra-high-density screens. This ensures that your icons will display properly across the range of devices on which your application can be installed...

    enter image description here


    Size & Format

    Launcher icons should be 32-bit PNGs with an alpha channel for transparency. The finished launcher icon dimensions corresponding to a given generalized screen density are shown in the table below.

    enter image description here


    Place icon in mipmap or drawable folder

    android:icon="@drawable/icon_name" or android:icon="@mipmap/icon_name"

    developer.android.com/guide says,

    This attribute must be set as a reference to a drawable resource containing the image (for example "@drawable/icon").

    about launcher icons android-developers.googleblog.com says,

    It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density. For example, an xxxhdpi app icon can be used on the launcher for an xxhdpi device.

    Dianne Hackborn from Google (Android Framework) says,

    If you are building different versions of your app for different densities, you should know about the "mipmap" resource directory. This is exactly like "drawable" resources, except it does not participate in density stripping when creating the different apk targets.

    For launcher icons, the AndroidManifest.xml file must reference the mipmap/ location

    <application android:name="ApplicationTitle"
             android:label="@string/app_label"
             android:icon="@mipmap/ic_launcher" >
    

    Little bit more quoting this

    1. You want to load an image for your device density and you are going to use it "as is", without changing its actual size. In this case you should work with drawables and Android will give you the best fitting image.

    2. You want to load an image for your device density, but this image is going to be scaled up or down. For instance this is needed when you want to show a bigger launcher icon, or you have an animation, which increases image's size. In such cases, to ensure best image quality, you should put your image into mipmap folder. What Android will do is, it will try to pick up the image from a higher density bucket instead of scaling it up. This will increase sharpness (quality) of the image.

    Fore more you can read mipmap vs drawable folders


    Tools to easily generate assets

    1. Android Asset Studio by romannurik.github
    2. Android Asset Studio by jgilfelt.github
    3. Image Asset Studio(from Android Studio)
    4. Material Icon Generator.bitdroid.de
    5. Android Material Design Icon Generator Plugin by github.com/konifar
    6. A script to generate android assets from a SVG file

    Read more : https://developer.android.com/guide/practices/ui_guidelines/icon_design_launcher.html

    How to Get a Sublist in C#

    Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.

    Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.

    R - " missing value where TRUE/FALSE needed "

    check the command : NA!=NA : you'll get the result NA, hence the error message.

    You have to use the function is.na for your ifstatement to work (in general, it is always better to use this function to check for NA values) :

    comments = c("no","yes",NA)
    for (l in 1:length(comments)) {
        if (!is.na(comments[l])) print(comments[l])
    }
    [1] "no"
    [1] "yes"
    

    Add space between two particular <td>s

    td:nth-of-type(n) { padding-right: 10px;}

    it will adjust auto space between all td

    Set Content-Type to application/json in jsp file

    @Petr Mensik & kensen john

    Thanks, I could not used the page directive because I have to set a different content type according to some URL parameter. I will paste my code here since it's something quite common with JSON:

        <%
            String callback = request.getParameter("callback");
            response.setCharacterEncoding("UTF-8");
            if (callback != null) {
                // Equivalent to: <@page contentType="text/javascript" pageEncoding="UTF-8">
                response.setContentType("text/javascript");
            } else {
                // Equivalent to: <@page contentType="application/json" pageEncoding="UTF-8">
                response.setContentType("application/json");
            }
    
            [...]
    
            String output = "";
    
            if (callback != null) {
                output += callback + "(";
            }
    
            output += jsonObj.toString();
    
            if (callback != null) {
                output += ");";
            }
        %>
        <%=output %>
    

    When callback is supplied, returns:

        callback({...JSON stuff...});
    

    with content-type "text/javascript"

    When callback is NOT supplied, returns:

        {...JSON stuff...}
    

    with content-type "application/json"

    Forward request headers from nginx proxy server

    If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

    location / {
        proxy_pass                      http://example.com;
        proxy_set_header                Host example.com;
        proxy_set_header                HTTP_Country-Code $geoip_country_code;
        proxy_pass_request_headers      on;
    }
    

    And now it's passed to the proxy backend.

    CSS Div stretch 100% page height

    If you are targeting more modern browsers, life can be very simple. try:

    .elem{    
        height: 100vh;
     }
    

    if you need it at 50% of the page, replace 100 with 50.

    How to give a pattern for new line in grep?

    try pcregrep instead of regular grep:

    pcregrep -M "pattern1.*\n.*pattern2" filename
    

    the -M option allows it to match across multiple lines, so you can search for newlines as \n.

    C# generic list <T> how to get the type of T?

    Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

    Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.

    /// <summary>
    /// Test if a type implements IList of T, and if so, determine T.
    /// </summary>
    public static bool TryListOfWhat(Type type, out Type innerType)
    {
        Contract.Requires(type != null);
    
        var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);
    
        innerType = interfaceTest(type);
        if (innerType != null)
        {
            return true;
        }
    
        foreach (var i in type.GetInterfaces())
        {
            innerType = interfaceTest(i);
            if (innerType != null)
            {
                return true;
            }
        }
    
        return false;
    }
    

    Example usage:

        object value = new ObservableCollection<int>();
    Type innerType;
    TryListOfWhat(value.GetType(), out innerType).Dump();
    innerType.Dump();
    

    Returns

    True
    typeof(Int32)