Programs & Examples On #Virtual hosts

Virtual hosts or virtual hosting is a method for hosting multiple domain names (with separate handling of each name) on a single server (or pool of servers).

Wildcards in a Windows hosts file

Editing the hosts file is less of a pain when you run "ipconfig /flushdns" from the windows command prompt, instead of restarting your computer.

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Redirect parent window from an iframe action

or an alternative is the following (using document object)

parent.document.location.href = "http://example.com";

"The import org.springframework cannot be resolved."

In my case, this issue was resolved by updating maven's dependencies:

enter image description here

How to cast/convert pointer to reference in C++

Call it like this:

foo(*ob);

Note that there is no casting going on here, as suggested in your question title. All we have done is de-referenced the pointer to the object which we then pass to the function.

Is it possible to opt-out of dark mode on iOS 13?

You can turn Dark Mode off in entire application in Xcode 11:

  1. Go Info.plist
  2. Add bellow like

    <key>UIUserInterfaceStyle</key>
    <string>Light</string>
    

Info.plist will be look like below...

enter image description here

Clear dropdownlist with JQuery

I tried both .empty() as well as .remove() for my dropdown and both were slow. Since I had almost 4,000 options there.

I used .html("") which is much faster in my condition.
Which is below

  $(dropdown).html("");

Install Application programmatically on Android

Do not forget to request permissions:

android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
android.Manifest.permission.READ_EXTERNAL_STORAGE

Add in AndroidManifest.xml the provider and permission:

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

Create XML file provider res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

Use below example code:

   public class InstallManagerApk extends AppCompatActivity {

    static final String NAME_APK_FILE = "some.apk";
    public static final int REQUEST_INSTALL = 0;

     @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // required permission:
        // android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
        // android.Manifest.permission.READ_EXTERNAL_STORAGE

        installApk();

    }

    ...

    /**
     * Install APK File
     */
    private void installApk() {

        try {

            File filePath = Environment.getExternalStorageDirectory();// path to file apk
            File file = new File(filePath, LoadManagerApkFile.NAME_APK_FILE);

            Uri uri = getApkUri( file.getPath() ); // get Uri for  each SDK Android

            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData( uri );
            intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK );
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
            intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, getApplicationInfo().packageName);

            if ( getPackageManager().queryIntentActivities(intent, 0 ) != null ) {// checked on start Activity

                startActivityForResult(intent, REQUEST_INSTALL);

            } else {
                throw new Exception("don`t start Activity.");
            }

        } catch ( Exception e ) {

            Log.i(TAG + ":InstallApk", "Failed installl APK file", e);
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG)
                .show();

        }

    }

    /**
     * Returns a Uri pointing to the APK to install.
     */
    private Uri getApkUri(String path) {

        // Before N, a MODE_WORLD_READABLE file could be passed via the ACTION_INSTALL_PACKAGE
        // Intent. Since N, MODE_WORLD_READABLE files are forbidden, and a FileProvider is
        // recommended.
        boolean useFileProvider = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;

        String tempFilename = "tmp.apk";
        byte[] buffer = new byte[16384];
        int fileMode = useFileProvider ? Context.MODE_PRIVATE : Context.MODE_WORLD_READABLE;
        try (InputStream is = new FileInputStream(new File(path));
             FileOutputStream fout = openFileOutput(tempFilename, fileMode)) {

            int n;
            while ((n = is.read(buffer)) >= 0) {
                fout.write(buffer, 0, n);
            }

        } catch (IOException e) {
            Log.i(TAG + ":getApkUri", "Failed to write temporary APK file", e);
        }

        if (useFileProvider) {

            File toInstall = new File(this.getFilesDir(), tempFilename);
            return FileProvider.getUriForFile(this,  BuildConfig.APPLICATION_ID, toInstall);

        } else {

            return Uri.fromFile(getFileStreamPath(tempFilename));

        }

    }

    /**
     * Listener event on installation APK file
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == REQUEST_INSTALL) {

            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this,"Install succeeded!", Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this,"Install canceled!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this,"Install Failed!", Toast.LENGTH_SHORT).show();
            }

        }

    }

    ...

}

Android emulator-5554 offline

I also had the same issue. I've tried all described here solutions but they didn't help me. Then I've removed all emulators in the Android Virtual Device Manager and created new ones. The problem was in CPU/ABI system image configuration of the Android Virtual Device Manager. On my Windows10 machine emulator with system image x86 always is offline where emulator with system image x86_64 is working fine as expected. Just be aware of this

What is “assert” in JavaScript?

It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):

http://chaijs.com/guide/styles/#assert

How do I add an image to a JButton

buttonB.setIcon(new ImageIcon(this.getClass().getResource("imagename")));

How to concatenate columns in a Postgres SELECT?

For example if there is employee table which consists of columns as:

employee_number,f_name,l_name,email_id,phone_number 

if we want to concatenate f_name + l_name as name.

SELECT employee_number,f_name ::TEXT ||','|| l_name::TEXT  AS "NAME",email_id,phone_number,designation FROM EMPLOYEE;

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

Try using ReadAsStringAsync() instead.

 var foo = resp.Content.ReadAsStringAsync().Result;

The reason why it ReadAsAsync<string>() doesn't work is because ReadAsAsync<> will try to use one of the default MediaTypeFormatter (i.e. JsonMediaTypeFormatter, XmlMediaTypeFormatter, ...) to read the content with content-type of text/plain. However, none of the default formatter can read the text/plain (they can only read application/json, application/xml, etc).

By using ReadAsStringAsync(), the content will be read as string regardless of the content-type.

How to take last four characters from a varchar?

Use the RIGHT() function: http://msdn.microsoft.com/en-us/library/ms177532(v=sql.105).aspx

SELECT RIGHT( '1234567890', 4 ); -- returns '7890'

Ways to circumvent the same-origin policy

The most recent way of overcoming the same-origin policy that I've found is http://anyorigin.com/

The site's made so that you just give it any url and it generates javascript/jquery code for you that lets you get the html/data, regardless of it's origin. In other words, it makes any url or webpage a JSONP request.

I've found it pretty useful :)

Here's some example javascript code from anyorigin:

$.getJSON('http://anyorigin.com/get?url=google.com&callback=?', function(data){
    $('#output').html(data.contents);
});

How do I put two increment statements in a C++ 'for' loop?

Try this

for(int i = 0; i != 5; ++i, ++j)
    do_something(i,j);

Download file through an ajax call php

AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

Setting query string using Fetch GET request

encodeQueryString — encode an object as querystring parameters

/**
 * Encode an object as url query string parameters
 * - includes the leading "?" prefix
 * - example input — {key: "value", alpha: "beta"}
 * - example output — output "?key=value&alpha=beta"
 * - returns empty string when given an empty object
 */
function encodeQueryString(params) {
    const keys = Object.keys(params)
    return keys.length
        ? "?" + keys
            .map(key => encodeURIComponent(key)
                + "=" + encodeURIComponent(params[key]))
            .join("&")
        : ""
}

encodeQueryString({key: "value", alpha: "beta"})
 //> "?key=value&alpha=beta"

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

This should work if current file is located in same directory where initcontrols is:

<?php
$ds = DIRECTORY_SEPARATOR;
$base_dir = realpath(dirname(__FILE__)  . $ds . '..') . $ds;
require_once("{$base_dir}initcontrols{$ds}config.php");
?>
<div>
<?php 
$file = "{$base_dir}initcontrols{$ds}header_myworks.php"; 
include_once($file); 
echo $plHeader;?>   
</div>

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

How to Update Multiple Array Elements in mongodb

I've been looking for a solution to this using the newest driver for C# 3.6 and here's the fix I eventually settled on. The key here is using "$[]" which according to MongoDB is new as of version 3.6. See https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[] for more information.

Here's the code:

{
   var filter = Builders<Scene>.Filter.Where(i => i.ID != null);
   var update = Builders<Scene>.Update.Unset("area.$[].discoveredBy");
   var result = collection.UpdateMany(filter, update, new UpdateOptions { IsUpsert = true});
}

For more context see my original post here: Remove array element from ALL documents using MongoDB C# driver

Insert value into a string at a certain position?

If you just want to insert a value at a certain position in a string, you can use the String.Insert method:

public string Insert(int startIndex, string value)

Example:

"abc".Insert(2, "XYZ") == "abXYZc"

Unresponsive KeyListener for JFrame

InputMaps and ActionMaps were designed to capture the key events for the component, it and all of its sub-components, or the entire window. This is controlled through the parameter in JComponent.getInputMap(). See How to Use Key Bindings for documentation.

The beauty of this design is that one can pick and choose which key strokes are important to monitor and have different actions fired based on those key strokes.

This code will call dispose() on a JFrame when the escape key is hit anywhere in the window. JFrame doesn't derive from JComponent so you have to use another component in the JFrame to create the key binding. The content pane might be such a component.

InputMap inputMap; 
ActionMap actionMap;
AbstractAction action;
JComponent component;

inputMap  = component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
actionMap = component.getActionMap();

action    = new AbstractAction()
{
   @Override
   public void actionPerformed(ActionEvent e)
   {
      dispose();
   }
};

inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "dispose");
actionMap.put("dispose", action);

How to obtain the location of cacerts of the default java installation?

Under Linux, to find the location of $JAVA_HOME:

readlink -f /usr/bin/java | sed "s:bin/java::"

the cacerts are under lib/security/cacerts:

$(readlink -f /usr/bin/java | sed "s:bin/java::")lib/security/cacerts

Under mac OS X , to find $JAVA_HOME run:

/usr/libexec/java_home

the cacerts are under Home/lib/security/cacerts:

$(/usr/libexec/java_home)/lib/security/cacerts

UPDATE (OS X with JDK)

above code was tested on computer without JDK installed. With JDK installed, as pR0Ps said, it's at

$(/usr/libexec/java_home)/jre/lib/security/cacerts

BULK INSERT with identity (auto-increment) column

My solution is to add the ID field as the LAST field in the table, thus bulk insert ignores it and it gets automatic values. Clean and simple ...

For instance, if inserting into a temp table:

CREATE TABLE #TempTable 
(field1 varchar(max), field2 varchar(max), ... 
ROW_ID int IDENTITY(1,1) NOT NULL)

Note that the ROW_ID field MUST always be specified as LAST field!

SQL Server Format Date DD.MM.YYYY HH:MM:SS

A quick way to do it in sql server 2012 is as follows:

SELECT FORMAT(GETDATE() , 'dd/MM/yyyy HH:mm:ss')

How to get Maven project version to the bash command line

If you don't mind to write the version into a temporary file, there is another solution (without grep/sed) that works well for me. (EDIT: see rjrjr's answer for a much simpler solution without any temporary file hassle)

I use the Exec Maven Plugin along with the echo binary. In contrast to the Maven Help Plugin, the Exec Plugin allows output redirection into a file, which can be used to bypass grep/sed, and makes it even possible to parse strange things like multiline version strings (with CDATA block in version tag), at least to a certain extent.

#!/usr/bin/env sh

MVN_VERSION=""
VERSION_FILE=$( mktemp mvn_project_version_XXXXX )
trap "rm -f -- \"$VERSION_FILE\"" INT EXIT

mvn -Dexec.executable="echo" \
    -Dexec.args='${project.version}' \
    -Dexec.outputFile="$VERSION_FILE" \
    --non-recursive \
    --batch-mode \
    org.codehaus.mojo:exec-maven-plugin:1.3.1:exec > /dev/null 2>&1 ||
    { echo "Maven invocation failed!" 1>&2; exit 1; }

