Programs & Examples On #Modality

How to resolve this System.IO.FileNotFoundException

Check all the references carefully

  • Version remains same on target machine and local machine
  • If assembly is referenced from GAC, ensure that proper version is loaded

For me cleaning entire solution by deleting manually, updating (removing and adding) references again with version in sync with target machine and then building with with Copy Local > False for GAC assemblies solves the problem.

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

Easy and simple solution for MAC

My Issue was

cordova build android
ANDROID_HOME=/Users/jerilkuruvila/Library/Android/sdk
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_65.jdk/Contents/Home
Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK.
Looked here: /Users/jerilkuruvila/Library/Android/sdk/tools/templates/gradle/wrapper

Solution

jerilkuruvila@Jerils-ENIAC tools $ cd templates
-bash: cd: mkdir: No such file or directory
jerilkuruvila@Jerils-ENIAC tools $ mkdir templates
jerilkuruvila@Jerils-ENIAC tools $ cp -rf gradle templates/
jerilkuruvila@Jerils-ENIAC tools $ chmod a+x templates/

cordova build android again working now !!!

Difference between Divide and Conquer Algo and Dynamic Programming

I assume you have already read Wikipedia and other academic resources on this, so I won't recycle any of that information. I must also caveat that I am not a computer science expert by any means, but I'll share my two cents on my understanding of these topics...

Dynamic Programming

Breaks the problem down into discrete subproblems. The recursive algorithm for the Fibonacci sequence is an example of Dynamic Programming, because it solves for fib(n) by first solving for fib(n-1). In order to solve the original problem, it solves a different problem.

Divide and Conquer

These algorithms typically solve similar pieces of the problem, and then put them together at the end. Mergesort is a classic example of divide and conquer. The main difference between this example and the Fibonacci example is that in a mergesort, the division can (theoretically) be arbitrary, and no matter how you slice it up, you are still merging and sorting. The same amount of work has to be done to mergesort the array, no matter how you divide it up. Solving for fib(52) requires more steps than solving for fib(2).

Find index of last occurrence of a substring in a string

If you don't wanna use rfind then this will do the trick/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos

Get the Highlighted/Selected text

Get highlighted text this way:

window.getSelection().toString()

and of course a special treatment for ie:

document.selection.createRange().htmlText

Removing path and extension from filename in PowerShell

you can use basename property

PS II> ls *.ps1 | select basename

How to escape single quotes within single quoted strings

Here are my two cents -- in the case if one wants to be sh-portable, not just bash-specific ( the solution is not too efficient, though, as it starts an external program -- sed ):

  • put this in quote.sh ( or just quote ) somewhere on your PATH :
# this works with standard input (stdin)
quote() {
  echo -n "'" ;
  sed 's/\(['"'"']['"'"']*\)/'"'"'"\1"'"'"'/g' ;
  echo -n "'"
}

case "$1" in
 -) quote ;;
 *) echo "usage: cat ... | quote - # single-quotes input for Bourne shell" 2>&1 ;;
esac

An example:

$ echo -n "G'day, mate!" | ./quote.sh -
'G'"'"'day, mate!'

And, of course, that converts back:

$ echo 'G'"'"'day, mate!'
G'day, mate!

Explanation: basically we have to enclose the input with quotes ', and then also replace any single quote within with this micro-monster: '"'"' ( end the opening quote with a pairing ', escape the found single quote by wrapping it with double quotes -- "'", and then finally issue a new opening single quote ', or in pseudo-notation : ' + "'" + ' == '"'"' )

One standard way to do that would be to use sed with the following substitution command:

s/\(['][']*\)/'"\1"'/g 

One small problem, though, is that in order to use that in shell one needs to escape all these single quote characters in the sed expression itself -- what leads to something like

sed 's/\(['"'"']['"'"']*\)/'"'"'"\1"'"'"'/g' 

( and one good way to build this result is to feed the original expression s/\(['][']*\)/'"\1"'/g to Kyle Rose' or George V. Reilly's scripts ).

Finally, it kind of makes sense to expect the input to come from stdin -- since passing it through command-line arguments could be already too much trouble.

( Oh, and may be we want to add a small help message so that the script does not hang when someone just runs it as ./quote.sh --help wondering what it does. )

Is there a standard sign function (signum, sgn) in C/C++?

The accepted Answer with the overload below does indeed not trigger -Wtype-limits.

template <typename T> inline constexpr
  int signum(T x, std::false_type) {
  return T(0) < x;
}

template <typename T> inline constexpr
  int signum(T x, std::true_type) {
  return (T(0) < x) - (x < T(0));
}

template <typename T> inline constexpr
  int signum(T x) {
  return signum(x, std::is_signed<T>());
}

For C++11 an alternative could be.

template <typename T>
typename std::enable_if<std::is_unsigned<T>::value, int>::type
inline constexpr signum(T const x) {
    return T(0) < x;  
}

template <typename T>
typename std::enable_if<std::is_signed<T>::value, int>::type
inline constexpr signum(T const x) {
    return (T(0) < x) - (x < T(0));  
}

For me it does not trigger any warnings on GCC 5.3.1.

What is the difference between Subject and BehaviorSubject?

It might help you to understand.

import * as Rx from 'rxjs';

const subject1 = new Rx.Subject();
subject1.next(1);
subject1.subscribe(x => console.log(x)); // will print nothing -> because we subscribed after the emission and it does not hold the value.

const subject2 = new Rx.Subject();
subject2.subscribe(x => console.log(x)); // print 1 -> because the emission happend after the subscription.
subject2.next(1);

const behavSubject1 = new Rx.BehaviorSubject(1);
behavSubject1.next(2);
behavSubject1.subscribe(x => console.log(x)); // print 2 -> because it holds the value.

const behavSubject2 = new Rx.BehaviorSubject(1);
behavSubject2.subscribe(x => console.log('val:', x)); // print 1 -> default value
behavSubject2.next(2) // just because of next emission will print 2 

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

np.mean() vs np.average() in Python NumPy?

In your invocation, the two functions are the same.

average can compute a weighted average though.

Doc links: mean and average

How to get the value from the GET parameters?

I found this ages ago, very easy:

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,    
    function(m,key,value) {
      vars[key] = value;
    });
    return vars;
  }

Then call it like this:

var fType = getUrlVars()["type"];

Pick any kind of file via an Intent in Android

Samsung file explorer needs not only custom action (com.sec.android.app.myfiles.PICK_DATA), but also category part (Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.

Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);

You can also use this action for opening multiple files: com.sec.android.app.myfiles.PICK_DATA_MULTIPLE Anyway here is my solution which works on Samsung and other devices:

public void openFile(String mimeType) {

        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType(mimeType);
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        // special intent for Samsung file manager
        Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
         // if you want any file type, you can skip next line 
        sIntent.putExtra("CONTENT_TYPE", mimeType); 
        sIntent.addCategory(Intent.CATEGORY_DEFAULT);

        Intent chooserIntent;
        if (getPackageManager().resolveActivity(sIntent, 0) != null){
            // it is device with Samsung file manager
            chooserIntent = Intent.createChooser(sIntent, "Open file");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
        } else {
            chooserIntent = Intent.createChooser(intent, "Open file");
        }

        try {
            startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
        } catch (android.content.ActivityNotFoundException ex) {
            Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
        }
    }

This solution works well for me, and maybe will be useful for someone else.

Convert Dictionary to JSON in Swift

using lldb

(lldb) p JSONSerialization.data(withJSONObject: notification.request.content.userInfo, options: [])
(Data) $R16 = 375 bytes
(lldb) p String(data: $R16!, encoding: .utf8)!
(String) $R18 = "{\"aps\": \"some_text\"}"

//or
p String(data: JSONSerialization.data(withJSONObject: notification.request.content.userInfo, options: [])!, encoding: .utf8)!
(String) $R4 = "{\"aps\": \"some_text\"}"

JQuery show and hide div on mouse click (animate)

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        $(".click-header").click(function(){
            $(this).next(".hidden-content").slideToggle("slow");
            $(this).toggleClass("expanded-header");
        });
    });
</script>
.demo-container {
    margin:0 auto;
    width: 600px;
    text-align:center;
}
.click-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-down.png) no-repeat 50% 50%;
}
.expanded-header {
    padding: 5px 10px 5px 60px;
    background: url(images/arrow-up.png) no-repeat 50% 50%;
}
.hidden-content {
    display:none;
    border: 1px solid #d7dbd8;
    padding: 20px;
    text-align: center;
}
<div class="demo-container">
    <div class="click-header">&nbsp;</div>
    <div class="hidden-content">Lorem Ipsum.</div>
</div>

How can I check if a single character appears in a string?

I'm not sure what the original poster is asking exactly. Since indexOf(...) and contains(...) both probably use loops internally, perhaps he's looking to see if this is possible at all without a loop? I can think of two ways off hand, one would of course be recurrsion:

public boolean containsChar(String s, char search) {
    if (s.length() == 0)
        return false;
    else
        return s.charAt(0) == search || containsChar(s.substring(1), search);
}

The other is far less elegant, but completeness...:

/**
 * Works for strings of up to 5 characters
 */
public boolean containsChar(String s, char search) {
    if (s.length() > 5) throw IllegalArgumentException();

    try {
        if (s.charAt(0) == search) return true;
        if (s.charAt(1) == search) return true;
        if (s.charAt(2) == search) return true;
        if (s.charAt(3) == search) return true;
        if (s.charAt(4) == search) return true;
    } catch (IndexOutOfBoundsException e) {
        // this should never happen...
        return false;
    }
    return false;
}

The number of lines grow as you need to support longer and longer strings of course. But there are no loops/recurrsions at all. You can even remove the length check if you're concerned that that length() uses a loop.

Expected block end YAML error

I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.

Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart.

I have solved it by fixing, the Alignment issue inside the same .yml file.

If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.

Now i am doing well.

How to overlay image with color in CSS?

You could use the hue-rotate function in the filter property. It's quite an obscure measurement though, you'd need to know how many degrees round the colour wheel you need to move in order to arrive at your desired hue, for example:

header {
    filter: hue-rotate(90deg);
}

Once you'd found the correct hue, you could combine the brightness and either grayscale or saturate functions to find the correct shade, for example:

header {
    filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}

The filter property has a vendor prefix in Webkit, so the final code would be:

header {
  -webkit-filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
          filter: hue-rotate(90deg) brightness(10%) grayscale(10%);
}

How can I check whether Google Maps is fully loaded?

GMap2::tilesloaded() would be the event you're looking for.

See GMap2.tilesloaded for references.

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How to display a range input slider vertically

Without changing the position to absolute, see below. This supports all recent browsers as well.

_x000D_
_x000D_
.vranger {_x000D_
  margin-top: 50px;_x000D_
   transform: rotate(270deg);_x000D_
  -moz-transform: rotate(270deg); /*do same for other browsers if required*/_x000D_
}
_x000D_
<input type="range" class="vranger"/>
_x000D_
_x000D_
_x000D_

for very old browsers, you can use -sand-transform: rotate(10deg); from CSS sandpaper

or use

prefix selector such as -ms-transform: rotate(270deg); for IE9

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

For chat applications or any other application that is in constant conversation with the server, WebSockets are the best option. However, you can only use WebSockets with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling to obtain similar functionality.

How do I close a tkinter window?

raise SystemExit

this worked on the first try, where

self.destroy()
root.destroy()

did not

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

Does C# support multiple inheritance?

You may want to take your argument a step further and talk about design patterns - and you can find out why he'd want to bother trying to inherit from multiple classes in c# if he even could

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

The solution to change the encoding to Latin1 / ISO-8859-1 solves an issue I observed with html2text.py as invoked on an output of tex4ht. I use that for an automated word count on LaTeX documents: tex4ht converts them to HTML, and then html2text.py strips them down to pure text for further counting through wc -w. Now, if, for example, a German "Umlaut" comes in through a literature database entry, that process would fail as html2text.py would complain e.g.

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 32243-32245: invalid data

Now these errors would then subsequently be particularly hard to track down, and essentially you want to have the Umlaut in your references section. A simple change inside html2text.py from

data = data.decode(encoding)

to

data = data.decode("ISO-8859-1")

solves that issue; if you're calling the script using the HTML file as first parameter, you can also pass the encoding as second parameter and spare the modification.

Showing an image from console in Python

Or simply execute the image through the shell, as in

import subprocess
subprocess.call([ fname ], shell=True)

and whatever program is installed to handle images will be launched.

Changing API level Android Studio

For android studio users:

  1. right click the App directory
  2. choose the "module setting" option
  3. change the ADK Platform as what you need
  4. Click Apply

The gradle will rebuild the project automatically.

How to copy files between two nodes using ansible

To copy remote-to-remote files you can use the synchronize module with 'delegate_to: source-server' keyword:

- hosts: serverB
  tasks:    
   - name: Copy Remote-To-Remote (from serverA to serverB)
     synchronize: src=/copy/from_serverA dest=/copy/to_serverB
     delegate_to: serverA

This playbook can run from your machineC.

Default values for Vue component props & how to check if a user did not set the prop?

Also something important to add here, in order to set default values for arrays and objects we must use the default function for props:

propE: {
      type: Object,
      // Object or array defaults must be returned from
      // a factory function
      default: function () {
        return { message: 'hello' }
      }
    },

Getting list of tables, and fields in each, in a database

SELECT * FROM INFORMATION_SCHEMA.COLUMNS for get all

SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS for get all table name. Try it on sqlserver,

How to use Global Variables in C#?

In C# you cannot define true global variables (in the sense that they don't belong to any class).

This being said, the simplest approach that I know to mimic this feature consists in using a static class, as follows:

public static class Globals
{
    public const Int32 BUFFER_SIZE = 512; // Unmodifiable
    public static String FILE_NAME = "Output.txt"; // Modifiable
    public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}

You can then retrieve the defined values anywhere in your code (provided it's part of the same namespace):

String code = Globals.CODE_PREFIX + value.ToString();

In order to deal with different namespaces, you can either:

  • declare the Globals class without including it into a specific namespace (so that it will be placed in the global application namespace);
  • insert the proper using directive for retrieving the variables from another namespace.

How does Git handle symbolic links?

You can find out what Git does with a file by seeing what it does when you add it to the index. The index is like a pre-commit. With the index committed, you can use git checkout to bring everything that was in the index back into the working directory. So, what does Git do when you add a symbolic link to the index?

To find out, first, make a symbolic link:

$ ln -s /path/referenced/by/symlink symlink

Git doesn't know about this file yet. git ls-files lets you inspect your index (-s prints stat-like output):

$ git ls-files -s ./symlink
[nothing]

Now, add the contents of the symbolic link to the Git object store by adding it to the index. When you add a file to the index, Git stores its contents in the Git object store.

$ git add ./symlink

So, what was added?

$ git ls-files -s ./symlink
120000 1596f9db1b9610f238b78dd168ae33faa2dec15c 0       symlink

The hash is a reference to the packed object that was created in the Git object store. You can examine this object if you look in .git/objects/15/96f9db1b9610f238b78dd168ae33faa2dec15c in the root of your repository. This is the file that Git stores in the repository, that you can later check out. If you examine this file, you'll see it is very small. It does not store the contents of the linked file. To confirm this, print the contents of the packed repository object with git cat-file:

$ git cat-file -p 1596f9db1b9610f238b78dd168ae33faa2dec15c
/path/referenced/by/symlink

(Note 120000 is the mode listed in ls-files output. It would be something like 100644 for a regular file.)

But what does Git do with this object when you check it out from the repository and into your filesystem? It depends on the core.symlinks config. From man git-config:

core.symlinks

If false, symbolic links are checked out as small plain files that contain the link text.

So, with a symbolic link in the repository, upon checkout you either get a text file with a reference to a full filesystem path, or a proper symbolic link, depending on the value of the core.symlinks config.

Either way, the data referenced by the symlink is not stored in the repository.

Div show/hide media query

 Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { 
  #my-content{
   width:100%;
 }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { 
  #my-content{
   width:100%;
 }
 }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { 
display: none;
 }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) {
// Havent code only get for more informations 
 } 

Git stash pop- needs merge, unable to refresh index

If anyone is having this issue outside of a merge/conflict/action, then it could be the git lock file for your project causing the issue.

git reset
     fatal: Unable to create '/PATH_TO_PROJECT/.git/index.lock': File exists.
rm -f /PATH_TO_PROJECT/.git/index.lock
git reset
git stash pop

jQuery - Increase the value of a counter when a button is clicked

It's just

var counter = 0;

$("#update").click(function() {
   counter++;
});

Convert string to variable name in python

You can use a Dictionary to keep track of the keys and values.

For instance...

dictOfStuff = {} ##Make a Dictionary

x = "Buffalo" ##OR it can equal the input of something, up to you.

dictOfStuff[x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to  what ever you like

print(dictOfStuff[x]) ##print out the value of the spot in the dict that same key ("name") as the dictionary.

A dictionary is very similar to a real life dictionary. You have a word and you have a definition. You can look up the word and get the definition. So in this case, you have the word "Buffalo" and it's definition is 4. It can work with any other word and definition. Just make sure you put them into the dictionary first.

cmake - find_library - custom library location

I've encountered a similar scenario. I solved it by adding in this following code just before find_library():

set(CMAKE_PREFIX_PATH /the/custom/path/to/your/lib/)

then it can find the library location.

jquery - fastest way to remove all rows from a very large table

Two issues I can see here:

  1. The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.

  2. The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.

jQuery how to bind onclick event to dynamically added HTML element

I believe the good way it to do:

$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );

How should I have explained the difference between an Interface and an Abstract class?

Your explanation looks decent, but may be it looked like you were reading it all from a textbook? :-/

What I'm more bothered about is, how solid was your example? Did you bother to include almost all the differences between abstract and interfaces?

Personally, I would suggest this link: http://mindprod.com/jgloss/interfacevsabstract.html#TABLE

for an exhaustive list of differences..

Hope it helps you and all other readers in their future interviews

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

The below code may help you.

protected String getLocalizedBigDecimalValue(BigDecimal input, Locale locale) {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setGroupingUsed(true);
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);
    return numberFormat.format(input);
}

Access-control-allow-origin with multiple domains

After reading every answer and trying them, none of them helped me. What I found while searching elsewhere is that you can create a custom attribute that you can then add to your controller. It overwrites the EnableCors ones and add the whitelisted domains in it.

This solution is working well because it lets you have the whitelisted domains in the webconfig (appsettings) instead of harcoding them in the EnableCors attribute on your controller.

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public class EnableCorsByAppSettingAttribute : Attribute, ICorsPolicyProvider
{
    const string defaultKey = "whiteListDomainCors";
    private readonly string rawOrigins;
    private CorsPolicy corsPolicy;

    /// <summary>
    /// By default uses "cors:AllowedOrigins" AppSetting key
    /// </summary>
    public EnableCorsByAppSettingAttribute()
        : this(defaultKey) // Use default AppSetting key
    {
    }

    /// <summary>
    /// Enables Cross Origin
    /// </summary>
    /// <param name="appSettingKey">AppSetting key that defines valid origins</param>
    public EnableCorsByAppSettingAttribute(string appSettingKey)
    {
        // Collect comma separated origins
        this.rawOrigins = AppSettings.whiteListDomainCors;
        this.BuildCorsPolicy();
    }

    /// <summary>
    /// Build Cors policy
    /// </summary>
    private void BuildCorsPolicy()
    {
        bool allowAnyHeader = String.IsNullOrEmpty(this.Headers) || this.Headers == "*";
        bool allowAnyMethod = String.IsNullOrEmpty(this.Methods) || this.Methods == "*";

        this.corsPolicy = new CorsPolicy
        {
            AllowAnyHeader = allowAnyHeader,
            AllowAnyMethod = allowAnyMethod,
        };

        // Add origins from app setting value
        this.corsPolicy.Origins.AddCommaSeperatedValues(this.rawOrigins);
        this.corsPolicy.Headers.AddCommaSeperatedValues(this.Headers);
        this.corsPolicy.Methods.AddCommaSeperatedValues(this.Methods);
    }

    public string Headers { get; set; }
    public string Methods { get; set; }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request,
                                               CancellationToken cancellationToken)
    {
        return Task.FromResult(this.corsPolicy);
    }
}

    internal static class CollectionExtensions
{
    public static void AddCommaSeperatedValues(this ICollection<string> current, string raw)
    {
        if (current == null)
        {
            return;
        }

        var paths = new List<string>(AppSettings.whiteListDomainCors.Split(new char[] { ',' }));
        foreach (var value in paths)
        {
            current.Add(value);
        }
    }
}

I found this guide online and it worked like a charm :

http://jnye.co/Posts/2032/dynamic-cors-origins-from-appsettings-using-web-api-2-2-cross-origin-support

I thought i'd drop that here for anyone in need.

PHP - Get bool to echo false when false

echo(var_export($var)); 

When $var is boolean variable, true or false will be printed out.

Installing PDO driver on MySQL Linux server

At first install necessary PDO parts by running the command

`sudo apt-get install php*-mysql` 

where * is a version name of php like 5.6, 7.0, 7.1, 7.2

After installation you need to mention these two statements

extension=pdo.so
extension=pdo_mysql.so

in your .ini file (uncomment if it is already there) and restart server by command

sudo service apache2 restart

Binding arrow keys in JS/jQuery

A terse solution using plain Javascript (thanks to Sygmoral for suggested improvements):

document.onkeydown = function(e) {
    switch (e.keyCode) {
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
    }
};

Also see https://stackoverflow.com/a/17929007/1397061.

php pdo: get the columns name of a table

$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

must be

$q = $dbh->prepare("DESCRIBE database.table");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);

Iterating over Numpy matrix rows to apply a function each?

While you should certainly provide more information, if you are trying to go through each row, you can just iterate with a for loop:

import numpy
m = numpy.ones((3,5),dtype='int')
for row in m:
  print str(row)

What, exactly, is needed for "margin: 0 auto;" to work?

Please go to this quick example I've created jsFiddle. Hopefull it's easy to understand. You can use a wrapper div with the width of the site to center align. The reason you must put width is that so browser knows you are not going for a liquid layout.

show distinct column values in pyspark dataframe: python

If you want to select ALL(columns) data as distinct frrom a DataFrame (df), then

df.select('*').distinct().show(10,truncate=False)

What was the strangest coding standard rule that you were forced to follow?

Back in the 80's/90's, I worked for an aircraft simulator company that used FORTRAN. Our FORTRAN compiler had a limit of 8 characters for variable names. The company's coding standards reserved the first three of them for Hungarian-notation style info. So we had to try and create meaningful variable names with just 5 characters!

How can I see function arguments in IPython Notebook Server 3?

Try Shift-Tab-Tab a bigger documentation appears, than with Shift-Tab. It's the same but you can scroll down.