# if you just care about the first line of the version, which will be
# sufficent for pretty much every use case I can imagine, you can use
# the read builtin
[ -s "$VERSION_FILE" ] && read -r MVN_VERSION < "$VERSION_FILE"

# Otherwise, you could use cat.
# Note that this still has issues when there are leading whitespaces
# in the multiline version string
#MVN_VERSION=$( cat "$VERSION_FILE" )

printf "Maven project version: %s\n" "$MVN_VERSION"

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

Online code beautifier and formatter

What language?? There are different tools for almost every imaginable programming language, since they all have different syntactic rules and conventions.

Good ol' indent is a nice, customizable, command-line utility to format C and C++ programs.

How can I print a quotation mark in C?

This one also works:

printf("%c\n", printf("Here, I print some double quotes: "));

But if you plan to use it in an interview, make sure you can explain what it does.

EDIT: Following Eric Postpischil's comment, here's a version that doesn't rely on ASCII:

printf("%c\n", printf("%*s", '"', "Printing quotes: "));

The output isn't as nice, and it still isn't 100% portable (will break on some hypothetical encoding schemes), but it should work on EBCDIC.

What Are The Best Width Ranges for Media Queries

best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920

Vim for Windows - What do I type to save and exit from a file?

A faster way to

  • Save
  • and quit

would be

:x

If you have opened multiple files you may need to do a

:xa

Xcode 8 shows error that provisioning profile doesn't include signing certificate

Had the same error. Profiles seems renewed, new certificates added, i even checked it when download. Also revoked former developer's certificates, excluded from provision profile. But Xcode still asking me about previous certificates with error:

No certificate for team 'MY_TEAM' matching 'iPhone Developer: FORMER_DEVELOPER' found

so, what I did to fix it:

  1. Go Build Settings -> Signing -> Code Signing Identity
  2. Find all 'FORMER_DEVELOPER' certificates and choose needed.

Hope it will help somebody.

How to substitute shell variables in complex text files

In reference to answer 2, when discussing envsubst, you asked:

How can I make it work with the variables that are declared in my .sh script?

The answer is you simply need to export your variables before calling envsubst.

You can also limit the variable strings you want to replace in the input using the envsubst SHELL_FORMAT argument (avoiding the unintended replacement of a string in the input with a common shell variable value - e.g. $HOME).

For instance:

export VAR1='somevalue' VAR2='someothervalue'
MYVARS='$VAR1:$VAR2'

envsubst "$MYVARS" <source.txt >destination.txt

Will replace all instances of $VAR1 and $VAR2 (and only VAR1 and VAR2) in source.txt with 'somevalue' and 'someothervalue' respectively.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

For me this problem occurred because I had a some invalid character in my Groovy script. In our case this was an extra blank line after the closing bracket of the script.

TextView Marquee not working

You must add the these attributes which is compulsary to marquee

 android:ellipsize="marquee"     
 android:focusable="true"    
 android:focusableInTouchMode="true"     
 android:singleLine="true"     
 android:marqueeRepeatLimit="marquee_forever"     
 android:scrollHorizontally="true"

how to measure running time of algorithms in python

Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods.

Below I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net.

import time                                                

def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        print '%r (%r, %r) %2.2f sec' % \
              (method.__name__, args, kw, te-ts)
        return result

    return timed

class Foo(object):

    @timeit
    def foo(self, a=2, b=3):
        time.sleep(0.2)

@timeit
def f1():
    time.sleep(1)
    print 'f1'

@timeit
def f2(a):
    time.sleep(2)
    print 'f2',a

@timeit
def f3(a, *args, **kw):
    time.sleep(0.3)
    print 'f3', args, kw

f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()

// John

'dependencies.dependency.version' is missing error, but version is managed in parent

A couple things I think you could try:

  1. Put the literal value of the version in the child pom

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>3.2.3.RELEASE</version>
      <scope>runtime</scope>
    </dependency>
    
  2. Clear your .m2 cache normally located C:\Users\user.m2\repository. I would say I do this pretty frequently when I'm working in maven. Especially before committing so that I can be more confident CI will run. You don't have to nuke the folder every time, sometimes just your project packages and the .cache folder are enough.

  3. Add a relativePath tag to your parent pom declaration

    <parent>
      <groupId>com.mycompany.app</groupId>
      <artifactId>my-app</artifactId>
      <version>1</version>
     <relativePath>../parent/pom.xml</relativePath>
    </parent>
    

It looks like you have 8 total errors in your poms. I would try to get some basic compilation running before adding the parent pom and properties.

"Could not find or load main class" Error while running java program using cmd prompt

I faced the same problem and tried everything mentioned here. The thing was I didn't refresh my project in eclipse after class creation . And once I refreshed it things worked as expected.

Splitting a C++ std::string using tokens, e.g. ";"

I find std::getline() is often the simplest. The optional delimiter parameter means it's not just for reading "lines":

#include <sstream>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<string> strings;
    istringstream f("denmark;sweden;india;us");
    string s;    
    while (getline(f, s, ';')) {
        cout << s << endl;
        strings.push_back(s);
    }
}

How can I change UIButton title color?

With Swift 5, UIButton has a setTitleColor(_:for:) method. setTitleColor(_:for:) has the following declaration:

Sets the color of the title to use for the specified state.

func setTitleColor(_ color: UIColor?, for state: UIControlState)

The following Playground sample code show how to create a UIbutton in a UIViewController and change it's title color using setTitleColor(_:for:):

import UIKit
import PlaygroundSupport

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white

        // Create button
        let button = UIButton(type: UIButton.ButtonType.system)

        // Set button's attributes
        button.setTitle("Print 0", for: UIControl.State.normal)
        button.setTitleColor(UIColor.orange, for: UIControl.State.normal)

        // Set button's frame
        button.frame.origin = CGPoint(x: 100, y: 100)
        button.sizeToFit()

        // Add action to button
        button.addTarget(self, action: #selector(printZero(_:)), for: UIControl.Event.touchUpInside)

        // Add button to subView
        view.addSubview(button)
    }

    @objc func printZero(_ sender: UIButton) {
        print("0")
    }

}

let controller = ViewController()
PlaygroundPage.current.liveView = controller

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

Dependencies

These are the packages that your package needs to run, so they will be installed when people run

 npm install PACKAGE-NAME

An example would be if you used jQuery in your project. If someone doesn't have jQuery installed, then it wouldn't work. To save as a dependency, use

 npm install --save

Dev-Dependencies

These are the dependencies that you use in development, but isn't needed when people are using it, so when people run npm install, it won't install them since the are not necessary. For example, if you use mocha to test, people don't need mocha to run, so npm install doesn't install it. To save as a dev dependency, use

npm install PACKAGE --save-dev

Peer Dependencies

These can be used if you want to create and publish your own library so that it can be used as a dependency. For example, if you want your package to be used as a dependency in another project, then these will also be installed when someone installs the project which has your project as a dependency. Most of the time you won't use peer dependencies.

What is newline character -- '\n'

Try this:

$ sed -e $'s/\n/\n\n/g' states

Detect click inside/outside of element with single event handler

In vanilla javaScript - in ES6

_x000D_
_x000D_
(() => {_x000D_
    document.querySelector('.parent').addEventListener('click', event => {_x000D_
        alert(event.target.classList.contains('child') ? 'Child element.' : 'Parent element.');_x000D_
    });_x000D_
})();
_x000D_
.parent {_x000D_
    display: inline-block;_x000D_
    padding: 45px;_x000D_
    background: lightgreen;_x000D_
}_x000D_
.child {_x000D_
    width: 120px;_x000D_
    height:60px;_x000D_
    background: teal;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Text-decoration: none not working

a:link{
  text-decoration: none!important;
}

=> Working with me :) , good luck

How can jQuery deferred be used?

I've just used Deferred in real code. In project jQuery Terminal I have function exec that call commands defined by user (like he was entering it and pressing enter), I've added Deferreds to the API and call exec with arrays. like this:

terminal.exec('command').then(function() {
   terminal.echo('command finished');
});

or

terminal.exec(['command 1', 'command 2', 'command 3']).then(function() {
   terminal.echo('all commands finished');
});

the commands can run async code, and exec need to call user code in order. My first api use pair of pause/resume calls and in new API I call those automatic when user return promise. So user code can just use

return $.get('/some/url');

or

var d = new $.Deferred();
setTimeout(function() {
    d.resolve("Hello Deferred"); // resolve value will be echoed
}, 500);
return d.promise();

I use code like this:

exec: function(command, silent, deferred) {
    var d;
    if ($.isArray(command)) {
        return $.when.apply($, $.map(command, function(command) {
            return self.exec(command, silent);
        }));
    }
    // both commands executed here (resume will call Term::exec)
    if (paused) {
        // delay command multiple time
        d = deferred || new $.Deferred();
        dalyed_commands.push([command, silent, d]);
        return d.promise();
    } else {
        // commands may return promise from user code
        // it will resolve exec promise when user promise
        // is resolved
        var ret = commands(command, silent, true, deferred);
        if (!ret) {
            if (deferred) {
                deferred.resolve(self);
                return deferred.promise();
            } else {
                d = new $.Deferred();
                ret = d.promise();
                ret.resolve();
            }
        }
        return ret;
    }
},

dalyed_commands is used in resume function that call exec again with all dalyed_commands.

and part of the commands function (I've stripped not related parts)

function commands(command, silent, exec, deferred) {

    var position = lines.length-1;
    // Call user interpreter function
    var result = interpreter.interpreter(command, self);
    // user code can return a promise
    if (result != undefined) {
        // new API - auto pause/resume when using promises
        self.pause();
        return $.when(result).then(function(result) {
            // don't echo result if user echo something
            if (result && position === lines.length-1) {
                display_object(result);
            }
            // resolve promise from exec. This will fire
            // code if used terminal::exec('command').then
            if (deferred) {
                deferred.resolve();
            }
            self.resume();
        });
    }
    // this is old API
    // if command call pause - wait until resume
    if (paused) {
        self.bind('resume.command', function() {
            // exec with resume/pause in user code
            if (deferred) {
                deferred.resolve();
            }
            self.unbind('resume.command');
        });
    } else {
        // this should not happen
        if (deferred) {
            deferred.resolve();
        }
    }
}

Possible to iterate backwards through a foreach?

No. ForEach just iterates through collection for each item and order depends whether it uses IEnumerable or GetEnumerator().

How can I create tests in Android Studio?

As of now (studio 0.61) maintaining proper project structure is enough. No need to create separate test project as in eclipse (see below).

Tests structure

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

Check out this one:

https://github.com/VBA-tools/VBA-Web

It's a high level library for dealing with REST. It's OOP, works with JSON, but also works with any other format.

Post form data using HttpWebRequest

Try this:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/recepticle.aspx");

var postData = "thing1=hello";
    postData += "&thing2=world";
var data = Encoding.ASCII.GetBytes(postData);

request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;

using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

var response = (HttpWebResponse)request.GetResponse();

var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

What's the difference between equal?, eql?, ===, and ==?

I wrote a simple test for all the above.

def eq(a, b)
  puts "#{[a, '==',  b]} : #{a == b}"
  puts "#{[a, '===', b]} : #{a === b}"
  puts "#{[a, '.eql?', b]} : #{a.eql?(b)}"
  puts "#{[a, '.equal?', b]} : #{a.equal?(b)}"
end

eq("all", "all")
eq(:all, :all)
eq(Object.new, Object.new)
eq(3, 3)
eq(1, 1.0)

Can someone explain how to append an element to an array in C programming?

For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array.

But you can also use memcpy() function, to append element(s) of another array. You can use memcpy()like this:

#include <stdio.h>
#include <string.h>

int main(void)
{

int first_array[10] = {45, 2, 48, 3, 6};
int scnd_array[] = {8, 14, 69, 23, 5};

// 5 is the number of the elements which are going to be appended
memcpy(a + 5, b, 5 * sizeof(int));

// loop through and print all the array
for (i = 0; i < 10; i++) {
    printf("%d\n", a[i]);
  }

}

How to set environment variable for everyone under my linux system?

Using PAM is execellent.

# modify the display PAM
$ cat /etc/security/pam_env.conf 
# BEFORE: $ export DISPLAY=:0.0 && python /var/tmp/myproject/click.py &
# AFTER : $ python $abc/click.py &
DISPLAY  DEFAULT=${REMOTEHOST}:0.0 OVERRIDE=${DISPLAY}
abc   DEFAULT=/var/tmp/myproject

Error loading the SDK when Eclipse starts

In my case, I have the latest Android SDK and just have to remove/delete the Android Wear system images and it worked.

How to enter a multi-line command

I just found out that there must not be any character between the back tick and the line break. Even whitespace will cause the command to not work.

How to pass data from 2nd activity to 1st activity when pressed back? - android

and I Have an issue which I wanted to do this sending data type in a Soft Button which I'd made and the softKey which is the default in every Android Device, so I've done this, first I've made an Intent in my "A" Activity:

            Intent intent = new Intent();
            intent.setClass(context, _AddNewEmployee.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivityForResult(intent, 6969);
            setResult(60);

Then in my second Activity, I've declared a Field in my "B" Activity:

private static int resultCode = 40;

then after I made my request successfully or whenever I wanted to tell the "A" Activity that this job is successfully done here change the value of resultCode to the same I've said in "A" Activity which in my case is "60" and then:

private void backToSearchActivityAndRequest() {
    Intent data = new Intent();
    data.putExtra("PhoneNumber", employeePhoneNumber);
    setResult(resultCode, data);
    finish();
}

@Override
public void onBackPressed() {
    backToSearchActivityAndRequest();
}

PS: Remember to remove the Super from the onBackPressed Method if you want this to work properly.

then I should call the onActivityResult Method in my "A" Activity as well:

   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 6969 && resultCode == 60) {
            if (data != null) {
                    user_mobile = data.getStringExtra("PhoneNumber");
                    numberTextField.setText(user_mobile);
                    getEmployeeByNumber();
            }
        }
    }