Shift-Tab-Tab-Tab and the tooltip will linger for 10 seconds while you type.

Shift-Tab-Tab-Tab-Tab and the docstring appears in the pager (small part at the bottom of the window) and stays there.

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

In Java8

//will prints each element line by line
stack.forEach(System.out::println);

or

//to print with commas
stack.forEach(
    (ele) -> {
        System.out.print(ele + ",");
    }
);

How can I get the intersection, union, and subset of arrays in Ruby?

If Multiset extends from the Array class

x = [1, 1, 2, 4, 7]
y = [1, 2, 2, 2]
z = [1, 1, 3, 7]

UNION

x.union(y)           # => [1, 2, 4, 7]      (ONLY IN RUBY 2.6)
x.union(y, z)        # => [1, 2, 4, 7, 3]   (ONLY IN RUBY 2.6)
x | y                # => [1, 2, 4, 7]

DIFFERENCE

x.difference(y)      # => [4, 7] (ONLY IN RUBY 2.6)
x.difference(y, z)   # => [4] (ONLY IN RUBY 2.6)
x - y                # => [4, 7]

INTERSECTION

x & y                # => [1, 2]

For more info about the new methods in Ruby 2.6, you can check this blog post about its new features

How do you add an ActionListener onto a JButton in Java

Two ways:

1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.

2. Use anonymous inner classes:

jBtnSelection.addActionListener(new ActionListener() { 
  public void actionPerformed(ActionEvent e) { 
    selectionButtonPressed();
  } 
} );

Later, you'll have to define selectionButtonPressed(). This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.

The second method also allows you to call the selection method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).

Conversion hex string into ascii in bash command line

You can use xxd:

$cat hex.txt
68 65 6c 6c 6f
$cat hex.txt | xxd -r -p
hello

How can I change text color via keyboard shortcut in MS word 2010

For Word 2010 and 2013, go to File > Options > Customize Ribbon > Keyboard Shortcuts > All Commands (in left list) > Color: (in right list) -- at this point, you type in the short cut (such as Alt+r) and select the color (such as red). (This actually goes back to 2003 but I don't have that installed to provide the pathway.)

Installing tkinter on ubuntu 14.04

First, make sure you have Tkinter module installed.

sudo apt-get install python-tk

In python 2 the package name is Tkinter not tkinter.

from Tkinter import *

ref: http://www.techinfected.net/2015/09/how-to-install-and-use-tkinter-in-ubuntu-debian-linux-mint.html

JPG vs. JPEG image formats

JPG and JPEG stand both for an image format proposed and supported by the Joint Photographic Experts Group. The two terms have the same meaning and are interchangeable.

To read on, check out Difference between JPG and JPEG.

  • The reason for the different file extensions dates back to the early versions of Windows. The original file extension for the Joint Photographic Expert Group File Format was ‘.jpeg’; however in Windows all files required a three letter file extension. So, the file extension was shortened to ‘.jpg’. However, Macintosh was not limited to three letter file extensions, so Mac users used ‘.jpeg’. Eventually, with upgrades Windows also began to accept ‘.jpeg’. However, many users were already used to ‘.jpg’, so both the three letter file extension and the four letter extension began to be commonly used, and still is.

  • Today, the most commonly accepted and used form is the ‘.jpg’, as many users were Windows users. Imaging applications, such as Adobe Photoshop, save all JPEG files with a ".jpg" extension on both Mac and Windows, in an attempt to avoid confusion. The Joint Photographic Expert Group File Format can also be saved with the upper-case ‘.JPEG’ and ‘.JPG’ file extensions, which are less common, but also accepted.

HTTP redirect: 301 (permanent) vs. 302 (temporary)

The main issue with 301 is browser will cache the redirection even if you disabled the redirection from the server level.

Its always better to use 302 if you are enabling the redirection for a short maintenance window.

std::queue iteration

If you need to iterate over a queue then you need something more than a queue. The point of the standard container adapters is to provide a minimal interface. If you need to do iteration as well, why not just use a deque (or list) instead?

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Double decimal formatting in Java

There are many way you can do this. Those are given bellow:

Suppose your original number is given bellow:

 double number = 2354548.235;

Using NumberFormat:

NumberFormat formatter = new DecimalFormat("#0.00");
    System.out.println(formatter.format(number));

Using String.format:

System.out.println(String.format("%,.2f", number));

Using DecimalFormat and pattern:

NumberFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
        DecimalFormat decimalFormatter = (DecimalFormat) nf;
        decimalFormatter.applyPattern("#,###,###.##");
        String fString = decimalFormatter.format(number);
        System.out.println(fString);

Using DecimalFormat and pattern

DecimalFormat decimalFormat = new DecimalFormat("############.##");
        BigDecimal formattedOutput = new BigDecimal(decimalFormat.format(number));
        System.out.println(formattedOutput);

In all cases the output will be: 2354548.23

Note:

During rounding you can add RoundingMode in your formatter. Here are some rounding mode given bellow:

    decimalFormat.setRoundingMode(RoundingMode.CEILING);
    decimalFormat.setRoundingMode(RoundingMode.FLOOR);
    decimalFormat.setRoundingMode(RoundingMode.HALF_DOWN);
    decimalFormat.setRoundingMode(RoundingMode.HALF_UP);
    decimalFormat.setRoundingMode(RoundingMode.UP);

Here are the imports:

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;

Escape invalid XML characters in C#

As the way to remove invalid XML characters I suggest you to use XmlConvert.IsXmlChar method. It was added since .NET Framework 4 and is presented in Silverlight too. Here is the small sample:

void Main() {
    string content = "\v\f\0";
    Console.WriteLine(IsValidXmlString(content)); // False

    content = RemoveInvalidXmlChars(content);
    Console.WriteLine(IsValidXmlString(content)); // True
}

static string RemoveInvalidXmlChars(string text) {
    var validXmlChars = text.Where(ch => XmlConvert.IsXmlChar(ch)).ToArray();
    return new string(validXmlChars);
}

static bool IsValidXmlString(string text) {
    try {
        XmlConvert.VerifyXmlChars(text);
        return true;
    } catch {
        return false;
    }
}

And as the way to escape invalid XML characters I suggest you to use XmlConvert.EncodeName method. Here is the small sample:

void Main() {
    const string content = "\v\f\0";
    Console.WriteLine(IsValidXmlString(content)); // False

    string encoded = XmlConvert.EncodeName(content);
    Console.WriteLine(IsValidXmlString(encoded)); // True

    string decoded = XmlConvert.DecodeName(encoded);
    Console.WriteLine(content == decoded); // True
}

static bool IsValidXmlString(string text) {
    try {
        XmlConvert.VerifyXmlChars(text);
        return true;
    } catch {
        return false;
    }
}

Update: It should be mentioned that the encoding operation produces a string with a length which is greater or equal than a length of a source string. It might be important when you store a encoded string in a database in a string column with length limitation and validate source string length in your app to fit data column limitation.

Return a string method in C#

Use x.fullNameMethod() to call the method.

Generator expressions vs. list comprehensions

When creating a generator from a mutable object (like a list) be aware that the generator will get evaluated on the state of the list at time of using the generator, not at time of the creation of the generator:

>>> mylist = ["a", "b", "c"]
>>> gen = (elem + "1" for elem in mylist)
>>> mylist.clear()
>>> for x in gen: print (x)
# nothing

If there is any chance of your list getting modified (or a mutable object inside that list) but you need the state at creation of the generator you need to use a list comprehension instead.

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

Appropriate datatype for holding percent values?

Assuming two decimal places on your percentages, the data type you use depends on how you plan to store your percentages. If you are going to store their fractional equivalent (e.g. 100.00% stored as 1.0000), I would store the data in a decimal(5,4) data type with a CHECK constraint that ensures that the values never exceed 1.0000 (assuming that is the cap) and never go below 0 (assuming that is the floor). If you are going to store their face value (e.g. 100.00% is stored as 100.00), then you should use decimal(5,2) with an appropriate CHECK constraint. Combined with a good column name, it makes it clear to other developers what the data is and how the data is stored in the column.

How to select specific form element in jQuery?

It isn't valid to have the same ID twice, that's why #name only finds the first one.

You can try:

$("#form2 input").val('Hello World!');

Or,

$("#form2 input[name=name]").val('Hello World!');

If you're stuck with an invalid page and want to select all #names, you can use the attribute selector on the id:

$("input[id=name]").val('Hello World!');

Fatal error: Maximum execution time of 30 seconds exceeded

I ran into this problem while upgrading to WordPress 4.0. By default WordPress limits the maximum execution time to 30 seconds.

Add the following code to your .htaccess file on your root directory of your WordPress Installation to over-ride the default.

php_value max_execution_time 300  //where 300 = 300 seconds = 5 minutes

Get the element triggering an onclick event in jquery?

You can pass the inline handler the this keyword, obtaining the element which fired the event.

like,

onclick="confirmSubmit(this);"

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

How to dynamically add elements to String array?

Arrays in Java have a defined size, you cannot change it later by adding or removing elements (you can read some basics here).

Instead, use a List:

ArrayList<String> mylist = new ArrayList<String>();
mylist.add(mystring); //this adds an element to the list.

Of course, if you know beforehand how many strings you are going to put in your array, you can create an array of that size and set the elements by using the correct position:

String[] myarray = new String[numberofstrings];
myarray[23] = string24; //this sets the 24'th (first index is 0) element to string24.

How to clear the cache of nginx?

In my case it was the enabled opcache in /etc/php/7.2/fpm/php.ini (Ubuntu):

opcache.enable=1

Setting it to 0 made the server loading the latest version of the (php)files.

Set title background color

Thanks for this clear explanation, however I would like to add a bit more to your answer by asking a linked question (don't really want to do a new post as this one is the basement on my question).

I'm declaring my titlebar in a Superclass from which, all my other activities are children, to have to change the color of the bar only once. I would like to also add an icon and change the text in the bar. I have done some testing, and managed to change either one or the other but not both at the same time (using setFeatureDrawable and setTitle). The ideal solution would be of course to follow the explanation in the thread given in the link, but as i'm declaring in a superclass, i have an issue due to the layout in setContentView and the R.id.myCustomBar, because if i remember well i can call setContentView only once...

EDIT Found my answer :

For those who, like me, like to work with superclasses because it's great for getting a menu available everywhere in an app, it works the same here.

Just add this to your superclass:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    setContentView(R.layout.customtitlebar);
    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.customtitlebar);
    customTitleText = (TextView) findViewById(R.id.customtitlebar);

(you have to declare the textview as protected class variable)

And then the power of this is that, everywhere in you app (if for instance all your activities are children of this class), you just have to call

customTitleText.setText("Whatever you want in title");

and your titlebar will be edited.

The XML associated in my case is (R.layout.customtitlebar) :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="@color/background">
<ImageView android:layout_width="25px" android:layout_height="25px"
    android:src="@drawable/icontitlebar"></ImageView>
<TextView android:id="@+id/customtitlebar"
    android:layout_width="wrap_content" android:layout_height="fill_parent"
    android:text="" android:textColor="@color/textcolor" android:textStyle="bold"
    android:background="@color/background" android:padding="3px" />
</LinearLayout>

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
 {
    std::cout << "Hello World\n";
 } 

HTML page disable copy/paste

You cannot prevent people from copying text from your page. If you are trying to satisfy a "requirement" this may work for you:

<body oncopy="return false" oncut="return false" onpaste="return false">

How to disable Ctrl C/V using javascript for both internet explorer and firefox browsers

A more advanced aproach:

How to detect Ctrl+V, Ctrl+C using JavaScript?

Edit: I just want to emphasise that disabling copy/paste is annoying, won't prevent copying and is 99% likely a bad idea.

Set default value of javascript object attributes

I saw an article yesterday that mentions an Object.__noSuchMethod__ property: JavascriptTips I've not had a chance to play around with it, so I don't know about browser support, but maybe you could use that in some way?

How to access the services from RESTful API in my angularjs page?

For instance your json looks like this : {"id":1,"content":"Hello, World!"}

You can access this thru angularjs like so:

angular.module('app', [])
    .controller('myApp', function($scope, $http) {
        $http.get('http://yourapp/api').
            then(function(response) {
                $scope.datafromapi = response.data;
            });
    });

Then on your html you would do it like this:

<!doctype html>
<html ng-app="myApp">
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="myApp">
            <p>The ID is {{datafromapi.id}}</p>
            <p>The content is {{datafromapi.content}}</p>
        </div>
    </body>
</html>

This calls the CDN for angularjs in case you don't want to download them.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>

Hope this helps.

Rolling or sliding window iterator?

I use the following code as a simple sliding window that uses generators to drastically increase readability. Its speed has so far been sufficient for use in bioinformatics sequence analysis in my experience.

I include it here because I didn't see this method used yet. Again, I make no claims about its compared performance.

def slidingWindow(sequence,winSize,step=1):
"""Returns a generator that will iterate through
the defined chunks of input sequence. Input sequence
must be sliceable."""

    # Verify the inputs
    if not ((type(winSize) == type(0)) and (type(step) == type(0))):
        raise Exception("**ERROR** type(winSize) and type(step) must be int.")
    if step > winSize:
        raise Exception("**ERROR** step must not be larger than winSize.")
    if winSize > len(sequence):
        raise Exception("**ERROR** winSize must not be larger than sequence length.")

    # Pre-compute number of chunks to emit
    numOfChunks = ((len(sequence)-winSize)/step)+1

    # Do the work
    for i in range(0,numOfChunks*step,step):
        yield sequence[i:i+winSize]

Run Command Line & Command From VBS

The problem is on this line:

oShell.run "cmd.exe /C copy "S:Claims\Sound.wav" "C:\WINDOWS\Media\Sound.wav"

Your first quote next to "S:Claims" ends the string; you need to escape the quotes around your files with a second quote, like this:

oShell.run "cmd.exe /C copy ""S:\Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

You also have a typo in S:Claims\Sound.wav, should be S:\Claims\Sound.wav.

I also assume the apostrophe before Dim oShell and after Set oShell = Nothing are typos as well.

ADB not recognising Nexus 4 under Windows 7

On Windows 7, with Samsung Nexus S, it showed nothing in Device Manager, the adb devices command showed no devices, but when plugged in device said USB debugging was on and connected.

I used Andrea's Feb 2 answer to install the Google USB driver, which created the /gooogle/usb_driver directory and used RobertNovelo's Mar 7 answer to go to the link and follow the instructions. The device showed up in Device Manager under 'other'. I right clicked on it and selected update driver, and now it shows up in Device Manager under 'Android device', and now command line adb devices lists it.

Difference between MongoDB and Mongoose

Mongoose is built untop of mongodb driver, the mongodb driver is more low level. Mongoose provides that easy abstraction to easily define a schema and query. But on the perfomance side Mongdb Driver is best.

How do I disable a Pylint warning?

I had this problem using Eclipse and solved it as follows:

In the pylint folder (e.g. C:\Python26\Lib\site-packages\pylint), hold Shift, right-click and choose to open the windows command in that folder. Type:

lint.py --generate-rcfile > standard.rc

This creates the standard.rc configuration file. Open it in Notepad and under [MESSAGES CONTROL], uncomment disable= and add the message ID's you want to disable, e.g.:

disable=W0511, C0321

Save the file, and in Eclipse ? Window ? Preferences ? PyDev ? *pylint, in the arguments box, type:

--rcfile=C:\Python26\Lib\site-packages\pylint\standard.rc

Now it should work...


You can also add a comment at the top of your code that will be interpreted by Pylint:

# pylint: disable=C0321

Pylint message codes.


Adding e.g. --disable-ids=C0321 in the arguments box does not work.

All available Pylint messages are stored in the dictionary _messages, an attribute of an instance of the pylint.utils.MessagesHandlerMixIn class. When running Pylint with the argument --disable-ids=... (at least without a configuration file), this dictionary is initially empty, raising a KeyError exception within Pylint (pylint.utils.MessagesHandlerMixIn.check_message_id().

In Eclipse, you can see this error-message in the Pylint Console (windows* ? show view ? Console, select Pylint console from the console options besides the console icon.)

Get the value of a dropdown in jQuery

If you're using a <select>, .val() gets the 'value' of the selected <option>. If it doesn't have a value, it may fallback to the id. Put the value you want it to return in the value attribute of each <option>

Edit: See comments for clarification on what value actually is (not necessarily equal to the value attribute).

Get Selected value from dropdown using JavaScript

The first thing i noticed is that you have a semi colon just after your closing bracket for your if statement );

You should also try and clean up your if statement by declaring a variable for the answer separately.

function answers() {

var select = document.getElementById("mySelect");
var answer = select.options[select.selectedIndex].value;

    if(answer == "To measure time"){
        alert("Thats correct"); 
    }

}

http://jsfiddle.net/zpdEp/

Does return stop a loop?

This code will exit the loop after the first iteration in a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
  if (iterator.name == 2) {
    return;
  }
  console.log(iterator.name);// 1
}