that's it, hope it helps you out. #HappyCoding;

VBA collection: list of keys

You can create a small class to hold the key and value, and then store objects of that class in the collection.

Class KeyValue:

Public key As String
Public value As String
Public Sub Init(k As String, v As String)
    key = k
    value = v
End Sub

Then to use it:

Public Sub Test()
    Dim col As Collection, kv As KeyValue
    Set col = New Collection
    Store col, "first key", "first string"
    Store col, "second key", "second string"
    Store col, "third key", "third string"
    For Each kv In col
        Debug.Print kv.key, kv.value
    Next kv
End Sub

Private Sub Store(col As Collection, k As String, v As String)
    If (Contains(col, k)) Then
        Set kv = col(k)
        kv.value = v
    Else
        Set kv = New KeyValue
        kv.Init k, v
        col.Add kv, k
    End If
End Sub

Private Function Contains(col As Collection, key As String) As Boolean
    On Error GoTo NotFound
    Dim itm As Object
    Set itm = col(key)
    Contains = True
MyExit:
    Exit Function
NotFound:
    Contains = False
    Resume MyExit
End Function

This is of course similar to the Dictionary suggestion, except without any external dependencies. The class can be made more complex as needed if you want to store more information.

PHP server on local machine?

Install XAMPP. If you're running MS Windows, WAMP is also an option.

How to disable Google Chrome auto update?

TL;DR

Delete the folder C:\Program Files\Google\Update


Here is what I do to stop auto update of chrome. Since you want to disable auto update, you may be installing chrome using the offline installer. If not, then I recommend that you use that; it makes more sense for you anyway! Select the second option that says "Alternate installer for all user accounts", but you may also choose the other option. Anyway, this process should work for all kinds of installation of chrome.

  1. Install chrome and go to about page with the internet connected. This is to trigger the update process.

  2. Open task manager, go to Processes tab and look for the process named something like google updater. You may need to click on 'Show processes from all users' button if your uac is turned on

  3. Right-click on google updater process name and select open file location. Once location is opened in the explorer, end the process

  4. Delete the file corresponding to that ended process (by now it is located and selected in the explorer, as was done in step 3; for most this is C:\Program Files\Google\Update, but will be different if you had chosen to install for a single user)

  5. open Scheduled tasks (by typing sched... in start perhaps)

  6. Click on 'Task Scheduler Library` on the left and on the right side search for entries corresponding to google product updates. Disable or delete those tasks

You should be good to go! Auto update is not only disabled but killed forever.

P.S.: step 5 and 6 are simply for overkilling :-)

The located assembly's manifest definition does not match the assembly reference

I was getting:

Could not load file or assembly 'XXX-new' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

It was because I changed the name of the assembly from XXX.dll to XXX-new.dll. Reverting name back to the original fixed the error.

Deep copy vs Shallow Copy

Shallow copy:

Some members of the copy may reference the same objects as the original:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(copy.pi)
    { }
};

Here, the pi member of the original and copied X object will both point to the same int.


Deep copy:

All members of the original are cloned (recursively, if necessary). There are no shared objects:

class X
{
private:
    int i;
    int *pi;
public:
    X()
        : pi(new int)
    { }
    X(const X& copy)   // <-- copy ctor
        : i(copy.i), pi(new int(*copy.pi))  // <-- note this line in particular!
    { }
};

Here, the pi member of the original and copied X object will point to different int objects, but both of these have the same value.