the below code will jump on the condition and continue on a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];

for (const iterator of objc) {
  if (iterator.name == 2) {
    continue;
  }
  console.log(iterator.name); // 1  , 3
}

How to set default Checked in checkbox ReactJS?

If someone wants to handle dynamic data with multiple rows, this is for handing dynamic data.

You can check if the rowId is equal to 0.

If it is equal to 0, then you can set the state of the boolean value as true.

interface MyCellRendererState {
    value: boolean;
}
constructor(props) {
        super(props);
        this.state = {
            value: props.value ? props.value : false
        };
        this.handleCheckboxChange = this.handleCheckboxChange.bind(this);
    }
handleCheckboxChange() {
        this.setState({ value: !this.state.value });
    };
render() {
        const { value } = this.state;
        const rowId = this.props.rowIndex
        if (rowId === 0) {
           this.state = {
             value : true }
        }
        return ( 
          <div onChange={this.handleCheckboxChange}>
            <input 
            type="radio" 
            checked={this.state.value}
            name="print"
            /> 
          </div>
         )
      }

Why is setState in reactjs Async instead of Sync?

You can use the following wrap to make sync call

_x000D_
_x000D_
this.setState((state =>{_x000D_
  return{_x000D_
    something_x000D_
  }_x000D_
})
_x000D_
_x000D_
_x000D_

A completely free agile software process tool

EDIT: Kanbanize is a commercial product and offers a 30 day free trial.

Disclosing: I am a co-founder of http://kanbanize.com/

Mark, I understand your desire to find the perfect application with all these features inside, but I really doubt that you will get it for free. There's a bunch of super cool apps (including Kanbanize) out there, but none of them is completely free.

Be careful what you call a Kanban board and what not, though. Trello is definitely NOT a kanban system (no WIP limits, no analytics, etc.). It is a great visual management system, but not a Kanban one.

Finally, to answer your question, tools that deserve attention in my opinion are: Kanbanize (of course), LeanKit, KanbanTool, Kanbanery and probably a few others. My personal bias is that LeanKit is the most advanced to date followed by Kanbanize and KanbanTool.

I hope that helps.

How to check edittext's text is email address or not?

On Android 2.2+ use this:

boolean isEmailValid(CharSequence email) {
   return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

for example:

EditText emailid = (EditText) loginView.findViewById(R.id.login_email);
String getEmailId = emailid.getText().toString();

// Check if email id is valid or not
       if (!isEmailValid(getEmailId)){
        new CustomToast().Show_Toast(getActivity(), loginView,
                "Your Email Id is Invalid.");
 }

'No JUnit tests found' in Eclipse

In Eclipse Photon you may need to add JUnit 4 or 5 to the build path. Right click @Test and select 'Add JUnit 4 to build path'.

jQuery Date Picker - disable past dates

you can simply use

startDate: 'today'

it working fine for me.

Wait .5 seconds before continuing code VB.net

Imports VB = Microsoft.VisualBasic

Public Sub wait(ByVal seconds As Single)
    Static start As Single
    start = VB.Timer()
    Do While VB.Timer() < start + seconds
        System.Windows.Forms.Application.DoEvents()
    Loop
End Sub

%20+ high cpu usage + no lag

Private Sub wait(ByVal seconds As Integer)
    For i As Integer = 0 To seconds * 100
        System.Threading.Thread.Sleep(10)
        Application.DoEvents()
    Next
End Sub

%0.1 cpu usage + high lag

LEFT JOIN only first row

@Matt Dodges answer put me on the right track. Thanks again for all the answers, which helped a lot of guys in the mean time. Got it working like this:

SELECT *
FROM feeds f
LEFT JOIN artists a ON a.artist_id = (
    SELECT artist_id
    FROM feeds_artists fa 
    WHERE fa.feed_id = f.id
    LIMIT 1
)
WHERE f.id = '13815'

How to present UIActionSheet iOS Swift?

You can use following code for Alert and Actionsheet for swift4

   @IBAction func alert_act(_ sender: Any) {

    do {


        let alert = UIAlertController(title: "Alert", message: "Would you like to continue learning?", preferredStyle: UIAlertController.Style.alert)

        alert.addAction(UIAlertAction(title: "No", style: UIAlertAction.Style.default, handler: nil))

          alert.addAction(UIAlertAction(title: "Yes", style: UIAlertAction.Style.default, handler: nil))


        self.present(alert, animated: true, completion: nil)


    }

  }


@IBAction func action_sheet1(_ sender: Any) {


    let action_sheet1 = UIAlertController(title: nil, message: "Alert message.", preferredStyle: .actionSheet)

    let defaultAction = UIAlertAction(title: "Default", style: .default, handler: nil)

    let deleteAction = UIAlertAction(title: "Delete", style: .destructive, handler: nil)

    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)



    action_sheet1.addAction(defaultAction)
    action_sheet1.addAction(deleteAction)
    action_sheet1.addAction(cancelAction)

    self.present(action_sheet1, animated: true, completion: nil)
}
    }

SVN commit command

To add a file/folder to the project, a good way is:

First of all add your files to /path/to/your/project/my/added/files, and then run following commands:

svn cleanup  /path/to/your/project

svn add --force /path/to/your/project/*

svn cleanup  /path/to/your/project

svn commit /path/to/your/project  -m 'Adding a file'

I used cleanup to prevent any segmentation fault (core dumped), and now the SVN project is updated.

How do I convert an interval into a number of hours with postgres?

         select date 'now()' - date '1955-12-15';

Here is the simple query which calculates total no of days.

Changing the JFrame title

these methods can help setTitle("your new title"); or super("your new title");

Which type of folder structure should be used with Angular 2?

The official guideline is there now. mgechev/angular2-seed had alignment with it too. see #857.

Angular 2 application structure

https://angular.io/guide/styleguide#overall-structural-guidelines

Why use getters and setters/accessors?

Well i just want to add that even if sometimes they are necessary for the encapsulation and security of your variables/objects, if we want to code a real Object Oriented Program, then we need to STOP OVERUSING THE ACCESSORS, cause sometimes we depend a lot on them when is not really necessary and that makes almost the same as if we put the variables public.

CASCADE DELETE just once

No. To do it just once you would simply write the delete statement for the table you want to cascade.

DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);
DELETE FROM some_table;

Get height of div with no height set in css

Can do this in jQuery. Try all options .height(), .innerHeight() or .outerHeight().

$('document').ready(function() {
    $('#right_div').css({'height': $('#left_div').innerHeight()});
});

Example Screenshot

enter image description here

Hope this helps. Thanks!!

How to create an empty DataFrame with a specified schema?

This is helpful for testing purposes.

Seq.empty[String].toDF()

CSS:Defining Styles for input elements inside a div

You can define style rules which only apply to specific elements inside your div with id divContainer like this:

#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */

How to add images in select list?

My solution is to use FontAwesome and then add library images as text! You just need the Unicodes and they are found here: FontAwesome Reference File forUnicodes

Here is an example state filter:

<select name='state' style='height: 45px; font-family:Arial, FontAwesome;'>
<option value=''>&#xf039; &nbsp; All States</option>
<option value='enabled' style='color:green;'>&#xf00c; &nbsp; Enabled</option>
<option value='paused' style='color:orange;'>&#xf04c; &nbsp; Paused</option>
<option value='archived' style='color:red;'>&#xf023; &nbsp; Archived</option>
</select>

Note the font-family:Arial, FontAwesome; is required to be assigned in style for select like given in the example!

Why XML-Serializable class need a parameterless constructor

During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.

You can make your constructor private or internal if you want, just so long as it's parameterless.

How to display the function, procedure, triggers source code in postgresql?

Here are few examples from PostgreSQL-9.5

Display list:

  1. Functions: \df+
  2. Triggers : \dy+

Display Definition:

postgres=# \sf
function name is required

postgres=# \sf pg_reload_conf()
CREATE OR REPLACE FUNCTION pg_catalog.pg_reload_conf()
 RETURNS boolean
 LANGUAGE internal
 STRICT
AS $function$pg_reload_conf$function$

postgres=# \sf pg_encoding_to_char
CREATE OR REPLACE FUNCTION pg_catalog.pg_encoding_to_char(integer)
 RETURNS name
 LANGUAGE internal
 STABLE STRICT
AS $function$PG_encoding_to_char$function$

The zip() function in Python 3

Unlike in Python 2, the zip function in Python 3 returns an iterator. Iterators can only be exhausted (by something like making a list out of them) once. The purpose of this is to save memory by only generating the elements of the iterator as you need them, rather than putting it all into memory at once. If you want to reuse your zipped object, just create a list out of it as you do in your second example, and then duplicate the list by something like

 test2 = list(zip(lis1,lis2))
 zipped_list = test2[:]
 zipped_list_2 = list(test2)

Vue is not defined

jsBin demo

  1. You missed the order, first goes:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.18/vue.min.js"></script>

and then:

<script>
    var demo = new Vue({
        el: '#demo',
        data: {
            message: 'Hello Vue.js!'
        }
    });
</script>
  1. And type="JavaScript" should be type="text/javascript" (or rather nothing at all)

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

You can use the following

new java.sql.Timestamp(System.currentTimeMillis()).getTime()

Result : 1539594988651

Hope this will help. Just my suggestion and not for reward points.

How do I debug Node.js applications?

Use Webstorm! It's perfect for debugging Node.js applications. It has a built-in debugger. Check out the docs here: https://www.jetbrains.com/help/webstorm/2016.1/running-and-debugging-node-js.html

How do I create a new column from the output of pandas groupby().sum()?

How do I create a new column with Groupby().Sum()?

There are two ways - one straightforward and the other slightly more interesting.


Everybody's Favorite: GroupBy.transform() with 'sum'

@Ed Chum's answer can be simplified, a bit. Call DataFrame.groupby rather than Series.groupby. This results in simpler syntax.

# The setup.
df[['Date', 'Data3']]

         Date  Data3
0  2015-05-08      5
1  2015-05-07      8
2  2015-05-06      6
3  2015-05-05      1
4  2015-05-08     50
5  2015-05-07    100
6  2015-05-06     60
7  2015-05-05    120

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64 

It's a tad faster,

df2 = pd.concat([df] * 12345)

%timeit df2['Data3'].groupby(df['Date']).transform('sum')
%timeit df2.groupby('Date')['Data3'].transform('sum')

10.4 ms ± 367 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
8.58 ms ± 559 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

Unconventional, but Worth your Consideration: GroupBy.sum() + Series.map()

I stumbled upon an interesting idiosyncrasy in the API. From what I tell, you can reproduce this on any major version over 0.20 (I tested this on 0.23 and 0.24). It seems like you consistently can shave off a few milliseconds of the time taken by transform if you instead use a direct function of GroupBy and broadcast it using map:

df.Date.map(df.groupby('Date')['Data3'].sum())

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Date, dtype: int64

Compare with

df.groupby('Date')['Data3'].transform('sum')

0     55
1    108
2     66
3    121
4     55
5    108
6     66
7    121
Name: Data3, dtype: int64

My tests show that map is a bit faster if you can afford to use the direct GroupBy function (such as mean, min, max, first, etc). It is more or less faster for most general situations upto around ~200 thousand records. After that, the performance really depends on the data.

(Left: v0.23, Right: v0.24)

Nice alternative to know, and better if you have smaller frames with smaller numbers of groups. . . but I would recommend transform as a first choice. Thought this was worth sharing anyway.

Benchmarking code, for reference:

import perfplot

perfplot.show(
    setup=lambda n: pd.DataFrame({'A': np.random.choice(n//10, n), 'B': np.ones(n)}),
    kernels=[
        lambda df: df.groupby('A')['B'].transform('sum'),
        lambda df:  df.A.map(df.groupby('A')['B'].sum()),
    ],
    labels=['GroupBy.transform', 'GroupBy.sum + map'],
    n_range=[2**k for k in range(5, 20)],
    xlabel='N',
    logy=True,
    logx=True
)

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

your google-services.json package name must match your build.gradle applicationId (applicationId "your package name")

How to determine if binary tree is balanced?

Wouldn't this work?

return ( ( Math.abs( size( root.left ) - size( root.right ) ) < 2 );

Any unbalanced tree would always fail this.

React Native add bold or italics to single words in <Text> field

You could just nest the Text components with the required style. The style will be applied along with already defined style in the first Text component.

Example:

 <Text style={styles.paragraph}>
   Trouble singing in. <Text style={{fontWeight: "bold"}}> Resolve</Text>
 </Text>

How to make an image center (vertically & horizontally) inside a bigger div

I had this issue in HTML5 using CSS3 and my image was centered as such within the DIV... oh yes, I can't forget how I had to add the height to show the image... for a while I wondered where it was until I did this. I don't think the position and display are necessary.

background-image: url('../Images/01.png');    
background-repeat:no-repeat;
background-position:center;
position:relative;
display:block;
height:60px;

How to configure log4j with a properties file

You can enable log4j internal logging by defining the 'log4j.debug' variable.

adb is not recognized as internal or external command on windows

If you get your adb from Android Studio (which most will nowadays since Android is deprecated on Eclipse), your adb program will most likely be located here:

%USERPROFILE%\AppData\Local\Android\sdk\platform-tools

Where %USERPROFILE% represents something like C:\Users\yourName.

If you go into your computer's environmental variables and add %USERPROFILE%\AppData\Local\Android\sdk\platform-tools to the PATH (just copy-paste that line, even with the % --- it will work fine, at least on Windows, you don't need to hardcode your username) then it should work now. Open a new command prompt and type adb to check.

Difference between single and double quotes in Bash

Others explained very well and just want to give with simple examples.

Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.' 

It will give this:

All sorts of things are ignored in single quotes, like $ & * ; |.

The only thing that cannot be put within single quotes is a single quote.

Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.

$ echo "Here's how we can use single ' and double \" quotes within double quotes"

It will give this:

Here's how we can use single ' and double " quotes within double quotes

It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.

$ echo "The current Oracle SID is $ORACLE_SID"

It will give this:

The current Oracle SID is test

Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.

$ today=`date '+%A, %B %d, %Y'`
$ echo $today 

It will give this:

Monday, September 28, 2015 

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

Please Try, if use "extends AppCompatActivity" and present actionbar.

 ActionBar eksinbar=getSupportActionBar();
if (eksinbar != null) {
    eksinbar.setDisplayHomeAsUpEnabled(true);
    eksinbar.setHomeAsUpIndicator(R.mipmap.imagexxx);
}

Unresponsive KeyListener for JFrame

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:

myComponent.setFocusable(true);

Distribution certificate / private key not installed

If you are being stuck on this problem. After switch the computer and not able to upload your build to App Store. Simply click manage certificate on the error page, the + plus on the bottom left corner and create a new distribution certificate. Then you'll be good to go.

Limit file format when using <input type="file">?

You can use "accept" attribute as a filter in the file select box. Using "accept" help you filter input files base on their "suffix" or their "meme type"

1.Filter based on suffix: Here "accept" attribute just allow to select files with .jpeg extension.

<input type="file" accept=".jpeg" />

2.Filter based on "file type" Here "accept" attribute just allow to select file with "image/jpeg" type.

<input type="file" accept="image/jpeg" />

Important: We can change or delete the extension of a file, without changing the meme type. For example it is possible to have a file without extension, but the type of this file can be "image/jpeg". So this file can not pass the accept=".jpeg" filter. but it can pass accept="image/jpeg".

3.We can use * to select all kind of a file type. For example below code allow to select all kind of images. for example "image/png" or "image/jpeg" or ... . All of them are allowed.

<input type="file" accept="image/*" /> 

4.We can use cama ( , ) as an "or operator" in select attribute. For example to allow all kind of images or pdf files we can use this code:

<input type="file" accept="image/* , application/pdf" />

How to round up integer division and have int result in Java?

If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b

Git: How to commit a manually deleted file?

The answer's here, I think.

It's better if you do git rm <fileName>, though.

Are "while(true)" loops so bad?

It's your gun, your bullet and your foot...

It's bad because you are asking for trouble. It won't be you or any of the other posters on this page who have examples of short/simple while loops.

The trouble will start at some very random time in the future. It might be caused by another programmer. It might be the person installing the software. It might be the end user.

Why? I had to find out why a 700K LOC app would gradually start burning 100% of the CPU time until every CPU was saturated. It was an amazing while (true) loop. It was big and nasty but it boiled down to:

x = read_value_from_database()
while (true) 
 if (x == 1)
  ...
  break;
 else if (x ==2)
  ...
  break;
and lots more else if conditions
}

There was no final else branch. If the value did not match an if condition the loop kept running until the end of time.

Of course, the programmer blamed the end users for not picking a value the programmer expected. (I then eliminated all instances of while(true) in the code.)

IMHO it is not good defensive programming to use constructs like while(true). It will come back to haunt you.

(But I do recall professors grading down if we did not comment every line, even for i++;)

How to get a value from a cell of a dataframe?

For pandas 0.10, where iloc is unavalable, filter a DF and get the first row data for the column VALUE:

df_filt = df[df['C1'] == C1val & df['C2'] == C2val]
result = df_filt.get_value(df_filt.index[0],'VALUE')

if there is more then 1 row filtered, obtain the first row value. There will be an exception if the filter result in empty data frame.

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

How can I get the application's path in a .NET console application?

I mean, why not a p/invoke method?

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    public class AppInfo
    {
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
            private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
            private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
            public static string StartupPath
            {
                get
                {
                    StringBuilder stringBuilder = new StringBuilder(260);
                    GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
                    return Path.GetDirectoryName(stringBuilder.ToString());
                }
            }
    }

You would use it just like the Application.StartupPath:

    Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

How to get the nth element of a python list or a default if not available

try:
   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError - probably better to let the caller handle this.

Handling optional parameters in javascript

You can know how many arguments were passed to your function and you can check if your second argument is a function or not:

function getData (id, parameters, callback) {
  if (arguments.length == 2) { // if only two arguments were supplied
    if (Object.prototype.toString.call(parameters) == "[object Function]") {
      callback = parameters; 
    }
  }
  //...
}

You can also use the arguments object in this way:

function getData (/*id, parameters, callback*/) {
  var id = arguments[0], parameters, callback;

  if (arguments.length == 2) { // only two arguments supplied
    if (Object.prototype.toString.call(arguments[1]) == "[object Function]") {
      callback = arguments[1]; // if is a function, set as 'callback'
    } else {
      parameters = arguments[1]; // if not a function, set as 'parameters'
    }
  } else if (arguments.length == 3) { // three arguments supplied
      parameters = arguments[1];
      callback = arguments[2];
  }
  //...
}

If you are interested, give a look to this article by John Resig, about a technique to simulate method overloading on JavaScript.

jQuery fade out then fade in

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require

What is the difference between call and apply?

Difference between these to methods are, how you want to pass the parameters.

“A for array and C for comma” is a handy mnemonic.

What are the safe characters for making URLs?

There are two sets of characters you need to watch out for: reserved and unsafe.

The reserved characters are:

  • ampersand ("&")
  • dollar ("$")
  • plus sign ("+")
  • comma (",")
  • forward slash ("/")
  • colon (":")
  • semi-colon (";")
  • equals ("=")
  • question mark ("?")
  • 'At' symbol ("@")
  • pound ("#").

The characters generally considered unsafe are:

  • space (" ")
  • less than and greater than ("<>")
  • open and close brackets ("[]")
  • open and close braces ("{}")
  • pipe ("|")
  • backslash ("")
  • caret ("^")
  • percent ("%")

I may have forgotten one or more, which leads to me echoing Carl V's answer. In the long run you are probably better off using a "white list" of allowed characters and then encoding the string rather than trying to stay abreast of characters that are disallowed by servers and systems.

How do I vertically align text in a div?

This is another variation of the div in a div pattern using calc() in CSS.

<div style="height:300px; border:1px solid green;">
  Text in outer div.
  <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)">
    Text in inner div.
  </div>
</div>

This works, because:

  • position:absolute for precise placement of the div within a div
  • we know the height of the inner div because we set it to 20px.
  • calc(50% - 10px) for 50% - half the height for centering the inner div

How to do a regular expression replace in MySQL?

If you are using MariaDB or MySQL 8.0, they have a function

REGEXP_REPLACE(col, regexp, replace)

See MariaDB docs and PCRE Regular expression enhancements

Note that you can use regexp grouping as well (I found that very useful):

SELECT REGEXP_REPLACE("stackoverflow", "(stack)(over)(flow)", '\\2 - \\1 - \\3')

returns

over - stack - flow

Remove part of a string

Here's the strsplit solution if s is a vector:

> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"

How to have Android Service communicate with Activity

I am surprised that no one has given reference to Otto event Bus library

http://square.github.io/otto/

I have been using this in my android apps and it works seamlessly.

How do I select between the 1st day of the current month and current day in MySQL?

I was looking for a similar query where I needed to use the first day of a month in my query. The last_day function didn't work for me but DAYOFMONTH came in handy.

So if anyone is looking for the same issue, the following code returns the date for first day of the current month.

SELECT DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY);