The default copy constructor (which is automatically provided if you don't provide one yourself) creates only shallow copies.

Correction: Several comments below have correctly pointed out that it is wrong to say that the default copy constructor always performs a shallow copy (or a deep copy, for that matter). Whether a type's copy constructor creates a shallow copy, or deep copy, or something in-between the two, depends on the combination of each member's copy behaviour; a member's type's copy constructor can be made to do whatever it wants, after all.

Here's what section 12.8, paragraph 8 of the 1998 C++ standard says about the above code examples:

The implicitly defined copy constructor for class X performs a memberwise copy of its subobjects. [...] Each subobject is copied in the manner appropriate to its type: [...] [I]f the subobject is of scalar type, the builtin assignment operator is used.

Passing parameters to JavaScript files

Nice question and creative answers but my suggetion is to make your methods paramterized and that should solve all your problems without any tricks.

if you have function:

function A()
{
    var val = external_value_from_query_string_or_global_param;
}

you can change this to:

function B(function_param)
{
    var val = function_param;
}

I think this is most natural approach, you don't need to crate extra documentation about 'file parameters' and you receive the same. This specially useful if you allow other developers to use your js file.

What is Inversion of Control?

I agree with NilObject, but I'd like to add to this:

if you find yourself copying an entire method and only changing a small piece of the code, you can consider tackling it with inversion of control

If you find yourself copying and pasting code around, you're almost always doing something wrong. Codified as the design principle Once and Only Once.

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

CSS last-child(-1)

You can use :nth-last-child(); in fact, besides :nth-last-of-type() I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.

ul li:nth-last-child(2)

Print JSON parsed object?

Use string formats;

console.log("%s %O", "My Object", obj);

Chrome has Format Specifiers with the following;

  • %s Formats the value as a string.
  • %d or %i Formats the value as an integer.
  • %f Formats the value as a floating point value.
  • %o Formats the value as an expandable DOM element (as in the Elements panel).
  • %O Formats the value as an expandable JavaScript object.
  • %c Formats the output string according to CSS styles you provide.

Firefox also has String Substitions which have similar options.

  • %o Outputs a hyperlink to a JavaScript object. Clicking the link opens an inspector.
  • %d or %i Outputs an integer. Formatting is not yet supported.
  • %s Outputs a string.
  • %f Outputs a floating-point value. Formatting is not yet supported.

Safari has printf style formatters

  • %d or %i Integer
  • %[0.N]f Floating-point value with N digits of precision
  • %o Object
  • %s String

Latex - Change margins of only a few pages

I could not find a easy way to set the margin for a single page.

My solution was to use vspace with the number of centimeters of empty space I wanted:

 \vspace*{5cm}                                                             

I put this command at the beginning of the pages that I wanted to have +5cm of margin.

How do I mock an open used in a with statement (using the Mock framework in Python)?

If you don't need any file further, you can decorate the test method:

@patch('builtins.open', mock_open(read_data="data"))
def test_testme():
    result = testeme()
    assert result == "data"

Tried to Load Angular More Than Once

I was also facing such an issue where I was continously getting an infinite loop and the page was reloading itself infinitely. After a bit of debugging I found out that the error was being caused because, angular was not able to load template given with a particular id because the template was not present in that file.

Be careful with the url's which you give in angular apps. If its not correct, angular can just keep on looking for it eventually, leading to infinite loop!

Hope this helps!

Return a value if no rows are found in Microsoft tSQL

This might be a dead horse, another way to return 1 row when no rows exist is to UNION another query and display results when non exist in the table.

SELECT S.Status, COUNT(s.id) AS StatusCount
FROM Sites S
WHERE S.Id = @SiteId
GROUP BY s.Status
UNION ALL --UNION BACK ON TABLE WITH NOT EXISTS
SELECT 'N/A' AS Status, 0 AS StatusCount
WHERE NOT EXISTS (SELECT 1
   FROM Sites S
   WHERE S.Id = @SiteId
) 

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

If you are using XAMPP rather than WAMP, the path you go to is:

C:\xampp\phpMyAdmin\config.inc.php

How do I change the font-size of an <option> element within <select>?

Like most form controls in HTML, the results of applying CSS to <select> and <option> elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option> element directly --- if you do Inspect Element on it, you'll see the font-size: 14px declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.

However, Chrome will let you apply font styles to the <optgroup> element, so to achieve the result you want you can wrap all the <option>s in an <optgroup> and then apply your font styles to a .styled-select optgroup selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.

Forked to a new JSFiddle to show you what I mean:

http://jsfiddle.net/zRtbZ/

clk'event vs rising_edge()

rising_edge is defined as:

FUNCTION rising_edge  (SIGNAL s : std_ulogic) RETURN BOOLEAN IS
BEGIN
    RETURN (s'EVENT AND (To_X01(s) = '1') AND
                        (To_X01(s'LAST_VALUE) = '0'));
END;

FUNCTION To_X01  ( s : std_ulogic ) RETURN  X01 IS
BEGIN
    RETURN (cvt_to_x01(s));
END;

CONSTANT cvt_to_x01 : logic_x01_table := (
                     'X',  -- 'U'
                     'X',  -- 'X'
                     '0',  -- '0'
                     '1',  -- '1'
                     'X',  -- 'Z'
                     'X',  -- 'W'
                     '0',  -- 'L'
                     '1',  -- 'H'
                     'X'   -- '-'
                    );

If your clock only goes from 0 to 1, and from 1 to 0, then rising_edge will produce identical code. Otherwise, you can interpret the difference.

Personally, my clocks only go from 0 to 1 and vice versa. I find rising_edge(clk) to be more descriptive than the (clk'event and clk = '1') variant.

Visual studio equivalent of java System.out

Or, if you want to see output in the Output window of Visual Studio, System.Diagnostics.Debug.WriteLine(stuff)

Get current date, given a timezone in PHP?

If you have access to PHP 5.3, the intl extension is very nice for doing things like this.

Here's an example from the manual:

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
    'America/Los_Angeles',IntlDateFormatter::GREGORIAN  );
$fmt->format(0); //0 for current time/date

In your case, you can do:

$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
        'America/New_York');
 $fmt->format($datetime); //where $datetime may be a DateTime object, an integer representing a Unix timestamp value (seconds since epoch, UTC) or an array in the format output by localtime(). 

As you can set a Timezone such as America/New_York, this is much better than using a GMT or UTC offset, as this takes into account the day light savings periods as well.

Finaly, as the intl extension uses ICU data, which contains a lot of very useful features when it comes to creating your own date/time formats.

Find which rows have different values for a given column in Teradata SQL

Join the table with itself and give it two different aliases (A and B in the following example). This allows to compare different rows of the same table.

SELECT DISTINCT A.Id
FROM
    Address A
    INNER JOIN Address B
        ON A.Id = B.Id AND A.[Adress Code] < B.[Adress Code]
WHERE
    A.Address <> B.Address

The "less than" comparison < ensures that you get 2 different addresses and you don't get the same 2 address codes twice. Using "not equal" <> instead, would yield the codes as (1, 2) and (2, 1); each one of them for the A alias and the B alias in turn.

The join clause is responsible for the pairing of the rows where as the where-clause tests additional conditions.


The query above works with any address codes. If you want to compare addresses with specific address codes, you can change the query to

SELECT A.Id
FROM
    Address A
    INNER JOIN Address B
        ON A.Id = B.Id
WHERE                     
    A.[Adress Code] = 1 AND
    B.[Adress Code] = 2 AND
    A.Address <> B.Address

I imagine that this might be useful to find customers having a billing address (Adress Code = 1 as an example) differing from the delivery address (Adress Code = 2) .

Eliminating duplicate values based on only one column of the table

From your example it seems reasonable to assume that the siteIP column is determined by the siteName column (that is, each site has only one siteIP). If this is indeed the case, then there is a simple solution using group by:

select
  sites.siteName,
  sites.siteIP,
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName,
  sites.siteIP
order by
  sites.siteName;

However, if my assumption is not correct (that is, it is possible for a site to have multiple siteIP), then it is not clear from you question which siteIP you want the query to return in the second column. If just any siteIP, then the following query will do:

select
  sites.siteName,
  min(sites.siteIP),
  max(history.date)
from sites
inner join history on
  sites.siteName=history.siteName
group by
  sites.siteName
order by
  sites.siteName;

Absolute positioning ignoring padding of parent

Well, this may not be the most elegant solution (semantically), but in some cases it'll work without any drawbacks: Instead of padding, use a transparent border on the parent element. The absolute positioned child elements will honor the border and it'll be rendered exactly the same (except you're using the border of the parent element for styling).

How to add default value for html <textarea>?

Here is my jsFiddle example. this works fine:

<textarea name='awesome'>Default value</textarea>

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

I got a similar error with '/' operand while processing images. I discovered the folder included a text file created by the 'XnView' image viewer. So, this kind of error occurs when some object is not the kind of object expected.

How to customize an end time for a YouTube video?

Use parameters(seconds) i.e. youtube.com/v/VIDEO_ID?start=4&end=117

Live DEMO:
https://puvox.software/software/youtube_trimmer.php

wp-admin shows blank page, how to fix it?

My case was that I had generated code for three custom content types and then just pasted all the code in functions.php without renaming the "function custom_post_type" part of each function. After renaming like e.g "function employees", it worked like a charm....it displayed.

Windows service on Local Computer started and then stopped error

Meanwhile, another reason : accidentally deleted the .config file caused the same error message appears:

"Service on local computer started and then stopped. some services stop automatically..."

How to initialize std::vector from C-style array?

std::vector<double>::assign is the way to go, because it's little code. But how does it work, actually? Doesnt't it resize and then copy? In MS implementation of STL I am using it does exactly so.

I'm afraid there's no faster way to implement (re)initializing your std::vector.

How to properly URL encode a string in PHP?

For the URI query use urlencode/urldecode; for anything else use rawurlencode/rawurldecode.

The difference between urlencode and rawurlencode is that

Is it possible to use global variables in Rust?

I am new to Rust, but this solution seems to work:

#[macro_use]
extern crate lazy_static;

use std::sync::{Arc, Mutex};

lazy_static! {
    static ref GLOBAL: Arc<Mutex<GlobalType> =
        Arc::new(Mutex::new(GlobalType::new()));
}

Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.

Both solutions should provide a safe approach to using global variables.

Can't connect to local MySQL server through socket '/tmp/mysql.sock

I think i saw this same behavior some time ago, but can't remember the details.
In our case, the problem was the moment the testrunner initialises database connections relative to first database interaction required, for instance, by import of a module in settings.py or some __init__.py. I'll try to digg up some more info, but this might already ring a bell for your case.

How to setup Main class in manifest file in jar produced by NetBeans project

Brother you don't need to set class path just follow these simple steps (I use Apache NetBeans)

Steps:

  1. extract the jar file which you want to add in your project.

  2. only copy those packages (folder) which you need in the project. (do not copy manifest file)

  3. open the main project jar file(dist/file.jar) with WinRAR.

  4. paste that folder or package in the main project jar file.

  5. Those packages work 100% in your project.

warning: Do not make any changes in the manifest file.

Another method:

  • In my case lib folder present outside the dist(main jar file) folder.
  • we need to move lib folder in dist folder.then we set class path from manifest.mf file of main jar file.

    Edit the manifest.mf And ADD this type of line

  • Class-Path: lib\foldername\jarfilename.jar lib\foldername\jarfilename.jar

Warning: lib folder must be inside the dist folder otherwise jar file do not access your lib folder jar files

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

Image is not showing in browser?

all you need to do is right click on the jsp page in the browser, which might look like "localhost:8080/images.jpg, copy this and paste it where the image is getting generated

AngularJS routing without the hash '#'

The following information is from:
https://scotch.io/quick-tips/pretty-urls-in-angularjs-removing-the-hashtag

It is very easy to get clean URLs and remove the hashtag from the URL in Angular.
By default, AngularJS will route URLs with a hashtag For Example:

There are 2 things that need to be done.

  • Configuring $locationProvider

  • Setting our base for relative links

  • $location Service

In Angular, the $location service parses the URL in the address bar and makes changes to your application and vice versa.

I would highly recommend reading through the official Angular $location docs to get a feel for the location service and what it provides.

https://docs.angularjs.org/api/ng/service/$location

$locationProvider and html5Mode

  • We will use the $locationProvider module and set html5Mode to true.
  • We will do this when defining your Angular application and configuring your routes.

    angular.module('noHash', [])
    
    .config(function($routeProvider, $locationProvider) {
    
       $routeProvider
           .when('/', {
               templateUrl : 'partials/home.html',
               controller : mainController
           })
           .when('/about', {
               templateUrl : 'partials/about.html',
               controller : mainController
           })
           .when('/contact', {
               templateUrl : 'partials/contact.html',
               controller : mainController
           });
    
       // use the HTML5 History API
       $locationProvider.html5Mode(true); });
    

What is the HTML5 History API? It is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page. For more information on this, here is a good HTML5 History API Article:

http://diveintohtml5.info/history.html

Setting For Relative Links

  • To link around your application using relative links, you will need to set the <base> in the <head> of your document. This may be in the root index.html file of your Angular app. Find the <base> tag, and set it to the root URL you'd like for your app.

For example: <base href="/">

  • There are plenty of other ways to configure this, and the HTML5 mode set to true should automatically resolve relative links. If your root of your application is different than the url (for instance /my-base, then use that as your base.

Fallback for Older Browsers

  • The $location service will automatically fallback to the hashbang method for browsers that do not support the HTML5 History API.
  • This happens transparently to you and you won’t have to configure anything for it to work. From the Angular $location docs, you can see the fallback method and how it works.

In Conclusion

  • This is a simple way to get pretty URLs and remove the hashtag in your Angular application. Have fun making those super clean and super fast Angular apps!

how do you view macro code in access?

Open the Access Database, you will see Table, Query, Report, Module & Macro.
This contains the macros which can be used to invoke common MS-Access actions in a sequence.

For custom VBA macro, press ALT+F11.

Enable binary mode while restoring a Database from an SQL dump

I meet the same problem in windows restoring a dump file. My dump file was created with windows powershell and mysqldump like:

mysqldump db > dump.sql

The problem comes from the default encoding of powershell is UTF16. To look deeper into this, we can use "file" utility of GNU, and there exists a windows version here.
The output of my dump file is:

Little-endian UTF-16 Unicode text, with very long lines, with CRLF line terminators.

Then a conversion of coding system is needed, and there are various software can do this. For example in emacs,

M-x set-buffer-file-coding-system

then input required coding system such as utf-8.

And in the future, for a better mysqldump result, use:

mysqldump <dbname> -r <filename>

and then the output is handled by mysqldump itself but not redirection of powershell.

reference: https://dba.stackexchange.com/questions/44721/error-while-restoring-a-database-from-an-sql-dump

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

CURL Command Line URL Parameters

Felipsmartins is correct.

It is worth mentioning that it is because you cannot really use the -d/--data option if this is not a POST request. But this is still possible if you use the -G option.

Which means you can do this:

curl -X DELETE -G 'http://localhost:5000/locations' -d 'id=3'

Here it is a bit silly but when you are on the command line and you have a lot of parameters, it is a lot tidier.

I am saying this because cURL commands are usually quite long, so it is worth making it on more than one line escaping the line breaks.

curl -X DELETE -G \
'http://localhost:5000/locations' \
-d id=3 \
-d name=Mario \
-d surname=Bros

This is obviously a lot more comfortable if you use zsh. I mean when you need to re-edit the previous command because zsh lets you go line by line. (just saying)

Hope it helps.

Trigger event on body load complete js/jquery

When the page loads totally (dom, images, ...)

$(window).load(function(){
    // full load
});

When DOM elements load (not necessary all images will be loaded)

$(function(){
    // DOM Ready
});

Then you can trigger any event

$("element").trigger("event");

Changing date format in R

This is really easy using package lubridate. All you have to do is tell R what format your date is already in. It then converts it into the standard format

nzd$date <- dmy(nzd$date)

that's it.

.htaccess or .htpasswd equivalent on IIS?

This is the documentation that you want: http://msdn.microsoft.com/en-us/library/aa292114(VS.71).aspx

I guess the answer is, yes, there is an equivalent that will accomplish the same thing, integrated with Windows security.

SQL Server - In clause with a declared variable

You need to execute this as a dynamic sp like

DECLARE @ExcludedList VARCHAR(MAX)

SET @ExcludedList = '3,4,22,6014'
declare @sql nvarchar(Max)

Set @sql='SELECT * FROM [A] WHERE Id NOT IN ('+@ExcludedList+')'

exec sp_executesql @sql

Drawing Isometric game worlds

If you have some tiles that exceed the bounds of your diamond, I recommend drawing in depth order:

...1...
..234..
.56789.
..abc..
...d...

How to use placeholder as default value in select2 framework

$("#e2").select2({
   placeholder: "Select a State",
   allowClear: true
});
$("#e2_2").select2({
   placeholder: "Select a State"
});

The placeholder can be declared via a data-placeholder attribute attached to the select, or via the placeholder configuration element as seen in the example code.

When placeholder is used for a non-multi-value select box, it requires that you include an empty tag as your first option.

Optionally, a clear button (visible once a selection is made) is available to reset the select box back to the placeholder value.

https://select2.org/placeholders

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

Read Excel sheet in Powershell

Sorry I know this is an old one but still felt like helping out ^_^

Maybe it's the way I read this but assuming the excel sheet 1 is called "London" and has this information; B5="Marleybone" B6="Paddington" B7="Victoria" B8="Hammersmith". And the excel sheet 2 is called "Nottingham" and has this information; C5="Alverton" C6="Annesley" C7="Arnold" C8="Askham". Then I think this code below would work. ^_^

$xlCellTypeLastCell = 11 
$startRow = 5

$excel = new-object -com excel.application
$wb = $excel.workbooks.open("C:\users\administrator\my_test.xls")

for ($i = 1; $i -le $wb.sheets.count; $i++)
    {
        $sh = $wb.Sheets.Item($i)
        $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
        $col = $col + $i - 1
        $city = $wb.Sheets.Item($i).name
        $rangeAddress = $sh.Cells.Item($startRow, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
        $sh.Range($rangeAddress).Value2 | foreach{
            New-Object PSObject -Property @{City = $city; Area=$_}
        }
    }

$excel.Workbooks.Close()

This should be the output (without the commas):

City, Area
---- ----
London, Marleybone
London, Paddington
London, Victoria
London, Hammersmith
Nottingham, Alverton
Nottingham, Annesley
Nottingham, Arnold
Nottingham, Askham

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Using either a float or a double value in a C expression will result in a value that is a double anyway, so printf can't tell the difference. Whereas a pointer to a double has to be explicitly signalled to scanf as distinct from a pointer to float, because what the pointer points to is what matters.

Regex (grep) for multi-line search needed

Without the need to install the grep variant pcregrep, you can do multiline search with grep.

$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c

Explanation:

-P activate perl-regexp for grep (a powerful extension of regular expressions)

-z suppress newline at the end of line, substituting it for null character. That is, grep knows where end of line is, but sees the input as one big line.

-o print only matching. Because we're using -z, the whole file is like a single big line, so if there is a match, the entire file would be printed; this way it won't do that.

In regexp:

(?s) activate PCRE_DOTALL, which means that . finds any character or newline

\N find anything except newline, even with PCRE_DOTALL activated

.*? find . in non-greedy mode, that is, stops as soon as possible.

^ find start of line

\1 backreference to the first group (\s*). This is a try to find the same indentation of method.

As you can imagine, this search prints the main method in a C (*.c) source file.

Rounding a double value to x number of decimal places in swift

Here's one for SwiftUI if you need a Text element with the number value.

struct RoundedDigitText : View {
    let digits : Int
    let number : Double

    var body : some View {
        Text(String(format: "%.\(digits)f", number))
    }
}

Find and Replace Inside a Text File from a Bash Command

You may also use the ed command to do in-file search and replace:

# delete all lines matching foobar 
ed -s test.txt <<< $'g/foobar/d\nw' 

See more in "Editing files via scripts with ed".

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

I got the same error in Chrome console.

My problem was, I was trying to go to the site using http:// instead of https://. So there was nothing to fix, just had to go to the same site using https.

How to import large sql file in phpmyadmin

Edit the config.inc.php file located in the phpmyadmin directory. In my case it is located at C:\wamp\apps\phpmyadmin3.2.0.1\config.inc.php.

Find the line with $cfg['UploadDir'] on it and update it to $cfg['UploadDir'] = 'upload';

Then, create a directory called ‘upload’ within the phpmyadmin directory (for me, at C:\wamp\apps\phpmyadmin3.2.0.1\upload\).

Then place the large SQL file that you are trying to import into the new upload directory. Now when you go onto the db import page within phpmyadmin console you will notice a drop down present that wasn’t there before – it contains all of the sql files in the upload directory that you have just created. You can now select this and begin the import.

If you’re not using WAMP on Windows, then I’m sure you’ll be able to adapt this to your environment without too much trouble.

Reference : http://daipratt.co.uk/importing-large-files-into-mysql-with-phpmyadmin/comment-page-4/

PHP - Copy image to my server direct from URL

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);

you must have allow_url_fopen set to on

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

You need to use passive mode.

If you're using linux client, use pftp or ftp -p.

From man ftp:

-p    Use passive mode for data transfers. Allows use of ftp in environments where a firewall prevents connections from the outside world back to the client machine. Requires that the ftp server support the PASV command. This is the default if invoked as pftp.

Java Refuses to Start - Could not reserve enough space for object heap

In Windows, I solved this problem editing directly the file /bin/cassandra.bat, changing the value of the "Xms" and "Xmx" JVM_OPTS parameters. You can try to edit the /bin/cassandra file. In this file I see an commented variable JVM_OPTS, try to uncomment and edit it.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

I am Using Design Support Library. And just by using custom theme I achived transparent Status Bar when Opened Navigation Drawer.

enter image description here

enter image description here

<style name="NavigationStyle" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryDark">@color/primaryColorDark</item>

    <!-- To Make Navigation Drawer Fill Status Bar and become Transparent Too -->
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>

</style>

Finally add theme in Manifest File

<activity
  ........
  ........
 android:theme="@style/NavigationStyle"> 
</activity>

Do not forget to use the property, android:fitsSystemWindows="true" in "DrawerLayout"

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

What you're checking

if(isset($_POST['submit']))

but there's no variable name called "submit". well i want you to understand why it doesn't works. lets imagine if you give your submit button name delete <input type="submit" value="Submit" name="delete" /> and check if(isset($_POST['delete'])) then it works in this code you didn't give any name to submit button and checking its exist or not with isset(); function so php didn't find any variable like "submit" so its not working now try this :

<input type="submit" name="submit" value="Submit" />

How can I get a precise time, for example in milliseconds in Objective-C?

You can get current time in milliseconds since January 1st, 1970 using an NSDate:

- (double)currentTimeInMilliseconds {
    NSDate *date = [NSDate date];
    return [date timeIntervalSince1970]*1000;
}

VBA using ubound on a multidimensional array

Looping D3 ways;

Sub SearchArray()
    Dim arr(3, 2) As Variant
    arr(0, 0) = "A"
    arr(0, 1) = "1"
    arr(0, 2) = "w"

    arr(1, 0) = "B"
    arr(1, 1) = "2"
    arr(1, 2) = "x"

    arr(2, 0) = "C"
    arr(2, 1) = "3"
    arr(2, 2) = "y"

    arr(3, 0) = "D"
    arr(3, 1) = "4"
    arr(3, 2) = "z"

    Debug.Print "Loop Dimension 1"
    For i = 0 To UBound(arr, 1)
        Debug.Print "arr(" & i & ", 0) is " & arr(i, 0)
    Next i
    Debug.Print ""

    Debug.Print "Loop Dimension 2"
    For j = 0 To UBound(arr, 2)
        Debug.Print "arr(0, " & j & ") is " & arr(0, j)
    Next j
    Debug.Print ""

    Debug.Print "Loop Dimension 1 and 2"
    For i = 0 To UBound(arr, 1)
        For j = 0 To UBound(arr, 2)
            Debug.Print "arr(" & i & ", " & j & ") is " & arr(i, j)
        Next j
    Next i
    Debug.Print ""

End Sub

Check an integer value is Null in c#

There is already a correct answer from Adam, but you have another option to refactor your code:

if (Age.GetValueOrDefault() == 0)
{
    // it's null or 0
}

Fit cell width to content

I'm not sure if I understand your question, but I'll take a stab at it:

_x000D_
_x000D_
td {
    border: 1px solid #000;
}

tr td:last-child {
    width: 1%;
    white-space: nowrap;
}
_x000D_
<table style="width: 100%;">
    <tr>
        <td class="block">this should stretch</td>
        <td class="block">this should stretch</td>
        <td class="block">this should be the content width</td>
    </tr>
</table>
_x000D_
_x000D_
_x000D_

AngularJS ngClass conditional

use this

<div ng-class="{states}[condition]"></div>

for example if the condition is [2 == 2], states are {true: '...', false: '...'}

<div ng-class="{true: 'ClassA', false: 'ClassB'}[condition]"></div>

How to get C# Enum description from value?

I put the code together from the accepted answer in a generic extension method, so it could be used for all kinds of objects:

public static string DescriptionAttr<T>(this T source)
{
    FieldInfo fi = source.GetType().GetField(source.ToString());

    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(
        typeof(DescriptionAttribute), false);

    if (attributes != null && attributes.Length > 0) return attributes[0].Description;
    else return source.ToString();
}

Using an enum like in the original post, or any other class whose property is decorated with the Description attribute, the code can be consumed like this:

string enumDesc = MyEnum.HereIsAnother.DescriptionAttr();
string classDesc = myInstance.SomeProperty.DescriptionAttr();

to remove first and last element in array

Say you have array named list. The Splice() function can be used for both adding and removing item in that array in specific index i.e that can be in the beginning or in the end or at any index. On the contrary there are another function name shift() and pop() which is capable of removing only the first and last item in the array.

This is the Shift Function which is only capable of removing the first element of the array

var item = [ 1,1,2,3,5,8,13,21,34 ]; // say you have this number series 
item.shift(); // [ 1,2,3,5,8,13,21,34 ];

The Pop Function removes item from an array at its last index

item.pop(); // [ 1,2,3,5,8,13,21 ];

Now comes the splice function by which you can remove item at any index

item.slice(0,1); // [ 2,3,5,8,13,21 ] removes the first object
item.slice(item.length-1,1); // [ 2,3,5,8,13 ] removes the last object 

The slice function accepts two parameters (Index to start with, number of steps to go);

Make the current commit the only (initial) commit in a Git repository?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D master

  5. Rename the current branch to master

    git branch -m master

  6. Finally, force update your repository

    git push -f origin master

PS: this will not keep your old commit history around

Hive ParseException - cannot recognize input near 'end' 'string'

I solved this issue by doing like that:

insert into my_table(my_field_0, ..., my_field_n) values(my_value_0, ..., my_value_n)

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

In Swift how to call method with parameters on GCD main thread?

Reload collectionView on Main Thread

DispatchQueue.main.async {
    self.collectionView.reloadData()
}

Prevent text selection after double click

For those looking for a solution for Angular 2+.

You can use the mousedown output of the table cell.

<td *ngFor="..."
    (mousedown)="onMouseDown($event)"
    (dblclick) ="onDblClick($event)">
  ...
</td>

And prevent if the detail > 1.

public onMouseDown(mouseEvent: MouseEvent) {
  // prevent text selection for dbl clicks.
  if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}

public onDblClick(mouseEvent: MouseEvent) {
 // todo: do what you really want to do ...
}

The dblclick output continues to work as expected.

How do I start/stop IIS Express Server?

I came across the same issue. My aim is to test PHP scripts with Oracle on Windows 7 Home and without thinking installed IIS7 express and as an afterthought considered Apache as a simpler approach. I will explore IIS express's capabilities seperately.

The challenge was after installing IIS7 express the Apache installation was playing second fiddle to IIS express and bringing up the Microsoft Homepage.

I resolved the port 80 issue by :-

  1. Stopping Microsoft WedMatrix :- net stop was /y
  2. Restarted the Apache Server
  3. Verifying Apache now was listening on the port :- netstat -anop
  4. Clearing out the Browsers caches - Firefox and IE
  5. Running localhost

Apache and IIS side by side (both listening to port 80) on windows2003

Either two different IP addresses (like recommended) or one web server is reverse-proxying the other (which is listening on a port <>80).

For instance: Apache listens on port 80, IIS on port 8080. Every http request goes to Apache first (of course). You can then decide to forward every request to a particular (named virtual) domain or every request that contains a particular directory (e.g. http://www.example.com/winapp/) to the IIS.

Advantage of this concept is that you have only one server listening to the public instead of two, you are more flexible as with two distinct servers.

Drawbacks: some webapps are crappily designed and a real pain in the ass to integrate into a reverse-proxy infrastructure. A working IIS webapp is dependent on a working Apache, so we have some inter-dependencies.

NGinx Default public www location?

'default public web root' can be found from nginx -V output:

nginx -V
nginx version: nginx/1.10.1
built with OpenSSL 1.0.2h  3 May 2016
TLS SNI support enabled
configure arguments: --prefix=/var/lib/nginx --sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --pid-path=/run/nginx/nginx.pid --lock-path=/run/nginx/nginx.lock --http-client-body-temp-path=/var/lib/nginx/tmp/client_body --http-proxy-temp-path=/var/lib/nginx/tmp/proxy --http-fastcgi-temp-path=/var/lib/nginx/tmp/fastcgi --http-uwsgi-temp-path=/var/lib/nginx/tmp/uwsgi --http-scgi-temp-path=/var/lib/nginx/tmp/scgi --user=nginx --group=nginx --with-ipv6 --with-file-aio --with-pcre-jit --with-http_dav_module --with-http_ssl_module --with-http_stub_status_module --with-http_gzip_static_module --with-http_v2_module --with-http_auth_request_module --with-mail --with-mail_ssl_module

the --prefix value is the answer to the question. for the sample above the root is /var/lib/nginx

Reading CSV file and storing values into an array

LINQ way:

var lines = File.ReadAllLines("test.txt").Select(a => a.Split(';'));
var csv = from line in lines
          select (from piece in line
                  select piece);

^^Wrong - Edit by Nick

It appears the original answerer was attempting to populate csv with a 2 dimensional array - an array containing arrays. Each item in the first array contains an array representing that line number with each item in the nested array containing the data for that specific column.

var csv = from line in lines
          select (line.Split(',')).ToArray();

Delete from two tables in one query

You should either create a FOREIGN KEY with ON DELETE CASCADE:

ALTER TABLE usersmessages
ADD CONSTRAINT fk_usermessages_messageid
FOREIGN KEY (messageid)
REFERENCES messages (messageid)
ON DELETE CASCADE

, or do it using two queries in a transaction:

START TRANSACTION;;

DELETE
FROM    usermessages
WHERE   messageid = 1

DELETE
FROM    messages
WHERE   messageid = 1;

COMMIT;

Transaction affects only InnoDB tables, though.

SQL query to select distinct row with minimum value

Ken Clark's answer didn't work in my case. It might not work in yours either. If not, try this:

SELECT * 
from table T

INNER JOIN
  (
  select id, MIN(point) MinPoint
  from table T
  group by AccountId
  ) NewT on T.id = NewT.id and T.point = NewT.MinPoint

ORDER BY game desc

Random number generator only generating one random number

My answer from here:

Just reiterating the right solution:

namespace mySpace
{
    public static class Util
    {
        private static rnd = new Random();
        public static int GetRandom()
        {
            return rnd.Next();
        }
    }
}

So you can call:

var i = Util.GetRandom();

all throughout.

If you strictly need a true stateless static method to generate random numbers, you can rely on a Guid.

public static class Util
{
    public static int GetRandom()
    {
        return Guid.NewGuid().GetHashCode();
    }
}

It's going to be a wee bit slower, but can be much more random than Random.Next, at least from my experience.

But not:

new Random(Guid.NewGuid().GetHashCode()).Next();

The unnecessary object creation is going to make it slower especially under a loop.

And never:

new Random().Next();

Not only it's slower (inside a loop), its randomness is... well not really good according to me..

setHintTextColor() in EditText

Seems that EditText apply the hintTextColor only if the text is empty. So simple solution will be like this

Editable text = mEditText.getText();
mEditText.setText(null);
mEditText.setHintTextColor(color);
mEditText.setText(text);

If you have multiple fields, you can extend the EditText and write a method which executes this logic and use that method instead.

Set margins in a LinearLayout programmatically

Here a single line Solution:

((LinearLayout.LayoutParams) yourLinearLayout.getLayoutParams()).marginToAdd = ((int)(Resources.getSystem().getDisplayMetrics().density * yourDPValue));

How to drop a PostgreSQL database if there are active connections to it?

In PostgreSQL 9.2 and above, to disconnect everything except your session from the database you are connected to:

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()
  AND pid <> pg_backend_pid();

In older versions it's the same, just change pid to procpid. To disconnect from a different database just change current_database() to the name of the database you want to disconnect users from.

You may want to REVOKE the CONNECT right from users of the database before disconnecting users, otherwise users will just keep on reconnecting and you'll never get the chance to drop the DB. See this comment and the question it's associated with, How do I detach all other users from the database.

If you just want to disconnect idle users, see this question.

Is it good practice to use the xor operator for boolean checks?

I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.

If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

What is time(NULL) in C?

You can pass in a pointer to a time_t object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL, it just ignores it and merely returns a new time_t object that represents the current time.

How to read HDF5 files in Python

from keras.models import load_model 

h= load_model('FILE_NAME.h5')

How can I add JAR files to the web-inf/lib folder in Eclipse?

Found a solution. This problem happens, when you import a project.

The solution is simple

  1. Right click -> Properties
  2. Project Facets -> Check Dyanmic Web Module and Java Version
  3. Apply Setting.

Now you should see the web app libraries showing your jars added.

Rebuild all indexes in a Database

Daniel's script appears to be a good all encompassing solution, but even he admitted that his laptop ran out of memory. Here is an option I came up with. I based my procedure off of Mohammad Nizamuddin's post on TechNet. I added an initial cursor loop that pulls all the database names into a temporary table and then uses that to pull all the base table names from each of those databases.

You can optionally pass the fill factor you would prefer and specify a target database if you do not want to re-index all databases.


--===============================================================
-- Name:  sp_RebuildAllIndexes
-- Arguements:  [Fill Factor], [Target Database name]
-- Purpose:  Loop through all the databases on a server and
--           compile a list of all the table within them.
--           This list is then used to rebuild indexes for
--           all the tables in all the database.  Optionally,
--           you may pass a specific database name if you only
--           want to reindex that target database.
--================================================================
CREATE PROCEDURE sp_RebuildAllIndexes(
    @FillFactor     INT = 90,
    @TargetDatabase NVARCHAR(100) = NULL)
AS
    BEGIN
        DECLARE @TablesToReIndex TABLE (
            TableName VARCHAR(200)
        );
        DECLARE @DbName VARCHAR(50);
        DECLARE @TableSelect VARCHAR(MAX);
        DECLARE @DatabasesToIndex CURSOR;

        IF ISNULL( @TargetDatabase, '' ) = ''
          SET @DatabasesToIndex = CURSOR
          FOR SELECT NAME
              FROM   master..sysdatabases
        ELSE
          SET @DatabasesToIndex = CURSOR
          FOR SELECT NAME
              FROM   master..sysdatabases
              WHERE  NAME = @TargetDatabase

        OPEN DatabasesToIndex

        FETCH NEXT FROM DatabasesToIndex INTO @DbName

        WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @TableSelect = 'INSERT INTO @TablesToReIndex SELECT CONCAT(TABLE_CATALOG, ''.'', TABLE_SCHEMA, ''.'', TABLE_NAME) AS TableName FROM '
                                   + @DbName
                                   + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''base table''';

                EXEC sp_executesql
                    @TableSelect;

                FETCH NEXT FROM DatabasesToIndex INTO @DbName
            END

        CLOSE DatabasesToIndex

        DEALLOCATE DatabasesToIndex

        DECLARE @TableName VARCHAR(255)
        DECLARE TableCursor CURSOR FOR
            SELECT TableName
            FROM   @TablesToReIndex

        OPEN TableCursor

        FETCH NEXT FROM TableCursor INTO @TableName

        WHILE @@FETCH_STATUS = 0
            BEGIN
                DBCC DBREINDEX(@TableName, ' ', @FillFactor)

                FETCH NEXT FROM TableCursor INTO @TableName
            END

        CLOSE TableCursor

        DEALLOCATE TableCursor
    END 

Angularjs checkbox checked by default on load and disables Select list when checked

If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.

http://jsfiddle.net/UTULc/

<div ng-app="">
  Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
  <select id="transferTo" ng-disabled="checked">
    <option>Tech1</option>
    <option>Tech2</option>
  </select>
</div>

Load local javascript file in chrome for testing?

Here's what I did by creating 2 files in the /sandbox directory:

  • First file: sandbox.js
  • Second file: index.html

_x000D_
_x000D_
const name = 'Karl'_x000D_
_x000D_
console.log('This is the name: ' + name)
_x000D_
<html>_x000D_
  <head>_x000D_
    <script type = "text/javascript" src = "file:///Users/karl/Downloads/sandbox/sandbox.js"></script>_x000D_
  </head>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can then use Chrome or any browser to inspect and debug/console your code!

Access item in a list of lists

for l in list1:
    val = 50 - l[0] + l[1] - l[2]
    print "val:", val

Loop through list and do operation on the sublist as you wanted.

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

background-size in shorthand background property (CSS3)

You will have to use vendor prefixes to support different browsers and therefore can't use it in shorthand.

body { 
        background: url(images/bg.jpg) no-repeat center center fixed; 
        -webkit-background-size: cover;
        -moz-background-size: cover;
        -o-background-size: cover;
        background-size: cover;
}

How to export a CSV to Excel using Powershell

If you want to convert CSV to Excel without Excel being installed, you can use the great .NET library EPPlus (under LGPL license) to create and modify Excel Sheets and also convert CSV to Excel really fast!

Preparation

  1. Download the latest stable EPPlus version
  2. Extract EPPlus to your preferred location (e.g. to $HOME\Documents\WindowsPowerShell\Modules\EPPlus)
  3. Right Click EPPlus.dll, select Properties and at the bottom of the General Tab click "Unblock" to allow loading of this dll. If you don't have the rights to do this, try [Reflection.Assembly]::UnsafeLoadFrom($DLLPath) | Out-Null

Detailed Powershell Commands to import CSV to Excel

# Create temporary CSV and Excel file names
$FileNameCSV = "$HOME\Downloads\test.csv"
$FileNameExcel = "$HOME\Downloads\test.xlsx"

# Create CSV File (with first line containing type information and empty last line)
Get-Process | Export-Csv -Delimiter ';' -Encoding UTF8 -Path $FileNameCSV

# Load EPPlus
$DLLPath = "$HOME\Documents\WindowsPowerShell\Modules\EPPlus\EPPlus.dll"
[Reflection.Assembly]::LoadFile($DLLPath) | Out-Null

# Set CSV Format
$Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
$Format.Delimiter = ";"
# use Text Qualifier if your CSV entries are quoted, e.g. "Cell1","Cell2"
$Format.TextQualifier = '"'
$Format.Encoding = [System.Text.Encoding]::UTF8
$Format.SkipLinesBeginning = '1'
$Format.SkipLinesEnd = '1'

# Set Preferred Table Style
$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1

# Create Excel File
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage 
$Worksheet = $ExcelPackage.Workbook.Worksheets.Add("FromCSV")

# Load CSV File with first row as heads using a table style
$null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true) 

# Load CSV File without table style
#$null=$Worksheet.Cells.LoadFromText($file,$format) 

# Fit Column Size to Size of Content
$Worksheet.Cells[$Worksheet.Dimension.Address].AutoFitColumns()

# Save Excel File
$ExcelPackage.SaveAs($FileNameExcel) 

Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"

The page cannot be displayed because an internal server error has occurred on server

it seems it works after I commented this line in web.config

<compilation debug="true" targetFramework="4.5.2" />

Showing loading animation in center of page while making a call to Action method in ASP .NET MVC

I defined two functions in Site.Master:

    <script type="text/javascript">
    var spinnerVisible = false;
    function showProgress() {
        if (!spinnerVisible) {
            $("div#spinner").fadeIn("fast");
            spinnerVisible = true;
        }
    };
    function hideProgress() {
        if (spinnerVisible) {
            var spinner = $("div#spinner");
            spinner.stop();
            spinner.fadeOut("fast");
            spinnerVisible = false;
        }
    };
</script>

And special section:

    <div id="spinner">
        Loading...
    </div>

Visual style is defined in CSS:

div#spinner
{
    display: none;
    width:100px;
    height: 100px;
    position: fixed;
    top: 50%;
    left: 50%;
    background:url(spinner.gif) no-repeat center #fff;
    text-align:center;
    padding:10px;
    font:normal 16px Tahoma, Geneva, sans-serif;
    border:1px solid #666;
    margin-left: -50px;
    margin-top: -50px;
    z-index:2;
    overflow: auto;
}

c - warning: implicit declaration of function ‘printf’

You need to include the appropriate header

#include <stdio.h>

If you're not sure which header a standard function is defined in, the function's man page will state this.

How do I connect to a MySQL Database in Python?

Stop Using MySQLDb if you want to avoid installing mysql headers just to access mysql from python.

Use pymysql. It does all of what MySQLDb does, but it was implemented purely in Python with NO External Dependencies. This makes the installation process on all operating systems consistent and easy. pymysql is a drop in replacement for MySQLDb and IMHO there is no reason to ever use MySQLDb for anything... EVER! - PTSD from installing MySQLDb on Mac OSX and *Nix systems, but that's just me.

Installation

pip install pymysql

That's it... you are ready to play.

Example usage from pymysql Github repo

import pymysql.cursors
import pymysql

# Connect to the database
connection = pymysql.connect(host='localhost',
                             user='user',
                             password='passwd',
                             db='db',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:
        # Create a new record
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('[email protected]', 'very-secret'))

    # connection is not autocommit by default. So you must commit to save
    # your changes.
    connection.commit()

    with connection.cursor() as cursor:
        # Read a single record
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('[email protected]',))
        result = cursor.fetchone()
        print(result)
finally:
    connection.close()

ALSO - Replace MySQLdb in existing code quickly and transparently

If you have existing code that uses MySQLdb, you can easily replace it with pymysql using this simple process:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()

All subsequent references to MySQLdb will use pymysql transparently.

How to set image to UIImage

UIImage *img = [UIImage imageNamed:@"anyImageName"];

imageNamed:
Returns the image object associated with the specified filename.

    + (UIImage *)imageNamed:(NSString *)name

Parameters
name
The name of the file. If this is the first time the image is being loaded, the method looks for an image with the specified name in the application’s main bundle.
Return Value
The image object for the specified file, or nil if the method could not find the specified image.

Discussion
This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

How can I convert a Word document to PDF?

It's already 2019, I can't believe still no easiest and conveniencest way to convert the most popular Micro$oft Word document to Adobe PDF format in Java world.

I almost tried every method the above answers mentioned, and I found the best and the only way can satisfy my requirement is by using OpenOffice or LibreOffice. Actually I am not exactly know the difference between them, seems both of them provide soffice command line.

My requirement is:

  1. It must run on Linux, more specifically CentOS, not on Windows, thus we cannot install Microsoft Office on it;
  2. It must support Chinese character, so ISO-8859-1 character encoding is not a choice, it must support Unicode.

First thing came in mind is doc-to-pdf-converter, but it lacks of maintenance, last update happened 4 years ago, I will not use a nobody-maintain-solution. Xdocreport seems a promising choice, but it can only convert docx, but not doc binary file which is mandatory for me. Using Java to call OpenOffice API seems good, but too complicated for such a simple requirement.

Finally I found the best solution: use OpenOffice command line to finish the job:

Runtime.getRuntime().exec("soffice --convert-to pdf -outdir . /path/some.doc");

I always believe the shortest code is the best code (of course it should be understandable), that's it.

callback to handle completion of pipe

I found an a bit different solution of my problem regarding this context. Thought worth sharing.

Most of the example create readStreams from file. But in my case readStream has to be created from JSON string coming from a message pool.

var jsonStream = through2.obj(function(chunk, encoding, callback) {
                    this.push(JSON.stringify(chunk, null, 4) + '\n');
                    callback();
                });
// message.value --> value/text to write in write.txt 
jsonStream.write(JSON.parse(message.value));
var writeStream = sftp.createWriteStream("/path/to/write/write.txt");

//"close" event didn't work for me!
writeStream.on( 'close', function () {
    console.log( "- done!" );
    sftp.end();
    }
);

//"finish" event didn't work for me either!
writeStream.on( 'close', function () {
    console.log( "- done!"
        sftp.end();
        }
);

// finally this worked for me!
jsonStream.on('data', function(data) {
    var toString = Object.prototype.toString.call(data);
    console.log('type of data:', toString);
    console.log( "- file transferred" );
});

jsonStream.pipe( writeStream );

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

Inconsistent accessibility: property type is less accessible

make your class public access modifier,

just add public keyword infront of your class name

 namespace Test
{
  public  class Delivery
    {
        private string name;
        private string address;
        private DateTime arrivalTime;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Address
        {
            get { return address; }
            set { address = value; }
        }

        public DateTime ArrivlaTime
        {
            get { return arrivalTime; }
            set { arrivalTime = value; }
        }

        public string ToString()
        {
            { return name + address + arrivalTime.ToString(); }
        }
    }
}

Could not load file or assembly ... The parameter is incorrect

The problem relates to the .Net runtime version of a referenced class library (expaned references, select the library and check the "Runtime Version". I had a problem with Antlr3.Runtime, after upgrading my visual studio project to v4.5. I used NuGet to uninstall Microsoft ASP.NET Web Optimisation Framework (due to a chain of dependencies that prevented me from uninstalling Antlr3 directly)

I then used NuGet to reinstall the Microsoft ASP.NET Web Optimisation Framework. This reinstalled the correct runtime versions.

Android how to convert int to String?

Use this String.valueOf(value);

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:

%windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows)

When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

If you are using linux and faced such problem during creating link, try to change jar file path of original jmeter file.

+ java -server -XX:+HeapDumpOnOutOfMemoryError -Xms512m -Xmx512m -XX:NewSize=128m -XX:MaxNewSize=128m -XX:MaxTenuringThreshold=2 -XX:PermSize=64m -XX:MaxPermSize=128m -XX:+CMSClassUnloadingEnabled -jar ./ApacheJMeter.jar -help

Change to:

java $ARGS $JVM_ARGS -jar "/opt/apache-jmeter-2.11/bin/ApacheJMeter.jar" "$@"

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I have encountered this error while updating records from table which has trigger enabled. For example - I have trigger 'Trigger1' on table 'Table1'. When I tried to update the 'Table1' using the update query - it throws the same error. THis is because if you are updating more than 1 record in your query, then 'Trigger1' will throw this error as it doesn't support updating multiple entries if it is enabled on same table. I tried disabling trigger before update and then performed update operation and it was completed without any error.

DISABLE TRIGGER Trigger1 ON Table1;
Update query --------
Enable TRIGGER Trigger1 ON Table1;

Adding git branch on the Bash command prompt

git 1.9.3 or later: use __git_ps1

Git provides a shell script called git-prompt.sh, which includes a function __git_ps1 that

prints text to add to bash PS1 prompt (includes branch name)

Its most basic usage is:

$ __git_ps1
(master)

It also takes an optional format string:

$ __git_ps1 'git:[%s]'
git:[master]

How to Get It

First, copy the file to somewhere (e.g. ~/.git-prompt.sh).

Option 1: use an existing copy on your filesystem. Example (Mac OS X 10.15):

$ find / -name 'git-prompt.sh' -type f -print -quit 2>/dev/null
/Library/Developer/CommandLineTools/usr/share/git-core/git-prompt.sh

Option 2: Pull the script from GitHub.

Next, add the following line to your .bashrc/.zshrc:

source ~/.git-prompt.sh

Finally, change your PS1 to call __git_ps1 as command-substitution:

Bash:

PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '

Zsh:

setopt PROMPT_SUBST ; PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

git < 1.9.3

But note that only git 1.9.3 (May 2014) or later allows you to safely display that branch name(!)

See commit 8976500 by Richard Hansen (richardhansen):

Both bash and zsh subject the value of PS1 to parameter expansion, command substitution, and arithmetic expansion.

Rather than include the raw, unescaped branch name in PS1 when running in two- or three-argument mode, construct PS1 to reference a variable that holds the branch name.

Because the shells do not recursively expand, this avoids arbitrary code execution by specially-crafted branch names such as

'$(IFS=_;cmd=sudo_rm_-rf_/;$cmd)'.

What devious mind would name a branch like that? ;) (Beside a Mom as in xkcd)

More Examples

still_dreaming_1 reports in the comments:

This seems to work great if you want a color prompt with xterm (in my .bashrc):

PS1='\[\e]0;\u@\h: \w\a\]\n${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\03??3[01;34m\]\w\[\033[00m\]$(__git_ps1)\$ ' 

Everything is a different color, including the branch.

In in Linux Mint 17.3 Cinnamon 64-bit:

PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\]$(__git_ps1) \$ ' 

what is <meta charset="utf-8">?

That meta tag basically specifies which character set a website is written with.

Here is a definition of UTF-8:

UTF-8 (U from Universal Character Set + Transformation Format—8-bit) is a character encoding capable of encoding all possible characters (called code points) in Unicode. The encoding is variable-length and uses 8-bit code units.

How to word wrap text in HTML?

In HTML body try:

<table>
    <tr>
        <td>
            <div style="word-wrap: break-word; width: 800px">
                Hello world, how are you? More text here to see if it wraps after a long while of writing and it does on Firefox but I have not tested it on Chrome yet. It also works wonders if you have a medium to long paragraph. Just avoid writing in the CSS file that the words have to break-all, that's a small tip.
            </div>
        </td>
    </tr>
</table>

In CSS body try:

background-size: auto;

table-layout: fixed;

How to do "If Clicked Else .."

This is all you need: http://api.jquery.com/click/

Having an "else" doesn't apply in this scenario, else would mean "did not click", in which case you just wouldn't do anything.

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

Erm, after understanding your question: are you sure that the signature-method only creates a SHA1 and encrypts it? GPG et al offer to compress/clear sign the data. Maybe this java-signature-alg also creates a detachable/attachable signature.

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

It is not related with Firewall. I had the same issue accessing from office and from mobile. I cleaned the cookies and worked fine. You can read more at https://support.google.com/chromebook/answer/1085581?hl=en

Grep characters before and after match?

With gawk , you can use match function:

    x="hey there how are you"
    echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
    ere   are

If you are ok with perl, more flexible solution : Following will print three characters before the pattern followed by actual pattern and then 5 character after the pattern.

echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
ey there how

This can also be applied to words instead of just characters.Following will print one word before the actual matching string.

echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
hey

Following will print one word after the pattern:

echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
how

Following will print one word before the pattern , then the actual word and then one word after the pattern:

echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
hey there how

Jquery - How to make $.post() use contentType=application/json?

The documentation currently shows that as of 3.0, $.post will accept the settings object, meaning that you can use the $.ajax options. 3.0 is not released yet and on the commit they're talking about hiding the reference to it in the docs, but look for it in the future!

Python: split a list based on a condition?

solution

from itertools import tee

def unpack_args(fn):
    return lambda t: fn(*t)

def separate(fn, lx):
    return map(
        unpack_args(
            lambda i, ly: filter(
                lambda el: bool(i) == fn(el),
                ly)),
        enumerate(tee(lx, 2)))

test

[even, odd] = separate(
    lambda x: bool(x % 2),
    [1, 2, 3, 4, 5])
print(list(even) == [2, 4])
print(list(odd) == [1, 3, 5])

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

As noted in the official documentation, simply apply the class(es) btn btn-link:

<!-- Deemphasize a button by making it look like a link while maintaining button behavior -->
<button type="button" class="btn btn-link">Link</button>

For example, with the code you have provided:

_x000D_
_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
_x000D_
<form action="..." method="post">_x000D_
  <div class="row-fluid">_x000D_
    <!-- Navigation for the form -->_x000D_
    <div class="span3">_x000D_
      <ul class="nav nav-tabs nav-stacked">_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 1">Link 1</button>_x000D_
        </li>_x000D_
        <li>_x000D_
          <button class="btn btn-link" role="link" type="submit" name="op" value="Link 2">Link 2</button>_x000D_
        </li>_x000D_
        <!-- ... -->_x000D_
      </ul>_x000D_
    </div>_x000D_
    <!-- The actual form -->_x000D_
    <div class="span9">_x000D_
      <!-- ... -->_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

Gooye if it's possible to use Joda Time in your project then this code works for me:

String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";

DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);

String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);

Store mysql query output into a shell variable

I don't know much about the MySQL command line interface, but assuming you only need help with the bashing, you should try to either swap the commands around like so:

myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql database -u $user -p$password)

which echos the string into MySQL. Or, you can be more fancy and use some new bash-features (the here string)

myvariable=$(mysql database -u $user -p$password<<<"SELECT A, B, C FROM table_a")

resulting in the same thing (assuming you're using a recent enough bash version), without involving echo.

Please note that the -p$password is not a typo, but is the way MySQL expects passwords to be entered through the command line (with no space between the option and value).

Note that myvariable will contain everything that MySQL outputs on standard out (usually everything but error messages), including any and all column headers, ASCII-art frames and so on, which may or may not be what you want.

EDIT:
As has been noted, there appears to be a -e parameter to MySQL, I'd go for that one, definitely.

C++ Array of pointers: delete or delete []?

You delete each pointer individually, and then you delete the entire array. Make sure you've defined a proper destructor for the classes being stored in the array, otherwise you cannot be sure that the objects are cleaned up properly. Be sure that all your destructors are virtual so that they behave properly when used with inheritance.

How to get the current taxonomy term ID (not the slug) in WordPress?

See wp_get_post_terms(), you'd do something like so:

global $post;
$terms = wp_get_post_terms( $post->ID, 'YOUR_TAXONOMY_NAME',array('fields' => 'ids') );

print_r($terms);

How to delete all instances of a character in a string in python?

Strings are immutable in Python, which means once a string is created, you cannot alter the contents of the strings. If at all, you need to change it, a new instance of the string will be created with the alterations.

Having that in mind, we have so many ways to solve this

  1. Using str.replace,

    >>> "it is icy".replace("i", "")
    't s cy'
    
  2. Using str.translate,

    >>> "it is icy".translate(None, "i")
    't s cy'
    
  3. Using Regular Expression,

    >>> import re
    >>> re.sub(r'i', "", "it is icy")
    't s cy'
    
  4. Using comprehension as a filter,

    >>> "".join([char for char in "it is icy" if char != "i"])
    't s cy'
    
  5. Using filter function

    >>> "".join(filter(lambda char: char != "i", "it is icy"))
    't s cy'
    

Timing comparison

def findreplace(m_string, char):
    m_string = list(m_string)
    for k in m_string:
        if k == char:
            del(m_string[m_string.index(k)])
    return "".join(m_string)

def replace(m_string, char):
    return m_string.replace("i", "")

def translate(m_string, char):
    return m_string.translate(None, "i")

from timeit import timeit

print timeit("findreplace('it is icy','i')", "from __main__ import findreplace")
print timeit("replace('it is icy','i')", "from __main__ import replace")
print timeit("translate('it is icy','i')", "from __main__ import translate")

Result

1.64474582672
0.29278588295
0.311302900314

str.replace and str.translate methods are 8 and 5 times faster than the accepted answer.

Note: Comprehension method and filter methods are expected to be slower, for this case, since they have to create list and then they have to be traversed again to construct a string. And re is a bit overkill for a single character replacement. So, they all are excluded from the timing comparison.

Invalid URI: The format of the URI could not be determined

The issue for me was that when i got some domain name, i had:

cloudsearch-..-..-xxx.aws.cloudsearch... [WRONG]

http://cloudsearch-..-..-xxx.aws.cloudsearch... [RIGHT]

hope this does the job for you :)

How to set proper codeigniter base url?

Try to add the controller to your index page aswell. Just looked at as similar structure on one of my own site and I hade my base url set to = "somedomain.com/v2/controller"

How to set the part of the text view is clickable

For bold,

mySpannable.setSpan(new StyleSpan(Typeface.BOLD),termStart,termStop,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

html5 - canvas element - Multiple layers

Related to this:

If you have something on your canvas and you want to draw something at the back of it - you can do it by changing the context.globalCompositeOperation setting to 'destination-over' - and then return it to 'source-over' when you're done.

_x000D_
_x000D_
   var context = document.getElementById('cvs').getContext('2d');_x000D_
_x000D_
    // Draw a red square_x000D_
    context.fillStyle = 'red';_x000D_
    context.fillRect(50,50,100,100);_x000D_
_x000D_
_x000D_
_x000D_
    // Change the globalCompositeOperation to destination-over so that anything_x000D_
    // that is drawn on to the canvas from this point on is drawn at the back_x000D_
    // of what's already on the canvas_x000D_
    context.globalCompositeOperation = 'destination-over';_x000D_
_x000D_
_x000D_
_x000D_
    // Draw a big yellow rectangle_x000D_
    context.fillStyle = 'yellow';_x000D_
    context.fillRect(0,0,600,250);_x000D_
_x000D_
_x000D_
    // Now return the globalCompositeOperation to source-over and draw a_x000D_
    // blue rectangle_x000D_
    context.globalCompositeOperation = 'source-over';_x000D_
_x000D_
    // Draw a blue rectangle_x000D_
    context.fillStyle = 'blue';_x000D_
    context.fillRect(75,75,100,100);
_x000D_
<canvas id="cvs" />
_x000D_
_x000D_
_x000D_

Switch case: can I use a range instead of a one number

Through switch case it's impossible.You can go with nested if statements.

if(number>=1 && number<=4){
//Do something
}else if(number>=5 && number<=9){
//Do something
}

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

Where do I get servlet-api.jar from?

You may want to consider using Java EE, which includes the javax.servlet.* packages. If you require a specific version of the servlet api, for instance to target a specific web application server, you will probably want the Java EE version which matches, see this version table.

OpenMP set_num_threads() is not working

I was facing the same problem . Solution is given below

Right click on Source Program > Properties > Configuration Properties > C/C++ > Language > Now change Open MP support flag to Yes....

You will get the desired result.

T-SQL split string based on delimiter

ALTER FUNCTION [dbo].[split_string](
          @delimited NVARCHAR(MAX),
          @delimiter NVARCHAR(100)
        ) RETURNS @t TABLE (id INT IDENTITY(1,1), val NVARCHAR(MAX))
AS
BEGIN
  DECLARE @xml XML
  SET @xml = N'<t>' + REPLACE(@delimited,@delimiter,'</t><t>') + '</t>'

  INSERT INTO @t(val)
  SELECT  r.value('.','varchar(MAX)') as item
  FROM  @xml.nodes('/t') as records(r)
  RETURN
END

Warning: X may be used uninitialized in this function

You get the warning because you did not assign a value to one, which is a pointer. This is undefined behavior.

You should declare it like this:

Vector* one = malloc(sizeof(Vector));

or like this:

Vector one;

in which case you need to replace -> operator with . like this:

one.a = 12;
one.b = 13;
one.c = -11;

Finally, in C99 and later you can use designated initializers:

Vector one = {
   .a = 12
,  .b = 13
,  .c = -11
};

Appending a line to a file only if it does not already exist

I needed to edit a file with restricted write permissions so needed sudo. working from ghostdog74's answer and using a temp file:

awk 'FNR==NR && /configs.*projectname\.conf/{f=1;next}f==0;END{ if(!f) { print "your line"}} ' file > /tmp/file
sudo mv /tmp/file file

Foreign Key to multiple tables

Yet another option is to have, in Ticket, one column specifying the owning entity type (User or Group), second column with referenced User or Group id and NOT to use Foreign Keys but instead rely on a Trigger to enforce referential integrity.

Two advantages I see here over Nathan's excellent model (above):

  • More immediate clarity and simplicity.
  • Simpler queries to write.

Are the decimal places in a CSS width respected?

Elements have to paint to an integer number of pixels, and as the other answers covered, percentages are indeed respected.

An important note is that pixels in this case means css pixels, not screen pixels, so a 200px container with a 50.7499% child will be rounded to 101px css pixels, which then get rendered onto 202px on a retina screen, and not 400 * .507499 ~= 203px.

Screen density is ignored in this calculation, and there is no way to paint* an element to specific retina subpixel sizes. You can't have elements' backgrounds or borders rendered at less than 1 css pixel size, even though the actual element's size could be less than 1 css pixel as Sandy Gifford showed.

[*] You can use some techniques like 0.5 offset box-shadow, etc, but the actual box model properties will paint to a full CSS pixel.

Printing without newline (print 'a',) prints a space, how to remove?

Just as a side note:

Printing is O(1) but building a string and then printing is O(n), where n is the total number of characters in the string. So yes, while building the string is "cleaner", it's not the most efficient method of doing so.

The way I would do it is as follows:

from sys import stdout
printf = stdout.write

Now you have a "print function" that prints out any string you give it without returning the new line character each time.

printf("Hello,")
printf("World!")

The output will be: Hello, World!

However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.

printf(str(2) + " " + str(4))

The output will be: 2 4

When to create variables (memory management)

It's really a matter of opinion. In your example, System.out.println(5) would be slightly more efficient, as you only refer to the number once and never change it. As was said in a comment, int is a primitive type and not a reference - thus it doesn't take up much space. However, you might want to set actual reference variables to null only if they are used in a very complicated method. All local reference variables are garbage collected when the method they are declared in returns.

Batch script: how to check for admin rights

Alternative: Use an external utility that is designed for this purpose, e.g., IsAdmin.exe (unrestricted freeware).

Exit codes:

0 - Current user not member of Administrators group

1 - Current user member of Administrators and running elevated

2 - Current user member of Administrators, but not running elevated

Print string to text file

text_file = open("Output.txt", "w")
text_file.write("Purchase Amount: %s" % TotalAmount)
text_file.close()

If you use a context manager, the file is closed automatically for you

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: %s" % TotalAmount)

If you're using Python2.6 or higher, it's preferred to use str.format()

with open("Output.txt", "w") as text_file:
    text_file.write("Purchase Amount: {0}".format(TotalAmount))

For python2.7 and higher you can use {} instead of {0}

In Python3, there is an optional file parameter to the print function

with open("Output.txt", "w") as text_file:
    print("Purchase Amount: {}".format(TotalAmount), file=text_file)

Python3.6 introduced f-strings for another alternative

with open("Output.txt", "w") as text_file:
    print(f"Purchase Amount: {TotalAmount}", file=text_file)

How to include jQuery in ASP.Net project?

You can include the script file directly in your page/master page, etc using:

 <script type="text/javascript" src="/scripts/jquery.min.js"></script> 

Us use a Content Delivery network like Google or Microsoft:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 

or:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>