Comparing a date column with the first day of the month :

select * from table_name where date between 
DATE_SUB(CURRENT_DATE, INTERVAL DAYOFMONTH(CURRENT_DATE)-1 DAY) and CURRENT_DATE

Take screenshots in the iOS simulator

  1. Focus simulator
  2. Go to menu File->Save Screen Shot

    or

    Press ?+S

Screen shot saves in desktop

How to set a default value in react-select

I'm using frequently something like this.

Default value from props in this example

if(Defaultvalue ===item.value) {
    return <option key={item.key} defaultValue value={item.value}>{plantel.value} </option>   
} else {
    return <option key={item.key} value={item.value}>{plantel.value} </option> 
}

No String-argument constructor/factory method to deserialize from String value ('')

Use below code snippet This worked for me

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});

Model Class

@JsonIgnoreProperties    public class Symbol {
    @JsonProperty("symbol")
    private String symbol;
}

How to reload the current route with the angular 2 router

Found a quick and straight-forward solution that doesn't require to tinker with the inner workings of angular:

Basically: Just create an alternate route with the same destination module and just toggle between them:

const routes: Routes = [
  {
    path: 'gesuch',
    loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
  },
  {
    path: 'gesuch-neu',
    loadChildren: './sections/gesuch/gesuch.module#GesuchModule'
  }
];

And here the toggeling menu:

<ul class="navigation">
    <li routerLink="/gesuch-neu" *ngIf="'gesuch' === getSection()">Gesuch</li>
    <li routerLink="/gesuch" *ngIf="'gesuch' !== getSection()">Gesuch</li>
</ul>

Hope it helps :)

Hash table runtime complexity (insert, search and delete)

Some hash tables (cuckoo hashing) have guaranteed O(1) lookup

ASP.NET Button to redirect to another page

<button type ="button" onclick="location.href='@Url.Action("viewname","Controllername")'"> Button name</button>

for e.g ,

<button type="button" onclick="location.href='@Url.Action("register","Home")'">Register</button>

How to get streaming url from online streaming radio station

Edited ZygD's answer for python 3.x.:

import re
import urllib.request
import string
url1 = input("Please enter a URL from Tunein Radio: ");
request = urllib.request.Request(url1);
response = urllib.request.urlopen(request);
raw_file = response.read().decode('utf-8');
API_key = re.findall(r"StreamUrl\":\"(.*?),\"",raw_file);
#print API_key;
#print "The API key is: " + API_key[0];
request2 = urllib.request.Request(str(API_key[0]));
response2 = urllib.request.urlopen(request2);
key_content = response2.read().decode('utf-8');
raw_stream_url = re.findall(r"Url\": \"(.*?)\"",key_content);
bandwidth = re.findall(r"Bandwidth\":(.*?),", key_content);
reliability = re.findall(r"lity\":(.*?),", key_content);
isPlaylist = re.findall(r"HasPlaylist\":(.*?),",key_content);
codec = re.findall(r"MediaType\": \"(.*?)\",", key_content);
tipe = re.findall(r"Type\": \"(.*?)\"", key_content);
total = 0
for element in raw_stream_url:
    total = total + 1
i = 0
print ("I found " + str(total) + " streams.");
for element in raw_stream_url:
    print ("Stream #" + str(i + 1));
    print ("Stream stats:");
    print ("Bandwidth: " + str(bandwidth[i]) + " kilobytes per second.");
    print ("Reliability: " + str(reliability[i]) + "%");
    print ("HasPlaylist: " + str(isPlaylist[i]));
    print ("Stream codec: " + str(codec[i]));
    print ("This audio stream is " + tipe[i].lower());
    print ("Pure streaming URL: " + str(raw_stream_url[i]));
i = i + 1
input("Press enter to close")

How to create a release signed apk file using Gradle?

For Kotlin Script (build.gradle.kts)

You should not put your signing credentials directly in the build.gradle.kts file. Instead the credentials should come from a file not under version control.

Put a file signing.properties where the module specific build.gradle.kts is found. Don't forget to add it to your .gitignore file!

signing.properties

storeFilePath=/home/willi/example.keystore
storePassword=secret
keyPassword=secret
keyAlias=myReleaseSigningKey

build.gradle.kts

android {
    // ...
    signingConfigs {
        create("release") {
            val properties = Properties().apply {
                load(File("signing.properties").reader())
            }
            storeFile = File(properties.getProperty("storeFilePath"))
            storePassword = properties.getProperty("storePassword")
            keyPassword = properties.getProperty("keyPassword")
            keyAlias = "release"
        }
    }

    buildTypes {
        getByName("release") {
            signingConfig = signingConfigs.getByName("release")
            // ...
        }
    }
}

How to check if mysql database exists

A very simple BASH-one-liner:

mysqlshow | grep dbname

Windows batch file file download from a URL

This should work i did the following for a game server project. It will download the zip and extract it to what ever directory you specify.

Save as name.bat or name.cmd

@echo off
set downloadurl=http://media.steampowered.com/installer/steamcmd.zip
set downloadpath=C:\steamcmd\steamcmd.zip
set directory=C:\steamcmd\
%WINDIR%\System32\WindowsPowerShell\v1.0\powershell.exe -Command "& {Import-Module BitsTransfer;Start-BitsTransfer '%downloadurl%' '%downloadpath%';$shell = new-object -com shell.application;$zip = $shell.NameSpace('%downloadpath%');foreach($item in $zip.items()){$shell.Namespace('%directory%').copyhere($item);};remove-item '%downloadpath%';}"
echo download complete and extracted to the directory.
pause

Original : https://github.com/C0nw0nk/SteamCMD-AutoUpdate-Any-Gameserver/blob/master/steam.cmd

Powershell: count members of a AD group

Something I'd like to share..

$adinfo.members actually give twice the number of actual members. $adinfo.member (without the "s") returns the correct amount. Even when dumping $adinfo.members & $adinfo.member to screen outputs the lower amount of members.

No idea how to explain this!

how to set active class to nav menu from twitter bootstrap

For those using Codeigniter, add this below your sidebar menu,

<script>
    $(document).ready(function () {
        $(".nav li").removeClass("active");
        var currentUrl = "<?php  echo current_url();  ?>";
        $('a[href="' + currentUrl + '"]').parents('li,ul').addClass('active');
    });
</script>

Why is the jquery script not working?

<script type="text/javascript" >
    do your codes here  it will work..
    type="text/javascript" is important for jquery 
<script>

How to use the DropDownList's SelectedIndexChanged event

The most basic way you can do this in SelectedIndexChanged events of DropDownLists. Check this code..

    <asp:DropDownList ID="DropDownList1" runat="server" onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="224px"
        AutoPostBack="True" AppendDataBoundItems="true">
    <asp:DropDownList ID="DropDownList2" runat="server"
        onselectedindexchanged="DropDownList2_SelectedIndexChanged">
    </asp:DropDownList> 


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList2

}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
    //Load DropDownList3
}

How can I add a custom HTTP header to ajax request with js or jQuery?

You can use js fetch

_x000D_
_x000D_
async function send(url,data) {_x000D_
  let r= await fetch(url, {_x000D_
        method: "POST", _x000D_
        headers: {_x000D_
          "My-header": "abc"  _x000D_
        },_x000D_
        body: JSON.stringify(data), _x000D_
  })_x000D_
  return await r.json()_x000D_
}_x000D_
_x000D_
// Example usage_x000D_
_x000D_
let url='https://server.test-cors.org/server?enable=true&status=200&methods=POST&headers=my-header';_x000D_
_x000D_
async function run() _x000D_
{_x000D_
 let jsonObj = await send(url,{ some: 'testdata' });_x000D_
 console.log(jsonObj[0].request.httpMethod + ' was send - open chrome console > network to see it');_x000D_
}_x000D_
_x000D_
run();
_x000D_
_x000D_
_x000D_

how to run two commands in sudo?

I usually do:

sudo bash -c 'whoami; whoami'

How to dismiss the dialog with click on outside of the dialog?

Another solution, this code was taken from android source code of Window You should just add these Two methods to your dialog source code.

@Override
public boolean onTouchEvent(MotionEvent event) {        
    if (isShowing() && (event.getAction() == MotionEvent.ACTION_DOWN
            && isOutOfBounds(getContext(), event) && getWindow().peekDecorView() != null)) {
        hide();
    }
    return false;
}

private boolean isOutOfBounds(Context context, MotionEvent event) {
    final int x = (int) event.getX();
    final int y = (int) event.getY();
    final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
    final View decorView = getWindow().getDecorView();
    return (x < -slop) || (y < -slop)
            || (x > (decorView.getWidth()+slop))
            || (y > (decorView.getHeight()+slop));
}

This solution doesnt have this problem :

This works great except that the activity underneath also reacts to the touch event. Is there some way to prevent this? – howettl

How to ensure a <select> form field is submitted when it is disabled?

I was faced with a slightly different scenario, in that I only wanted to not allow the user to change the selected value based on an earlier selectbox. What I ended up doing was just disabling all the other non-selected options in the selectbox using

$('#toSelect')find(':not(:selected)').prop('disabled',true);

java.util.NoSuchElementException - Scanner reading user input

This has really puzzled me for a while but this is what I found in the end.

When you call, sc.close() in first method, it not only closes your scanner but closes your System.in input stream as well. You can verify it by printing its status at very top of the second method as :

    System.out.println(System.in.available());

So, now when you re-instantiate, Scanner in second method, it doesn't find any open System.in stream and hence the exception.

I doubt if there is any way out to reopen System.in because:

public void close() throws IOException --> Closes this input stream and releases any system resources associated with this stream. The general contract of close is that it closes the input stream. A closed stream cannot perform input operations and **cannot be reopened.**

The only good solution for your problem is to initiate the Scanner in your main method, pass that as argument in your two methods, and close it again in your main method e.g.:

main method related code block:

Scanner scanner = new Scanner(System.in);  

// Ask users for quantities 
PromptCustomerQty(customer, ProductList, scanner );

// Ask user for payment method
PromptCustomerPayment(customer, scanner );

//close the scanner 
scanner.close();

Your Methods:

 public static void PromptCustomerQty(Customer customer, 
                             ArrayList<Product> ProductList, Scanner scanner) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }


 public static void PromptCustomerPayment (Customer customer, Scanner sc) {

    // no more scanner instantiation
    ...
    // no more scanner close
 }

Hope this gives you some insight about the failure and possible resolution.

What is a MIME type?

MIME stands for Multi-purpose Internet Mail Extensions. MIME types form a standard way of classifying file types on the Internet. Internet programs such as Web servers and browsers all have a list of MIME types, so that they can transfer files of the same type in the same way, no matter what operating system they are working in.

A MIME type has two parts: a type and a subtype. They are separated by a slash (/). For example, the MIME type for Microsoft Word files is application and the subtype is msword. Together, the complete MIME type is application/msword.

Although there is a complete list of MIME types, it does not list the extensions associated with the files, nor a description of the file type. This means that if you want to find the MIME type for a certain kind of file, it can be difficult. Sometimes you have to look through the list and make a guess as to the MIME type of the file you are concerned with.

Hashcode and Equals for Hashset

  1. There's no need to call equals if hashCode differs.
  2. There's no need to call hashCode if (obj1 == obj2).
  3. There's no need for hashCode and/or equals just to iterate - you're not comparing objects
  4. When needed to distinguish in between objects.

How to printf long long

%lld is the standard C99 way, but that doesn't work on the compiler that I'm using (mingw32-gcc v4.6.0). The way to do it on this compiler is: %I64d

So try this:

if(e%n==0)printf("%15I64d -> %1.16I64d\n",e, 4*pi);

and

scanf("%I64d", &n);

The only way I know of for doing this in a completely portable way is to use the defines in <inttypes.h>.

In your case, it would look like this:

scanf("%"SCNd64"", &n);
//...    
if(e%n==0)printf("%15"PRId64" -> %1.16"PRId64"\n",e, 4*pi);

It really is very ugly... but at least it is portable.

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Have them create a testflightapp.com account.

This is very useful for beta testing - which I'm guessing is what you need the udids for.

You can send them a download link to your app (found in the permissions tap at the bottom of the page) and it will tell them their udid hasn't been validated yet. It will then tell them their udid! They can copy and paste this and text it to you.

Is div inside list allowed?

I'm starting in the webdesign universe and i used DIVs inside LIs with no problem with the semantics. I think that DIVs aren't allowed on lists, that means you can't put a DIV inside an UL, but it has no problem inserting it on a LI (because LI are just list items haha) The problem that i have been encountering is that sometimes the DIV behaves somewhat different from usual, but nothing that our good CSS can't handle haha. Anyway, sorry for my bad english and if my response wasn't helpful haha good luck!

How to set a CheckBox by default Checked in ASP.Net MVC

An alternative solution is using jQuery:

    <script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            PrepareCheckbox();
        });
        function PrepareCheckbox(){
            document.getElementById("checkbox").checked = true;
        }
    </script>

Prevent form submission on Enter key press

Using TypeScript, and avoid multiples calls on the function

let el1= <HTMLInputElement>document.getElementById('searchUser');
el1.onkeypress = SearchListEnter;

function SearchListEnter(event: KeyboardEvent) {
    if (event.which !== 13) {
        return;
    }
    // more stuff
}

What is the difference between a var and val definition in Scala?

val means immutable and var means mutable

you can think val as java programming language final key world or c++ language const key world?

How to read xml file contents in jQuery and display in html elements?

Get the XML using Ajax call, find the main element, loop through all the element and append data in table.

Sample code

 //ajax call to load XML and parse it
        $.ajax({
            type: 'GET',
            url: 'https://res.cloudinary.com/dmsxwwfb5/raw/upload/v1591716537/book.xml',           // The file path.
            dataType: 'xml',    
            success: function(xml) {
               //find all book tags, loop them and append to table body
                $(xml).find('book').each(function() {
                    
                    // Append new data to the tbody element.
                    $('#tableBody').append(
                        '<tr>' +
                            '<td>' +
                                $(this).find('author').text() + '</td> ' +
                            '<td>' +
                                $(this).find('title').text() + '</td> ' +
                            '<td>' +
                                $(this).find('genre').text() + '</td> ' +
                                '<td>' +
                                $(this).find('price').text() + '</td> ' +
                                '<td>' +
                                $(this).find('description').text() + '</td> ' +
                        '</tr>');
                });
            }
        });

Fiddle link: https://jsfiddle.net/pn9xs8hf/2/

Source: Read XML using jQuery & load it in HTML Table

insert/delete/update trigger in SQL server

the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
                    EmpID int,
                    Activity varchar(20),
                    DoneBy varchar(50),
                    Date_Time datetime NOT NULL DEFAULT GETDATE()
                   );

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
    SET @activity = 'UPDATE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SET @activity = 'INSERT';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin 
    SET @activity = 'DELETE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from deleted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

How to detect Esc Key Press in React and how to handle it

Another way to accomplish this in a functional component, is to use useEffect and useFunction, like this:

import React, { useEffect } from 'react';

const App = () => {


  useEffect(() => {
    const handleEsc = (event) => {
       if (event.keyCode === 27) {
        console.log('Close')
      }
    };
    window.addEventListener('keydown', handleEsc);

    return () => {
      window.removeEventListener('keydown', handleEsc);
    };
  }, []);

  return(<p>Press ESC to console log "Close"</p>);
}

Instead of console.log, you can use useState to trigger something.

LOAD DATA INFILE Error Code : 13

CentOS 7+ Minimal Secure Solution: (should work with RedHat too)

chcon -Rv --type=mysqld_db_t /YOUR/PATH/

Explanation:

Knowing that you applied the good practice of using secure-file-priv=/YOUR/PATH/ in my.cnf in order to use load data infile sql statement, you still see the following:

ERROR 13 (HY000): Can't get stat of '/YOUR/PATH/FILE.EXT' (Errcode: 13 "Permission denied")

That's caused by SELinux Enforcing mode, it's not secure to change the mode to Permissive or disable SELinux.
In short,

chcon change SELinux security context of a file or files/directories in a similar way to how 'chown' or 'chmod' may be used to change the ownership or standard file permissions of a file.

SELinux Enforcing mode prevents mysqld from accessing directories with secure-context-type default_t, hence we need to change the secure-context-type of our path to mysqld_db_t. To see the current secure-context-type use the command:

ls --directory --scontext /YOUR/PATH/

In case you want to reset/undo the solution, then apply below command:

restorecon -Rv /YOUR/PATH/

The solution I shared is referenced in below links:

https://wiki.centos.org/HowTos/SELinux
https://mariadb.com/kb/en/selinux/
https://linux.die.net/man/8/mysqld_selinux

getaddrinfo: nodename nor servname provided, or not known

rest-client's RestClient needs the http: scheme when resolving the URL. It calls Net::HTTP for you, which doesn't want the http: part, but rest-client takes care of that.

Is the URL the actual one you are attempting to reach? example.org is a valid domain used for testing and documentation and is reachable; I'd expect the "api" and "api_endpoint" parts to fail and see that when I try to reach them.

require 'socket'

IPSocket.getaddress('example.org') # => "2620:0:2d0:200::10"
IPSocket.getaddress('api.example.org') # => 
# ~> -:7:in `getaddress': getaddrinfo: nodename nor servname provided, or not known (SocketError)
# ~>    from -:7:in `<main>'

Here's what I get using Curl:

greg-mbp-wireless:~ greg$ curl api.example.org/api_endpoint
curl: (6) Couldn't resolve host 'api.example.org'
greg-mbp-wireless:~ greg$ curl example.org/api_endpoint
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>404 Not Found</title>
</head><body>
<h1>Not Found</h1>
<p>The requested URL /api_endpoint was not found on this server.</p>
<hr>
<address>Apache Server at example.org Port 80</address>
</body></html>
greg-mbp-wireless:~ greg$ curl example.org
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
  <META http-equiv="Content-Type" content="text/html; charset=utf-8">
  <TITLE>Example Web Page</TITLE>
</HEAD> 
<body>  
<p>You have reached this web page by typing &quot;example.com&quot;,
&quot;example.net&quot;,&quot;example.org&quot
  or &quot;example.edu&quot; into your web browser.</p>
<p>These domain names are reserved for use in documentation and are not available 
  for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 
  2606</a>, Section 3.</p>
</BODY>
</HTML>

Shell - Write variable contents to a file

Use the echo command:

var="text to append";
destdir=/some/directory/path/filename

if [ -f "$destdir" ]
then 
    echo "$var" > "$destdir"
fi

The if tests that $destdir represents a file.

The > appends the text after truncating the file. If you only want to append the text in $var to the file existing contents, then use >> instead:

echo "$var" >> "$destdir"

The cp command is used for copying files (to files), not for writing text to a file.

How to wrap text around an image using HTML/CSS

you have to float your image container as follows:

HTML

<div id="container">
    <div id="floated">...some other random text</div>
    ...
    some random text
    ...
</div>

CSS

#container{
    width: 400px;
    background: yellow;
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

FIDDLE

http://jsfiddle.net/kYDgL/

Auto-redirect to another HTML page

One of these will work...

_x000D_
_x000D_
<head>_x000D_
  <meta http-equiv='refresh' content='0; URL=http://example.com/'>_x000D_
</head>
_x000D_
_x000D_
_x000D_

...or it can done with JavaScript:

_x000D_
_x000D_
window.location.href = 'https://example.com/';
_x000D_
_x000D_
_x000D_

Best way to copy a database (SQL Server 2008)

Easiest way is actually a script.

Run this on production:

USE MASTER;

BACKUP DATABASE [MyDatabase]
TO DISK = 'C:\temp\MyDatabase1.bak' -- some writeable folder. 
WITH COPY_ONLY

This one command makes a complete backup copy of the database onto a single file, without interfering with production availability or backup schedule, etc.

To restore, just run this on your dev or test SQL Server:

USE MASTER;

RESTORE DATABASE [MyDatabase]
FROM DISK = 'C:\temp\MyDatabase1.bak'
WITH
MOVE 'MyDatabase'   TO 'C:\Sql\MyDatabase.mdf', -- or wherever these live on target
MOVE 'MyDatabase_log'   TO 'C:\Sql\MyDatabase_log.ldf',
REPLACE, RECOVERY

Then save these scripts on each server. One-click convenience.

Edit:
if you get an error when restoring that the logical names don't match, you can get them like this:

RESTORE FILELISTONLY
FROM disk = 'C:\temp\MyDatabaseName1.bak'

If you use SQL Server logins (not windows authentication) you can run this after restoring each time (on the dev/test machine):

use MyDatabaseName;
sp_change_users_login 'Auto_Fix', 'userloginname', null, 'userpassword';

How do I turn a C# object into a JSON string in .NET?

Use Json.Net library, you can download it from Nuget Packet Manager.

Serializing to Json String:

 var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

Deserializing to Object:

var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

Postgres hasn't implemented an equivalent to INSERT OR REPLACE. From the ON CONFLICT docs (emphasis mine):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

Though it doesn't give you shorthand for replacement, ON CONFLICT DO UPDATE applies more generally, since it lets you set new values based on preexisting data. For example:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;

MongoDB - Update objects in a document's array (nested updating)

For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:

 db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.

The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:

 db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:

db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
               {$inc : {total : 1 , "items.$.price" : 1}} ,
               false ,
               true);

Locating child nodes of WebElements in selenium

The toString() method of Selenium's By-Class produces something like "By.xpath: //XpathFoo"

So you could take a substring starting at the colon with something like this:

String selector = divA.toString().substring(s.indexOf(":") + 2);

With this, you could find your element inside your other element with this:

WebElement input = driver.findElement( By.xpath( selector + "//input" ) );

Advantage: You have to search only once on the actual SUT, so it could give you a bonus in performance.

Disadvantage: Ugly... if you want to search for the parent element with css selectory and use xpath for it's childs, you have to check for types before you concatenate... In this case, Slanec's solution (using findElement on a WebElement) is much better.

Save matplotlib file to a directory

In addition to the answers already given, if you want to create a new directory, you could use this function:

def mkdir_p(mypath):
    '''Creates a directory. equivalent to using mkdir -p on the command line'''

    from errno import EEXIST
    from os import makedirs,path

    try:
        makedirs(mypath)
    except OSError as exc: # Python >2.5
        if exc.errno == EEXIST and path.isdir(mypath):
            pass
        else: raise

and then:

import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(100))

# Create new directory
output_dir = "some/new/directory"
mkdir_p(output_dir)

fig.savefig('{}/graph.png'.format(output_dir))

How to use Comparator in Java to sort

For the sake of completeness.

Using Java8

people.sort(Comparator.comparingInt(People::getId));

if you want in descending order

people.sort(Comparator.comparingInt(People::getId).reversed());

What's the difference between Visual Studio Community and other, paid versions?

All these answers are partially wrong.

Microsoft has clarified that Community is for ANY USE as long as your revenue is under $1 Million US dollars. That is literally the only difference between Pro and Community. Corporate or free or not, irrelevant.

Even the lack of TFS support is not true. I can verify it is present and works perfectly.

EDIT: Here is an MSDN post regarding the $1M limit: MSDN (hint: it's in the VS 2017 license)

EDIT: Even over the revenue limit, open source is still free.

Best way to convert string to bytes in Python 3?

It's easier than it is thought:

my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
type(my_str_as_bytes) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
type(my_decoded_str) # ensure it is string representation

'Missing contentDescription attribute on image' in XML

The warning is indeed annoying and in many (most!) cases no contentDescription is necessary for various decorative ImageViews. The most radical way to solve the problem is just to tell the Lint to ignore this check. In Eclipse, go to "Android/Lint Error Checking" in Preferences, find "contentDescription" (it is in the "Accessibility" group) and change "Severity:" to Ignore.

Git Push error: refusing to update checked out branch

TLDR

  1. Pull & push again: git pull &&& git push.
  2. Still a problem? Push into different branch: git push origin master:foo and merge it on remote repo.
  3. Alternatively force the push by adding -f (denyCurrentBranch needs to be ignored).

Basically the error means that your repository is not up-to-date with the remote code (its index and work tree is inconsistent with what you pushed).

Normally you should pull first to get the recent changes and push it again.

If won't help, try pushing into different branch, e.g.:

git push origin master:foo

then merge this branch on the remote repository back with master.

If you changed some past commits intentionally via git rebase and you want to override repo with your changes, you probably want to force the push by adding -f/--force parameter (not recommended if you didn't do rebase). If still won't work, you need to set receive.denyCurrentBranch to ignore on remote as suggested by a git message via:

git config receive.denyCurrentBranch ignore

Ctrl+click doesn't work in Eclipse Juno

Go to

Window -> Preferences -> General -> Editors -> Text Editors -> Hyperlinking

and be sure that

Enable on demand hyperlink style navigation

is checked.

Form Validation With Bootstrap (jQuery)

You can get another validation on this tutorial : http://twitterbootstrap.org/bootstrap-form-validation

They use JQuery validation.

jquery.validate.js

jquery.validate.min.js

jquery-1.7.1.min.js

enter image description here

And you'll get the source code there.

 <form id="registration-form" class="form-horizontal">
 <h2>Sample Registration form <small>(Fill up the forms to get register)</small></h2>
 <div class="form-control-group">
        <label class="control-label" for="name">Your Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="name" id="name"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">User Name</label>
 <div class="controls">
          <input type="text" class="input-xlarge" name="username" id="username"></div>
 </div>
 <div class="form-control-group">
        <label class="control-label" for="name">Password</label>
 <div class="controls">
          <input type="password" class="input-xlarge" name="password" id="password">

</div>
</div>
<div class="form-control-group">
            <label class="control-label" for="name"> Retype Password</label>
<div class="controls">
              <input type="password" class="input-xlarge" name="confirm_password" id="confirm_password"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="email">Email Address</label>
<div class="controls">
              <input type="text" class="input-xlarge" name="email" id="email"></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message">Your Address</label>
<div class="controls">
              <textarea class="input-xlarge" name="address" id="address" rows="3"></textarea></div>
</div>
<div class="form-control-group">
            <label class="control-label" for="message"> Please agree to our policy</label>
<div class="controls">
             <input id="agree" class="checkbox" type="checkbox" name="agree"></div>
</div>
<div class="form-actions">
            <button type="submit" class="btn btn-success btn-large">Register</button>
            <button type="reset" class="btn">Cancel</button></div>
</form>

And The JQuery :

<script src="assets/js/jquery-1.7.1.min.js"></script>

<script src="assets/js/jquery.validate.js"></script>

<script src="script.js"></script>
<script>
            addEventListener('load', prettyPrint, false);
            $(document).ready(function(){
            $('pre').addClass('prettyprint linenums');
                  });

Here is the live example of the code: http://twitterbootstrap.org/live/bootstrap-form-validation/

Check the full tutorial: http://twitterbootstrap.org/bootstrap-form-validation/

happy coding.

Textarea that can do syntax highlighting on the fly?

It's not possible to achieve the required level of control over presentation in a regular textarea.

If you're OK with that, try CodeMirror or Ace or Monaco (used in MS VSCode).

From the duplicate thread - an obligatory wikipedia link: Comparison of JavaScript-based source code editors

How can I refresh or reload the JFrame?

Try this code. I also faced the same problem, but some how I solved it.

public class KitchenUserInterface {

    private JFrame frame;
    private JPanel main_panel, northpanel , southpanel;
    private JLabel label;
    private JButton nextOrder;
    private JList list;

    private static KitchenUserInterface kitchenRunner ;

    public void setList(String[] order){
        kitchenRunner.frame.dispose();
        kitchenRunner.frame.setVisible(false);
        kitchenRunner= new KitchenUserInterface(order);

    }

    public KitchenUserInterface getInstance() {
        if(kitchenRunner == null) {
            synchronized(KitchenUserInterface.class) {
                if(kitchenRunner == null) {
                    kitchenRunner = new KitchenUserInterface();
                }
            }
        }


        return this.kitchenRunner;
    }

    private KitchenUserInterface() {


        frame = new JFrame("Lullaby's Kitchen");
        main_panel = new JPanel();
        main_panel.setLayout(new BorderLayout());
        frame.setContentPane(main_panel);



        northpanel = new JPanel();
        northpanel.setLayout(new FlowLayout());


        label = new JLabel("Kitchen");

        northpanel.add(label);


        main_panel.add(northpanel , BorderLayout.NORTH);


        frame.setSize(500 , 500 );
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private KitchenUserInterface (String[] order){
        this();
        list = new JList<String>(order);
        main_panel.add(list , BorderLayout.CENTER);

        southpanel = new JPanel();
         southpanel.setLayout(new FlowLayout());

         nextOrder = new JButton("Next Order Set");
         nextOrder.addActionListener(new OrderUpListener(list));
         southpanel.add(nextOrder);
         main_panel.add(southpanel, BorderLayout.SOUTH);



    }

    public static void main(String[] args) {
        KitchenUserInterface dat = kitchenRunner.getInstance();
        try{

        Thread.sleep(1500);
        System.out.println("Ready");
        dat.setList(OrderArray.getInstance().getOrders());
        }
        catch(Exception event) {
            System.out.println("Error sleep");
            System.out.println(event);
        }


        }

}

Zip folder in C#

"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"

You need to add the dll file as a reference in your project. Right click on References in the Solution Explorer->Add Reference->Browse and then select the dll.

Finally you'll need to add it as a using statement in whatever files you want to use it in.

What is the difference between using constructor vs getInitialState in React / React Native?

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

is equivalent to

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

I have filtered my Excel data and now I want to number the rows. How do I do that?

Try this:

On first row set value 1 (e.g cell A1)

on next row set: =A1+1

Finally autocomplete the remaining rows

Stored procedure or function expects parameter which is not supplied

in my case, I was passing all the parameters but one of the parameter my code was passing a null value for string.

Eg: cmd.Parameters.AddWithValue("@userName", userName);

in the above case, if the data type of userName is string, I was passing userName as null.

Datetime format Issue: String was not recognized as a valid DateTime

DateTime dt1 = DateTime.ParseExact([YourDate], "dd-MM-yyyy HH:mm:ss",  
                                           CultureInfo.InvariantCulture);

Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.

For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).

Transfer data from one database to another database

  1. You can backup and restore the database using Management Studio.
  2. Again from Management Studio you can use "copy database".
  3. you can even do it manually if there is a reason to do so. I mean manually create the target db and manually copying data by sql statements...

can you clarify why you ask this? Is it that you dont have expierience in doing it or something else?