Programs & Examples On #Rdbms agnostic

How does the class_weight parameter in scikit-learn work?

The first answer is good for understanding how it works. But I wanted to understand how I should be using it in practice.

SUMMARY

  • for moderately imbalanced data WITHOUT noise, there is not much of a difference in applying class weights
  • for moderately imbalanced data WITH noise and strongly imbalanced, it is better to apply class weights
  • param class_weight="balanced" works decent in the absence of you wanting to optimize manually
  • with class_weight="balanced" you capture more true events (higher TRUE recall) but also you are more likely to get false alerts (lower TRUE precision)
    • as a result, the total % TRUE might be higher than actual because of all the false positives
    • AUC might misguide you here if the false alarms are an issue
  • no need to change decision threshold to the imbalance %, even for strong imbalance, ok to keep 0.5 (or somewhere around that depending on what you need)

NB

The result might differ when using RF or GBM. sklearn does not have class_weight="balanced" for GBM but lightgbm has LGBMClassifier(is_unbalance=False)

CODE

# scikit-learn==0.21.3
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, classification_report
import numpy as np
import pandas as pd

# case: moderate imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.8]) #,flip_y=0.1,class_sep=0.5)
np.mean(y) # 0.2

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.184
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.184 => same as first
LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X).mean() # 0.296 => seems to make things worse?
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.292 => seems to make things worse?

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.83
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:2,1:8}).fit(X,y).predict(X)) # 0.86 => about the same
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.86 => about the same

# case: strong imbalance
X, y = datasets.make_classification(n_samples=50*15, n_features=5, n_informative=2, n_redundant=0, random_state=1, weights=[0.95])
np.mean(y) # 0.06

LogisticRegression(C=1e9).fit(X,y).predict(X).mean() # 0.02
(LogisticRegression(C=1e9).fit(X,y).predict_proba(X)[:,1]>0.5).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:0.5,1:0.5}).fit(X,y).predict(X).mean() # 0.02 => same as first
LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X).mean() # 0.25 => huh??
LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X).mean() # 0.22 => huh??
(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).mean() # same as last

roc_auc_score(y,LogisticRegression(C=1e9).fit(X,y).predict(X)) # 0.64
roc_auc_score(y,LogisticRegression(C=1e9,class_weight={0:1,1:20}).fit(X,y).predict(X)) # 0.84 => much better
roc_auc_score(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)) # 0.85 => similar to manual
roc_auc_score(y,(LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict_proba(X)[:,1]>0.5).astype(int)) # same as last

print(classification_report(y,LogisticRegression(C=1e9).fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9).fit(X,y).predict(X),margins=True,normalize='index') # few prediced TRUE with only 28% TRUE recall and 86% TRUE precision so 6%*28%~=2%

print(classification_report(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X)))
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True)
pd.crosstab(y,LogisticRegression(C=1e9,class_weight="balanced").fit(X,y).predict(X),margins=True,normalize='index') # 88% TRUE recall but also lot of false positives with only 23% TRUE precision, making total predicted % TRUE > actual % TRUE

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

PyTypeObject PyDict_Type=
{ ...

PyTypeObject PyDict_Type=
{
  PyObject_HEAD_INIT(&PyType_Type),
                     "dict",
                     dict_print,
                     0,
                     0
}; 

watch the name field, in gcc it compile without warning, but in g++ it will, i don't know why.

in gcc (Compiling C), -Wno-write-strings is active by default.

in g++ (Compiling C++) -Wwrite-strings is active by default

This is why there is a different behaviour. For us using macros of Boost_python generates such warnings. So we use -Wno-write-strings when compiling C++ since we always use -Werror

How to cache data in a MVC application

Here's a nice and simple cache helper class/service I use:

using System.Runtime.Caching;  

public class InMemoryCache: ICacheService
{
    public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
    {
        T item = MemoryCache.Default.Get(cacheKey) as T;
        if (item == null)
        {
            item = getItemCallback();
            MemoryCache.Default.Add(cacheKey, item, DateTime.Now.AddMinutes(10));
        }
        return item;
    }
}

interface ICacheService
{
    T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}

Usage:

cacheProvider.GetOrSet("cache key", (delegate method if cache is empty));

Cache provider will check if there's anything by the name of "cache id" in the cache, and if there's not, it will call a delegate method to fetch data and store it in cache.

Example:

var products=cacheService.GetOrSet("catalog.products", ()=>productRepository.GetAll())

How to make Java work with SQL Server?

For anyone still googling this, go to \blackboard\config\tomcat\conf and in wrapper.conf put an extra line in wrapper.java.classpath pointing to the sqljdbc4.jar and then update the wrapper.conf.bb as well

Then restart the blackboard services and tomcat and it should work

It won't work by simply setting your java classpath, you have to set it up in the blackboard config files to point to your jar file with the jdbc library

ls command: how can I get a recursive full-path listing, one line per file?

I knew the file name but wanted the directory as well.

find $PWD | fgrep filename

worked perfectly in Mac OS 10.12.1

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

Let's break down the full URL that a client would type into their address bar to reach your servlet:

http://www.example.com:80/awesome-application/path/to/servlet/path/info?a=1&b=2#boo

The parts are:

  1. scheme: http
  2. hostname: www.example.com
  3. port: 80
  4. context path: awesome-application
  5. servlet path: path/to/servlet
  6. path info: path/info
  7. query: a=1&b=2
  8. fragment: boo

The request URI (returned by getRequestURI) corresponds to parts 4, 5 and 6.

(incidentally, even though you're not asking for this, the method getRequestURL would give you parts 1, 2, 3, 4, 5 and 6).

Now:

  • part 4 (the context path) is used to select your particular application out of many other applications that may be running in the server
  • part 5 (the servlet path) is used to select a particular servlet out of many other servlets that may be bundled in your application's WAR
  • part 6 (the path info) is interpreted by your servlet's logic (e.g. it may point to some resource controlled by your servlet).
  • part 7 (the query) is also made available to your servlet using getQueryString
  • part 8 (the fragment) is not even sent to the server and is relevant and known only to the client

The following always holds (except for URL encoding differences):

requestURI = contextPath + servletPath + pathInfo

The following example from the Servlet 3.0 specification is very helpful:


Note: image follows, I don't have the time to recreate in HTML:

enter image description here

How to correctly display .csv files within Excel 2013?

Another possible problem is that the csv file contains a byte order mark "FEFF". The byte order mark is intended to detect whether the file has been moved from a system using big endian or little endian byte ordering to a system of the opposite endianness. https://en.wikipedia.org/wiki/Byte_order_mark

Removing the "FEFF" byte order mark using a hex editor should allow Excel to read the file.

Functions that return a function

Imagine the function as a type, like an int. You can return ints in a function. You can return functions too, they are object of type "function".

Now the syntax problem: because functions returns values, how can you return a function and not it's returning value?

by omitting brackets! Because without brackets, the function won't be executed! So:

return b;

Will return the "function" (imagine it like if you are returning a number), while:

return b();

First executes the function then return the value obtained by executing it, it's a big difference!

Strip spaces/tabs/newlines - python

If you want to remove multiple whitespace items and replace them with single spaces, the easiest way is with a regexp like this:

>>> import re
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
>>> re.sub('\s+',' ',myString)
'I want to Remove all white spaces, new lines and tabs '

You can then remove the trailing space with .strip() if you want to.

adding multiple entries to a HashMap at once in one statement

You can use the Double Brace Initialization as shown below:

Map<String, Integer> hashMap = new HashMap<String, Integer>()
{{
     put("One", 1);
     put("Two", 2);
     put("Three", 3);
}};

As a piece of warning, please refer to the thread Efficiency of Java “Double Brace Initialization" for the performance implications that it might have.

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

Find full path of the Python interpreter?

There are a few alternate ways to figure out the currently used python in Linux is:

  1. which python command.
  2. command -v python command
  3. type python command

Similarly On Windows with Cygwin will also result the same.

kuvivek@HOSTNAME ~
$ which python
/usr/bin/python

kuvivek@HOSTNAME ~
$ whereis python
python: /usr/bin/python /usr/bin/python3.4 /usr/lib/python2.7 /usr/lib/python3.4        /usr/include/python2.7 /usr/include/python3.4m /usr/share/man/man1/python.1.gz

kuvivek@HOSTNAME ~
$ which python3
/usr/bin/python3

kuvivek@HOSTNAME ~
$ command -v python
/usr/bin/python

kuvivek@HOSTNAME ~
$ type python
python is hashed (/usr/bin/python)

If you are already in the python shell. Try anyone of these. Note: This is an alternate way. Not the best pythonic way.

>>> import os
>>> os.popen('which python').read()
'/usr/bin/python\n'
>>>
>>> os.popen('type python').read()
'python is /usr/bin/python\n'
>>>
>>> os.popen('command -v python').read()
'/usr/bin/python\n'
>>>
>>>

If you are not sure of the actual path of the python command and is available in your system, Use the following command.

pi@osboxes:~ $ which python
/usr/bin/python
pi@osboxes:~ $ readlink -f $(which python)
/usr/bin/python2.7
pi@osboxes:~ $ 
pi@osboxes:~ $ which python3
/usr/bin/python3
pi@osboxes:~ $ 
pi@osboxes:~ $ readlink -f $(which python3)
/usr/bin/python3.7
pi@osboxes:~ $ 

How to do date/time comparison

The following solved my problem of converting string into date

package main

import (
    "fmt"
    "time"
)

func main() {
    value  := "Thu, 05/19/11, 10:47PM"
    // Writing down the way the standard time would look like formatted our way
    layout := "Mon, 01/02/06, 03:04PM"
    t, _ := time.Parse(layout, value)
    fmt.Println(t)
}

// => "Thu May 19 22:47:00 +0000 2011"

Thanks to paul adam smith

How do I ignore files in Subversion?

  1. open you use JetBrains Product(i.e. Pycharm)
  2. then click the 'commit' button on the top toolbar or use shortcut 'ctrl + k' screenshot_toolbar
  3. on the commit interface, move your unwanted files to another change list as follows. screenshot_commit_change
  4. next time you can only commit default change list.

Convert a Unicode string to an escaped ASCII string

You need to use the Convert() method in the Encoding class:

  • Create an Encoding object that represents ASCII encoding
  • Create an Encoding object that represents Unicode encoding
  • Call Encoding.Convert() with the source encoding, the destination encoding, and the string to be encoded

There is an example here:

using System;
using System.Text;

namespace ConvertExample
{
   class ConvertExampleClass
   {
      static void Main()
      {
         string unicodeString = "This string contains the unicode character Pi(\u03a0)";

         // Create two different encodings.
         Encoding ascii = Encoding.ASCII;
         Encoding unicode = Encoding.Unicode;

         // Convert the string into a byte[].
         byte[] unicodeBytes = unicode.GetBytes(unicodeString);

         // Perform the conversion from one encoding to the other.
         byte[] asciiBytes = Encoding.Convert(unicode, ascii, unicodeBytes);

         // Convert the new byte[] into a char[] and then into a string.
         // This is a slightly different approach to converting to illustrate
         // the use of GetCharCount/GetChars.
         char[] asciiChars = new char[ascii.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
         ascii.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
         string asciiString = new string(asciiChars);

         // Display the strings created before and after the conversion.
         Console.WriteLine("Original string: {0}", unicodeString);
         Console.WriteLine("Ascii converted string: {0}", asciiString);
      }
   }
}

CharSequence VS String in Java?

This is almost certainly performance reasons. For example, imagine a parser that goes through a 500k ByteBuffer containing strings.

There are 3 approaches to returning the string content:

  1. Build a String[] at parse time, one character at a time. This will take a noticeable amount of time. We can use == instead of .equals to compare cached references.

  2. Build an int[] with offsets at parse time, then dynamically build String when a get() happens. Each String will be a new object, so no caching returned values and using ==

  3. Build a CharSequence[] at parse time. Since no new data is stored (other than offsets into the byte buffer), the parsing is much lower that #1. At get time, we don't need to build a String, so get performance is equal to #1 (much better than #2), as we're only returning a reference to an existing object.

In addition to the processing gains you get using CharSequence, you also reduce the memory footprint by not duplicating data. For example, if you have a buffer containing 3 paragraphs of text, and want to return either all 3 or a single paragraph, you need 4 Strings to represent this. Using CharSequence you only need 1 buffer with the data, and 4 instances of a CharSequence implementation that tracks the start and length.

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

The debate between cssSelector vs XPath would remain as one of the most subjective debate in the Selenium Community. What we already know so far can be summarized as:

  • People in favor of cssSelector say that it is more readable and faster (especially when running against Internet Explorer).
  • While those in favor of XPath tout it's ability to transverse the page (while cssSelector cannot).
  • Traversing the DOM in older browsers like IE8 does not work with cssSelector but is fine with XPath.
  • XPath can walk up the DOM (e.g. from child to parent), whereas cssSelector can only traverse down the DOM (e.g. from parent to child)
  • However not being able to traverse the DOM with cssSelector in older browsers isn't necessarily a bad thing as it is more of an indicator that your page has poor design and could benefit from some helpful markup.
  • Ben Burton mentions you should use cssSelector because that's how applications are built. This makes the tests easier to write, talk about, and have others help maintain.
  • Adam Goucher says to adopt a more hybrid approach -- focusing first on IDs, then cssSelector, and leveraging XPath only when you need it (e.g. walking up the DOM) and that XPath will always be more powerful for advanced locators.

Dave Haeffner carried out a test on a page with two HTML data tables, one table is written without helpful attributes (ID and Class), and the other with them. I have analyzed the test procedure and the outcome of this experiment in details in the discussion Why should I ever use cssSelector selectors as opposed to XPath for automated testing?. While this experiment demonstrated that each Locator Strategy is reasonably equivalent across browsers, it didn't adequately paint the whole picture for us. Dave Haeffner in the other discussion Css Vs. X Path, Under a Microscope mentioned, in an an end-to-end test there were a lot of other variables at play Sauce startup, Browser start up, and latency to and from the application under test. The unfortunate takeaway from that experiment could be that one driver may be faster than the other (e.g. IE vs Firefox), when in fact, that's wasn't the case at all. To get a real taste of what the performance difference is between cssSelector and XPath, we needed to dig deeper. We did that by running everything from a local machine while using a performance benchmarking utility. We also focused on a specific Selenium action rather than the entire test run, and run things numerous times. I have analyzed the specific test procedure and the outcome of this experiment in details in the discussion cssSelector vs XPath for selenium. But the tests were still missing one aspect i.e. more browser coverage (e.g., Internet Explorer 9 and 10) and testing against a larger and deeper page.

Dave Haeffner in another discussion Css Vs. X Path, Under a Microscope (Part 2) mentions, in order to make sure the required benchmarks are covered in the best possible way we need to consider an example that demonstrates a large and deep page.


Test SetUp

To demonstrate this detailed example, a Windows XP virtual machine was setup and Ruby (1.9.3) was installed. All the available browsers and their equivalent browser drivers for Selenium was also installed. For benchmarking, Ruby's standard lib benchmark was used.


Test Code

require_relative 'base'
require 'benchmark'

class LargeDOM < Base

  LOCATORS = {
    nested_sibling_traversal: {
      css: "div#siblings > div:nth-of-type(1) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3) > div:nth-of-type(3)",
      xpath: "//div[@id='siblings']/div[1]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]/div[3]"
    },
    nested_sibling_traversal_by_class: {
      css: "div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1 > div.item-1",
      xpath: "//div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]/div[contains(@class, 'item-1')]"
    },
    table_header_id_and_class: {
      css: "table#large-table thead .column-50",
      xpath: "//table[@id='large-table']//thead//*[@class='column-50']"
    },
    table_header_id_class_and_direct_desc: {
      css: "table#large-table > thead .column-50",
      xpath: "//table[@id='large-table']/thead//*[@class='column-50']"
    },
    table_header_traversing: {
      css: "table#large-table thead tr th:nth-of-type(50)",
      xpath: "//table[@id='large-table']//thead//tr//th[50]"
    },
    table_header_traversing_and_direct_desc: {
      css: "table#large-table > thead > tr > th:nth-of-type(50)",
      xpath: "//table[@id='large-table']/thead/tr/th[50]"
    },
    table_cell_id_and_class: {
      css: "table#large-table tbody .column-50",
      xpath: "//table[@id='large-table']//tbody//*[@class='column-50']"
    },
    table_cell_id_class_and_direct_desc: {
      css: "table#large-table > tbody .column-50",
      xpath: "//table[@id='large-table']/tbody//*[@class='column-50']"
    },
    table_cell_traversing: {
      css: "table#large-table tbody tr td:nth-of-type(50)",
      xpath: "//table[@id='large-table']//tbody//tr//td[50]"
    },
    table_cell_traversing_and_direct_desc: {
      css: "table#large-table > tbody > tr > td:nth-of-type(50)",
      xpath: "//table[@id='large-table']/tbody/tr/td[50]"
    }
  }

  attr_reader :driver

  def initialize(driver)
    @driver = driver
    visit '/large'
    is_displayed?(id: 'siblings')
    super
  end

  # The benchmarking approach was borrowed from
  # http://rubylearning.com/blog/2013/06/19/how-do-i-benchmark-ruby-code/
  def benchmark
    Benchmark.bmbm(27) do |bm|
      LOCATORS.each do |example, data|
    data.each do |strategy, locator|
      bm.report(example.to_s + " using " + strategy.to_s) do
        begin
          ENV['iterations'].to_i.times do |count|
         find(strategy => locator)
          end
        rescue Selenium::WebDriver::Error::NoSuchElementError => error
          puts "( 0.0 )"
        end
      end
    end
      end
    end
  end

end

Results

NOTE: The output is in seconds, and the results are for the total run time of 100 executions.

In Table Form:

css_xpath_under_microscopev2

In Chart Form:

  • Chrome:

chart-chrome

  • Firefox:

chart-firefox

  • Internet Explorer 8:

chart-ie8

  • Internet Explorer 9:

chart-ie9

  • Internet Explorer 10:

chart-ie10

  • Opera:

chart-opera


Analyzing the Results

  • Chrome and Firefox are clearly tuned for faster cssSelector performance.
  • Internet Explorer 8 is a grab bag of cssSelector that won't work, an out of control XPath traversal that takes ~65 seconds, and a 38 second table traversal with no cssSelector result to compare it against.
  • In IE 9 and 10, XPath is faster overall. In Safari, it's a toss up, except for a couple of slower traversal runs with XPath. And across almost all browsers, the nested sibling traversal and table cell traversal done with XPath are an expensive operation.
  • These shouldn't be that surprising since the locators are brittle and inefficient and we need to avoid them.

Summary

  • Overall there are two circumstances where XPath is markedly slower than cssSelector. But they are easily avoidable.
  • The performance difference is slightly in favor of for non-IE browsers and slightly in favor of for IE browsers.

Trivia

You can perform the bench-marking on your own, using this library where Dave Haeffner wrapped up all the code.

?: operator (the 'Elvis operator') in PHP

Yes, this is new in PHP 5.3. It returns either the value of the test expression if it is evaluated as TRUE, or the alternative value if it is evaluated as FALSE.

Cannot open backup device. Operating System error 5

I was just going through this myself. I had ensured that my MSSQLSERVER login user had full access but it was still causing issues. It only worked once I moved the destination to the root of C. More importantly out of a user folder (even though I had a share with full permissions - even tried "Everyone" as a test).

I don't know if i consider my issue "fixed", however it is "working".

Just a FYI for any other users that come across this thread.

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

This is maybe the wrong answer for you. But this was the first hit on Google when I tried to solve my problem. With that said...

The same error message occurred for me as well, but when I tried to run IIS Express through Visual Studio.

My problem was that I mistakenly commited my applicationhost.config to TFS. Later when I tried to run the project on my laptop after getting the latest commits. that's when the error occurred.

I found that the virtual directory path was wrong.

<virtualDirectory path="/" physicalPath="C:\Users\user1\Documents\Visual Studio 2015\Projects\ProjectName\ProjectName\ProjectName.Web" />

Hope that this help somebody!

This is my first post, so be gentle :)

Making a mocked method return an argument that was passed to it

This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:

@Test
fun demo() {
  // mock a sample function
  val aMock: (String) -> (String) = mockk()

  // make it return the same as the argument on every invocation
  every {
    aMock.invoke(any())
  } answers {
    firstArg()
  }

  // test it
  assertEquals("senko", aMock.invoke("senko"))
  assertEquals("senko1", aMock.invoke("senko1"))
  assertNotEquals("not a senko", aMock.invoke("senko"))
}

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

C compiling - "undefined reference to"?

seems you need to link with the obj file that implements tolayer5()

Update: your function declaration doesn't match the implementation:

      void tolayer5(int AorB, struct msg msgReceived)
      void tolayer5(int, char data[])

So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().

Finding the average of an array using JS

You calculate an average by adding all the elements and then dividing by the number of elements.

var total = 0;
for(var i = 0; i < grades.length; i++) {
    total += grades[i];
}
var avg = total / grades.length;

The reason you got 68 as your result is because in your loop, you keep overwriting your average, so the final value will be the result of your last calculation. And your division and multiplication by grades.length cancel each other out.

How to convert a Java String to an ASCII byte array?

There is only one character wrong in the code you tried:

Charset characterSet = Charset.forName("US-ASCII");
String string = "Wazzup";
byte[] bytes = String.getBytes(characterSet);
               ^

Notice the upper case "String". This tries to invoke a static method on the string class, which does not exist. Instead you need to invoke the method on your string instance:

byte[] bytes = string.getBytes(characterSet);

How to change position of Toast in Android?

If you get an error indicating that you must call makeText, the following code will fix it:

Toast toast= Toast.makeText(getApplicationContext(), 
"Your string here", Toast.LENGTH_SHORT);  
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();

Making macOS Installer Packages which are Developer ID ready

There is one very interesting application by Stéphane Sudre which does all of this for you, is scriptable / supports building from the command line, has a super nice GUI and is FREE. Sad thing is: it's called "Packages" which makes it impossible to find in google.

http://s.sudre.free.fr/Software/Packages/about.html

I wished I had known about it before I started handcrafting my own scripts.

Packages application screenshot

Intellij idea subversion checkout error: `Cannot run program "svn"`

If you're going with Manoj's solution (https://stackoverflow.com/a/29509007/2024713) and still having the problem try switching off "Enable interactive mode" if available in your version of IntelliJ. It worked for me

Java - using System.getProperty("user.dir") to get the home directory

"user.dir" is the current working directory, not the home directory It is all described here.

http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

Also, by using \\ instead of File.separator, you will lose portability with *nix system which uses / for file separator.

Passing an array of parameters to a stored procedure

I'd consider passing your IDs as an XML string, and then you could shred the XML into a temp table to join against, or you could also query against the XML directly using SP_XML_PREPAREDOCUMENT and OPENXML.

What is the difference between a framework and a library?

I will try to explain like you're five.

Let's imagine that you had opened a burger restaurant in your city while ago. But you feel it's so hard to make a burger as a beginner. You were thinking about an easy way to make burgers for customers. Someone told you that there are McDonald Burger Framework and BurgerKing Burger Framework.

If you use McDonald Burger Framework, It's so easy to make Big Mac burger. (but you cannot make Whopper.)

If you use BurgerKing Burger Framework, It's so easy to make Whopper Burger. (however, you cannot make Big Mac)

Anyway, In the end, they are all burgers. An important thing here is, you have to follow their framework's rule to make burgers. otherwise, you feel even harder to make it or won't be able to make it.

And you also heard that there is something called Simple Burger-Patty Library.

If you use this Library, you can make whatever burger patty so easily (X2 speed). It doesn't really matter if you use McDonald Burger Framework or BurgerKing Burger Framework. Either way, you can still use this Simple Burger-Patty Library. (Even you can use this Library without frameworks.)

Do you see the difference between Framework vs Library now?


Once you started using McDonald Burger Framework. It would not be easy to switch to BurgerKing Burger Framework. Since you have to change the whole kitchen.

But Library, It would be much easier to switch others. or you can just not to use it.

How can I make a JPA OneToOne relation lazy

First off, some clarifications to KLE's answer:

  1. Unconstrained (nullable) one-to-one association is the only one that can not be proxied without bytecode instrumentation. The reason for this is that owner entity MUST know whether association property should contain a proxy object or NULL and it can't determine that by looking at its base table's columns due to one-to-one normally being mapped via shared PK, so it has to be eagerly fetched anyway making proxy pointless. Here's a more detailed explanation.

  2. many-to-one associations (and one-to-many, obviously) do not suffer from this issue. Owner entity can easily check its own FK (and in case of one-to-many, empty collection proxy is created initially and populated on demand), so the association can be lazy.

  3. Replacing one-to-one with one-to-many is pretty much never a good idea. You can replace it with unique many-to-one but there are other (possibly better) options.

Rob H. has a valid point, however you may not be able to implement it depending on your model (e.g. if your one-to-one association is nullable).

Now, as far as original question goes:

A) @ManyToOne(fetch=FetchType.LAZY) should work just fine. Are you sure it's not being overwritten in the query itself? It's possible to specify join fetch in HQL and / or explicitly set fetch mode via Criteria API which would take precedence over class annotation. If that's not the case and you're still having problems, please post your classes, query and resulting SQL for more to-the-point conversation.

B) @OneToOne is trickier. If it's definitely not nullable, go with Rob H.'s suggestion and specify it as such:

@OneToOne(optional = false, fetch = FetchType.LAZY)

Otherwise, if you can change your database (add a foreign key column to owner table), do so and map it as "joined":

@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name="other_entity_fk")
public OtherEntity getOther()

and in OtherEntity:

@OneToOne(mappedBy = "other")
public OwnerEntity getOwner()

If you can't do that (and can't live with eager fetching) bytecode instrumentation is your only option. I have to agree with CPerkins, however - if you have 80!!! joins due to eager OneToOne associations, you've got bigger problems then this :-)

What is the iBeacon Bluetooth Profile

iBeacon Profile contains 31 Bytes which includes the followings

  1. Prefix - 9 Bytes - which include s the adv data and Manufacturer data
  2. UUID - 16 Bytes
  3. Major - 2 Bytes
  4. Minor - 2 Bytes
  5. TxPower - 1 Byte

enter image description here

Order by multiple columns with Doctrine

In Doctrine 2.x you can't pass multiple order by using doctrine 'orderBy' or 'addOrderBy' as above examples. Because, it automatically adds the 'ASC' at the end of the last column name when you left the second parameter blank, such as in the 'orderBy' function.

For an example ->orderBy('a.fist_name ASC, a.last_name ASC') will output SQL something like this 'ORDER BY first_name ASC, last_name ASC ASC'. So this is SQL syntax error. Simply because default of the orderBy or addOrderBy is 'ASC'.

To add multiple order by's you need to use 'add' function. And it will be like this.

->add('orderBy','first_name ASC, last_name ASC'). This will give you the correctly formatted SQL.

More info on add() function. https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/query-builder.html#low-level-api

Hope this helps. Cheers!

How to get MD5 sum of a string using python?

For Python 2.x, use python's hashlib

import hashlib
m = hashlib.md5()
m.update("000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite")
print m.hexdigest()

Output: a02506b31c1cd46c2e0b6380fb94eb3d

How can I execute a PHP function in a form action?

I'm not sure I understand what you are trying to achieve as we don't have what username() is supposed to return but you might want to try something like that. I would also recommend you don't echo whole page and rather use something like that, it's much easier to read and maintain:

<?php
require_once ( 'username.php' );
if (isset($_POST)) {
  $textfield = $_POST['textfield']; // this will get you what was in the
                                    // textfield if the form was submitted
}
?>

<form name="form1" method="post" action="<?php echo($_SERVER['PHP_SELF']) ?">
  <p>Your username is: <?php echo(username()) ?></p>
  <p>
    <label>
      <input type="text" name="textfield" id="textfield">
    </label>
  </p>
  <p>
    <label>
      <input type="submit" name="button" id="button" value="Submit">
    </label>
  </p>
</form>

This will post the results in the same page. So first time you display the page, only the empty form is shown, if you press on submit, the textfield field will be in the $textfield variable and you can display it again as you want.

I don't know if the username() function was supposed to return you the URL of where you should send the results but that's what you'd want in the action attribute of your form. I've put the result down in a sample paragraph so you see how you can display the result. See the "Your username is..." part.


// Edit:

If you want to send the value without leaving the page, you want to use AJAX. Do a search on jQuery on StackOverflow or on Google.

You would probably want to have your function return the username instead of echo it though. But if you absolutely want to echo it from the function, just call it like that <?php username() ?> in your HTML form.

I think you will need to understand the flow of the client-server process of your pages before going further. Let's say that the sample code above is called form.php.

  1. Your form.php is called.
  2. The form.php generates the HTML and is sent to the client's browser.
  3. The client only sees the resulting HTML form.
  4. When the user presses the button, you have two choices: a) let the browser do its usual thing so send the values in the form fields to the page specified in action (in this case, the URL is defined by PHP_SELF which is the current page.php). Or b) use javascript to push this data to a page without refreshing the page, this is commonly called AJAX.
  5. A page, in your case, it could be changed to username.php, will then verify against the database if the username exists and then you want to regenerate HTML that contains the values you need, back to step 1.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

T-SQL XOR Operator

How about this?

(A=1 OR B=1 OR C=1) 
AND NOT (A=1 AND B=1 AND C=1)

And if A, B and C can have null values you would need the following:

(A=1 OR B=1 OR C=1) 
AND NOT ( (A=1 AND A is not null) AND (B=1 AND B is not null) AND (C=1 AND C is not null) )

This is scalable to larger number of fields and hence more applicable.

What is the difference between readonly="true" & readonly="readonly"?

readonly="readonly" is xhtml syntax. In xhtml boolean attributes are written this way. In xhtml 'attribute minimization' (<input type="checkbox" checked>) isn't allowed, so this is the valid way to include boolean attributes in xhtml. See this page for more.information.

If your document type is xhtml transitional or strict and you want to validate it, use readonly="readonly otherwise readonly is sufficient.

Typescript input onchange event.target.value

This is when you're working with a FileList Object:

onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
  const fileListObj: FileList | null = event.target.files;
  if (Object.keys(fileListObj as Object).length > 3) {
    alert('Only three images pleaseeeee :)');
  } else {
    // Do something
  }

  return;
}}

CSS background image to fit width, height should auto-scale in proportion

Just add this one line:

    .your-class {
        height: 100vh;
    }

vh is viewport height. This will automatically scale to fit the device' browser window.

Check more here: Make div 100% height of browser window

Cannot drop database because it is currently in use

Go to available databases section and select master. Then Try DROP DATABASE the_DB_name.

How do I convert a Django QuerySet into list of dicts?

Use the .values() method:

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

Note: the result is a QuerySet which mostly behaves like a list, but isn't actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.

What Ruby IDE do you prefer?

Aptana more or less is RadRails, or it's based on it. I've used it, and it's really good, but it does have some problems. For instance, it breaks the basic search dialog on my system (giving a raw java exception to the end user), and it clutters the interface with add like notices and upgrade bars and news feeds and...

But all in all it's pretty good, especially its editors (ERB, HTML/XML, ...) are top notch.

How can I get a channel ID from YouTube?

To obtain the channel id you can do the following request which gives you the channel id and playlist id.

https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&mine=true&key={YOUR_API_KEY}

mine parameter means the current authorized user

as u said channel id is perfixed with UC+{your account id} which you get while login, you can use this one also without requesting the above url you can directly call the channel api with your google id and just prefix with UC

https://www.googleapis.com/youtube/v3/channels?part=contentDetails%2C+statistics%2Csnippet&id=UC{your account id}&key={YOUR_API_KEY}

What happens to a declared, uninitialized variable in C? Does it have a value?

It depends on the storage duration of the variable. A variable with static storage duration is always implicitly initialized with zero.

As for automatic (local) variables, an uninitialized variable has indeterminate value. Indeterminate value, among other things, mean that whatever "value" you might "see" in that variable is not only unpredictable, it is not even guaranteed to be stable. For example, in practice (i.e. ignoring the UB for a second) this code

int num;
int a = num;
int b = num;

does not guarantee that variables a and b will receive identical values. Interestingly, this is not some pedantic theoretical concept, this readily happens in practice as consequence of optimization.

So in general, the popular answer that "it is initialized with whatever garbage was in memory" is not even remotely correct. Uninitialized variable's behavior is different from that of a variable initialized with garbage.

Spark specify multiple column conditions for dataframe join

In Pyspark you can simply specify each condition separately:

val Lead_all = Leads.join(Utm_Master,  
    (Leaddetails.LeadSource == Utm_Master.LeadSource) &
    (Leaddetails.Utm_Source == Utm_Master.Utm_Source) &
    (Leaddetails.Utm_Medium == Utm_Master.Utm_Medium) &
    (Leaddetails.Utm_Campaign == Utm_Master.Utm_Campaign))

Just be sure to use operators and parenthesis correctly.

How can I mix LaTeX in with Markdown?

I came across this discussion only now, so I hope my comment is still useful. I am involved with MathJax and, from how I understand your situation, I think that it would be a good way to solve the problem: you leave your LaTeX code as is, and let MathJax render the mathematics upon viewing.

Is there any reason why you would prefer images?

Remove quotes from a character vector in R

Easiest way is :

> a = "some string"
> write(a, stdout())  # Can specify stderr() also.
some string

Gives you the option to print to stderr if you're doing some error handling printing.

How to call shell commands from Ruby

One more option:

When you:

  • need stderr as well as stdout
  • can't/won't use Open3/Open4 (they throw exceptions in NetBeans on my Mac, no idea why)

You can use shell redirection:

puts %x[cat bogus.txt].inspect
  => ""

puts %x[cat bogus.txt 2>&1].inspect
  => "cat: bogus.txt: No such file or directory\n"

The 2>&1 syntax works across Linux, Mac and Windows since the early days of MS-DOS.

How to change the font and font size of an HTML input tag?

In your 'head' section, add this code:

<style>
input[type='text'] { font-size: 24px; }
</style>

Or you can only add the:

input[type='text'] { font-size: 24px; }

to a CSS file which can later be included.

You can also change the font face by using the CSS property: font-family

font-family: monospace;

So you can have a CSS code like this:

input[type='text'] { font-size: 24px; font-family: monospace; }

You can find further help at the W3Schools website.

I suggest you to have a look at the CSS3 specification. With CSS3 you can also load a font from the web instead of having the limitation to use only the most common fonts or tell the user to download the font you're using.

How to run or debug php on Visual Studio Code (VSCode)

Debugging PHP with VSCode using the vscode-php-debug extension

VSCode can now support debugging PHP projects through the marketplace extension vscode-php-debug.

This extension uses XDebug in the background, and allows you to use breakpoints, watches, stack traces and the like:

Screenshot: PHP Debugging in VSCode using vscode-php-debug extension

Installation is straightforward from within VSCode: Summon the command line with F1 and then type ext install php-debug

Twitter Bootstrap onclick event on buttons-radio

Don't use data-toggle attribute so that you can control the toggle behavior by yourself. So it will avoid 'race-condition'

my codes:

button group template (written in .erb, embedded ruby for ruby on rails):

<div class="btn-group" id="featuresFilter">
     <% _.each(features, function(feature) { %> <button class="btn btn-primary" data="<%= feature %>"><%= feature %></button> <% }); %>
</div>

and javascript:

onChangeFeatures = function(e){
        var el=e.target;
        $(el).button('toggle');

        var features=el.parentElement;
        var activeFeatures=$(features).find(".active");
        console.log(activeFeatures);
}

onChangeFeatures function will be triggered once the button is clicked.

Close Form Button Event

This should handle cases of clicking on [x] or ALT+F4

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   if (e.CloseReason == CloseReason.UserClosing)
   {
      DialogResult result = MessageBox.Show("Do you really want to exit?", "Dialog Title", MessageBoxButtons.YesNo);
      if (result == DialogResult.Yes)
      {
          Environment.Exit(0);
      }
      else 
      {
         e.Cancel = true;
      }
   }
   else
   {
      e.Cancel = true;
   }
}   

Are static class variables possible in Python?

Static methods in python are called classmethods. Take a look at the following code

class MyClass:

    def myInstanceMethod(self):
        print 'output from an instance method'

    @classmethod
    def myStaticMethod(cls):
        print 'output from a static method'

>>> MyClass.myInstanceMethod()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method myInstanceMethod() must be called [...]

>>> MyClass.myStaticMethod()
output from a static method

Notice that when we call the method myInstanceMethod, we get an error. This is because it requires that method be called on an instance of this class. The method myStaticMethod is set as a classmethod using the decorator @classmethod.

Just for kicks and giggles, we could call myInstanceMethod on the class by passing in an instance of the class, like so:

>>> MyClass.myInstanceMethod(MyClass())
output from an instance method

Combining (concatenating) date and time into a datetime

drop table test

create table test(
    CollectionDate date NULL,
    CollectionTime  [time](0) NULL,
    CollectionDateTime as (isnull(convert(datetime,CollectionDate)+convert(datetime,CollectionTime),CollectionDate))
-- if CollectionDate is datetime no need to convert it above
)

insert test (CollectionDate, CollectionTime)
values ('2013-12-10', '22:51:19.227'),
       ('2013-12-10', null),
       (null, '22:51:19.227')

select * from test

CollectionDate  CollectionTime  CollectionDateTime
2013-12-10      22:51:19        2013-12-10 22:51:19.000
2013-12-10      NULL            2013-12-10 00:00:00.000
NULL            22:51:19        NULL

programmatically add column & rows to WPF Datagrid

edit: sorry, I no longer have the code mentioned below. It was a neat solution, although complex.


I posted a sample project describing how to use PropertyDescriptor and lambda delegates with dynamic ObservableCollection and DynamicObject to populate a grid with strongly-typed column definitions.

Columns can be added/removed at runtime dynamically. If your data is not a object with known type, you could create a data structure that would enable access by any number of columns and specify a PropertyDescriptor for each "column".

For example:

IList<string> ColumnNames { get; set; }
//dict.key is column name, dict.value is value
Dictionary<string, string> Rows { get; set; }

You can define columns this way:

var descriptors= new List<PropertyDescriptor>();
//retrieve column name from preprepared list or retrieve from one of the items in dictionary
foreach(var columnName in ColumnNames)
    descriptors.Add(new DynamicPropertyDescriptor<Dictionary, string>(ColumnName, x => x[columnName]))
MyItemsCollection = new DynamicDataGridSource(Rows, descriptors) 

Or even better, in case of some real objects

public class User 
{
    public string FirstName { get; set; }
    public string LastName{ get; set; }
    ...
}

You can specify columns strongly typed (related to your data model):

var propertyDescriptors = new List<PropertyDescriptor>
{
    new DynamicPropertyDescriptor<User, string>("First name", x => x.FirstName ),
    new DynamicPropertyDescriptor<User, string>("Last name", x => x.LastName ),
    ...
}

var users = retrieve some users

Users = new DynamicDataGridSource<User>(users, propertyDescriptors, PropertyChangedListeningMode.Handler);

Then you just bind to Users collections and columns are autogenerated as you speficy them. Strings passed to property descriptors are names for column headers. At runtime you can add more PropertyDescriptors to 'Users' add another column to the grid.

How do I set up IntelliJ IDEA for Android applications?

Just in case someone is lost. For both new application or existing ones go to File->Project Structure. Then in Project settings on the left pane select Project for the Java SDK and select Modules for Android SDK.

How do I set/unset a cookie with jQuery?

I thought Vignesh Pichamani's answer was the simplest and cleanest. Just adding to his the ability to set the number of days before expiration:

EDIT: also added 'never expires' option if no day number is set

        function setCookie(key, value, days) {
            var expires = new Date();
            if (days) {
                expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
                document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
            } else {
                document.cookie = key + '=' + value + ';expires=Fri, 30 Dec 9999 23:59:59 GMT;';
            }
        }

        function getCookie(key) {
            var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
            return keyValue ? keyValue[2] : null;
        }

Set the cookie:

setCookie('myData', 1, 30); // myData=1 for 30 days. 
setCookie('myData', 1); // myData=1 'forever' (until the year 9999) 

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

Multiple maven repositories in one gradle file

In short you have to do like this

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "https://maven.fabric.io/public" }
}

Detail:

You need to specify each maven URL in its own curly braces. Here is what I got working with skeleton dependencies for the web services project I’m going to build up:

apply plugin: 'java'

sourceCompatibility = 1.7
version = '1.0'

repositories {
  maven { url "http://maven.springframework.org/release" }
  maven { url "http://maven.restlet.org" }
  mavenCentral()
}

dependencies {
  compile group:'org.restlet.jee', name:'org.restlet', version:'2.1.1'
  compile group:'org.restlet.jee', name:'org.restlet.ext.servlet',version.1.1'
  compile group:'org.springframework', name:'spring-web', version:'3.2.1.RELEASE'
  compile group:'org.slf4j', name:'slf4j-api', version:'1.7.2'
  compile group:'ch.qos.logback', name:'logback-core', version:'1.0.9'
  testCompile group:'junit', name:'junit', version:'4.11'
}

Blog

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

This did the trick for me:Just remove all the libraries and then compile and run. It would prompt their are errors in your project confirm. Rerun the project after applying the libraries.

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

Try

html

<!-- placeholder , 
    `click` download , `.remove()` options ,
     at js callback , following js 
-->
<a>download</a>

js

        $(document).ready(function () {
            $.ajax({
                // `url` 
                url: '/echo/json/',
                type: "POST",
                dataType: 'json',
                // `file`, data-uri, base64
                data: {
                    json: JSON.stringify({
                        "file": "data:text/plain;base64,YWJj"
                    })
                },
                // `custom header`
                headers: {
                    "x-custom-header": 123
                },
                beforeSend: function (jqxhr) {
                    console.log(this.headers);
                    alert("custom headers" + JSON.stringify(this.headers));
                },
                success: function (data) {
                    // `file download`
                    $("a")
                        .attr({
                        "href": data.file,
                            "download": "file.txt"
                    })
                        .html($("a").attr("download"))
                        .get(0).click();
                    console.log(JSON.parse(JSON.stringify(data)));
                },
                error: function (jqxhr, textStatus, errorThrown) {
                  console.log(textStatus, errorThrown)
                }
            });
        });

jsfiddle http://jsfiddle.net/guest271314/SJYy3/

MySQL CONCAT returns NULL if any field contain NULL

CONCAT_WS still produces null for me if the first field is Null. I solved this by adding a zero length string at the beginning as in

CONCAT_WS("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`)

however

CONCAT("",`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`) 

produces Null when the first field is Null.

Visual Studio Code cannot detect installed git

Visual Studio Code simply looks in your PATH for git. Many UI clients ship with a "Portable Git" for simplicity, and do not add git to the path.

If you add your existing git client to your PATH (so that it can find git.exe), Visual Studio Code should enable Git source control management.

How can I get a collection of keys in a JavaScript dictionary?

A different approach would be to using multi-dimensional arrays:

var driversCounter = [
    ["one", 1], 
    ["two", 2], 
    ["three", 3], 
    ["four", 4], 
    ["five", 5]
]

and access the value by driverCounter[k][j], where j=0,1 in the case.
Add it in a drop down list by:

var dd = document.getElementById('your_dropdown_element');
for(i=0;i<driversCounter.length-1;i++)
{
    dd.options.add(opt);
    opt.text = driversCounter[i][0];
    opt.value = driversCounter[i][1];
}

Custom alert and confirm box in jquery

You can use the dialog widget of JQuery UI

http://jqueryui.com/dialog/

updating table rows in postgres using subquery

You're after the UPDATE FROM syntax.

UPDATE 
  table T1  
SET 
  column1 = T2.column1 
FROM 
  table T2 
  INNER JOIN table T3 USING (column2) 
WHERE 
  T1.column2 = T2.column2;

References

Read from file in eclipse

Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

Also, if you're in Linux, remember that its file systems are usually case sensitive.

Postgresql column reference "id" is ambiguous

I suppose your p2vg table has also an id field , in that case , postgres cannot find if the id in the SELECT refers to vg or p2vg.

you should use SELECT(vg.id,vg.name) to remove ambiguity

What is the preferred/idiomatic way to insert into a map?

I just change the problem a little bit (map of strings) to show another interest of insert:

std::map<int, std::string> rancking;

rancking[0] = 42;  // << some compilers [gcc] show no error

rancking.insert(std::pair<int, std::string>(0, 42));// always a compile error

the fact that compiler shows no error on "rancking[1] = 42;" can have devastating impact !

Compare two Timestamp in java

java.util.Date mytime = null;
if (mytime.after(now) && mytime.before(last_download_time) )

Worked for me

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

What is "pom" packaging in maven?

Real life use case

At a Java-heavy company we had a python project that needed to go into a Nexus artifact repository. Python doesn't really have binaries, so simply just wanted to .tar or .zip the python files and push. The repo already had maven integration, so we used <packaging>pom</packaging> designator with the maven assembly plugin to package the python project as a .zip and upload it.

The steps are outlined in this SO post

How to solve '...is a 'type', which is not valid in the given context'? (C#)

CERAS is a class name which cannot be assigned. As the class implements IDisposable a typical usage would be:

using (CERas.CERAS ceras = new CERas.CERAS())
{
    // call some method on ceras
}

What is size_t in C?

size_t is unsigned integer data type. On systems using the GNU C Library, this will be unsigned int or unsigned long int. size_t is commonly used for array indexing and loop counting.

Is there any ASCII character for <br>?

<br> is an HTML element. There isn't any ASCII code for it.

But, for line break sometimes &#013; is used as the text code.

Or &lt;br&gt;

You can check the text code here.

Is there a minlength validation attribute in HTML5?

My solution for textarea using jQuery and combining HTML5 required validation to check the minimum length.

minlength.js

$(document).ready(function(){
  $('form textarea[minlength]').on('keyup', function(){
    e_len = $(this).val().trim().length
    e_min_len = Number($(this).attr('minlength'))
    message = e_min_len <= e_len ? '' : e_min_len + ' characters minimum'
    this.setCustomValidity(message)
  })
})

HTML

<form action="">
  <textarea name="test_min_length" id="" cols="30" rows="10" minlength="10"></textarea>
</form>

How to change the spinner background in Android?

It is already said in other answers . I did it like placing Spinner inside a CardView and changed the cardBackgroundColor . You could use some other views also and set its background either drawable or color . Thus it doesn't affect Spinner drop down arrow. As the spinner dropdown arrow disappears if we set background to Spinner.

 <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:cardCornerRadius="6dp"
        app:cardBackgroundColor="@color/white">
        
        <Spinner
            android:id="@+id/spinner"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"/>

    </androidx.cardview.widget.CardView>

Cannot make a static reference to the non-static method

This question is not new and existing answers give some good theoretical background. I just want to add a more pragmatic answer.

getText is a method of the Context abstract class and in order to call it, one needs an instance of it's subclass (Activity, Service, Application or other). The problem is, that the public static final variables are initialized before any instance of Context is created.

There are several ways to solve this:

  1. Make the variable a member variable (field) of the Activity or other subclass of Context by removing the static modifier and placing it within the class body;
  2. Keep it static and delay the initialization to a later point (e.g. in the onCreate method);
  3. Make it a local variable in the place of actual usage.

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

How to enable authentication on MongoDB through Docker?

I want to comment but don't have enough reputation.

The user-adding executable script shown above has to be modified with --authenticationDatabase admin and NEWDATABASENAME.

mongo --authenticationDatabase admin --host localhost -u USER_PREVIOUSLY_DEFINED -p PASS_YOU_PREVIOUSLY_DEFINED NEWDATABASENAME --eval "db.createUser({user: 'NEWUSERNAME', pwd: 'PASSWORD', roles: [{role: 'readWrite', db: 'NEWDATABASENAME'}]});"

https://i.stack.imgur.com/MdyXo.png

Using "label for" on radio buttons

(Firstly read the other answers which has explained the for in the <label></label> tags. Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1" but with different ids id="r1_1" ... id="r1_2"

So this way the answer is more clear and removes the conflicts between name and ids as well.

You need different ids for different options of the radio box.

_x000D_
_x000D_
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
       <label for="r1_1">button text one</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
       <label for="r1_2">button text two</label>_x000D_
       <br/>_x000D_
       <input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
       <label for="r1_3">button text three</label>
_x000D_
_x000D_
_x000D_

Could not find method compile() for arguments Gradle

In my case, all the compile statements has somehow arranged in a single line. separating them in individual lines has fixed the issue.

SQL state [99999]; error code [17004]; Invalid column type: 1111 With Spring SimpleJdbcCall

Finally I solve the issues using below code. This type of error will happen when there is a mismatch between In/Out parameter as declare in procedure and in java code declareParameters. Here we need to defined oracle return tab

public class ManualSaleStoredProcedureDao {

private SimpleJdbcCall getAllSytemUsers;

public List<SystemUser> getAllSytemUsers(String clientCode) {

    MapSqlParameterSource in = new MapSqlParameterSource();
    in.addValue("pi_client_code", clientCode);
    Map<String, Object> result = getAllSytemUsers.execute(in);
    @SuppressWarnings("unchecked")
    List<SystemUser> systemUsers = (List<SystemUser>) result
            .get(VSCConstants.GET_SYSTEM_USER_OUT_PARAM1);
    return systemUsers;

}

public void setDataSource(DataSource dataSource) {

    getAllSytemUsers = new SimpleJdbcCall(dataSource)
            .withSchemaName(VSCConstants.SCHEMA)
            .withProcedureName(VSCConstants.GET_SYSTEM_USER_PROC_NAME)
            .declareParameters(
                    new SqlParameter(
                            "pi_client_code",
                            OracleTypes.NUMBER,
                            "pi_client_code"),
                    new SqlInOutParameter(
                            "po_system_users",
                            OracleTypes.ARRAY,
                            "T_SYSTEM_USER_TAB",
                            new OracleSystemUser()));

}

Cross-browser custom styling for file upload button

I'm posting this because (to my surprise) there was no other place I could find that recommended this.

There's a really easy way to do this, without restricting you to browser-defined input dimensions. Just use the <label> tag around a hidden file upload button. This allows for even more freedom in styling than the styling allowed via webkit's built-in styling[1].

The label tag was made for the exact purpose of directing any click events on it to the child inputs[2], so using that, you won't require any JavaScript to direct the click event to the input button for you anymore. You'd to use something like the following:

_x000D_
_x000D_
label.myLabel input[type="file"] {_x000D_
    position:absolute;_x000D_
    top: -1000px;_x000D_
}_x000D_
_x000D_
/***** Example custom styling *****/_x000D_
.myLabel {_x000D_
    border: 2px solid #AAA;_x000D_
    border-radius: 4px;_x000D_
    padding: 2px 5px;_x000D_
    margin: 2px;_x000D_
    background: #DDD;_x000D_
    display: inline-block;_x000D_
}_x000D_
.myLabel:hover {_x000D_
    background: #CCC;_x000D_
}_x000D_
.myLabel:active {_x000D_
    background: #CCF;_x000D_
}_x000D_
.myLabel :invalid + span {_x000D_
    color: #A44;_x000D_
}_x000D_
.myLabel :valid + span {_x000D_
    color: #4A4;_x000D_
}
_x000D_
<label class="myLabel">_x000D_
    <input type="file" required/>_x000D_
    <span>My Label</span>_x000D_
</label>
_x000D_
_x000D_
_x000D_

I've used a fixed position to hide the input, to make it work even in ancient versions of Internet Explorer (emulated IE8- refused to work on a visibility:hidden or display:none file-input). I've tested in emulated IE7 and up, and it worked perfectly.


  1. You can't use <button>s inside <label> tags unfortunately, so you'll have to define the styles for the buttons yourself. To me, this is the only downside to this approach.
  2. If the for attribute is defined, its value is used to trigger the input with the same id as the for attribute on the <label>.

Randomize numbers with jQuery?

function rollDice(){
   return (Math.floor(Math.random()*6)+1);
}

String.Format not work in TypeScript

String Interpolation

Note: As of TypeScript 1.4, string interpolation is available in TypeScript:

var a = "Hello";
var b = "World";

var text = `${a} ${b}`

This will compile to:

var a = "Hello";
var b = "World";
var text = a + " " + b;

String Format

The JavaScript String object doesn't have a format function. TypeScript doesn't add to the native objects, so it also doesn't have a String.format function.

For TypeScript, you need to extend the String interface and then you need to supply an implementation:

interface String {
    format(...replacements: string[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function(match, number) { 
      return typeof args[number] != 'undefined'
        ? args[number]
        : match
      ;
    });
  };
}

You can then use the feature:

var myStr = 'This is an {0} for {0} purposes: {1}';

alert(myStr.format('example', 'end'));

You could also consider string interpolation (a feature of Template Strings), which is an ECMAScript 6 feature - although to use it for the String.format use case, you would still need to wrap it in a function in order to supply a raw string containing the format and then positional arguments. It is more typically used inline with the variables that are being interpolated, so you'd need to map using arguments to make it work for this use case.

For example, format strings are normally defined to be used later... which doesn't work:

// Works
var myFormatString = 'This is an {0} for {0} purposes: {1}';

// Compiler warnings (a and b not yet defines)
var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;

So to use string interpolation, rather than a format string, you would need to use:

function myTemplate(a: string, b: string) {
    var myTemplateString = `This is an ${a} for ${a} purposes: ${b}`;
}

alert(myTemplate('example', 'end'));

The other common use case for format strings is that they are used as a resource that is shared. I haven't yet discovered a way to load a template string from a data source without using eval.

How can I strip first X characters from string using sed?

I found the answer in pure sed supplied by this question (admittedly, posted after this question was posted). This does exactly what you asked, solely in sed:

result=\`echo "$pid" | sed '/./ { s/pid:\ //g; }'\``

The dot in sed '/./) is whatever you want to match. Your question is exactly what I was attempting to, except in my case I wanted to match a specific line in a file and then uncomment it. In my case it was:

# Uncomment a line (edit the file in-place):
sed -i '/#\ COMMENTED_LINE_TO_MATCH/ { s/#\ //g; }' /path/to/target/file

The -i after sed is to edit the file in place (remove this switch if you want to test your matching expression prior to editing the file).

(I posted this because I wanted to do this entirely with sed as this question asked and none of the previous answered solved that problem.)

Getting file size in Python?

os.path.getsize(path)

Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.

Mocking python function based on input arguments

Side effect takes a function (which can also be a lambda function), so for simple cases you may use:

m = MagicMock(side_effect=(lambda x: x+1))

How do I parse command line arguments in Bash?

The top answer to this question seemed a bit buggy when I tried it -- here's my solution which I've found to be more robust:

boolean_arg=""
arg_with_value=""

while [[ $# -gt 0 ]]
do
key="$1"
case $key in
    -b|--boolean-arg)
    boolean_arg=true
    shift
    ;;
    -a|--arg-with-value)
    arg_with_value="$2"
    shift
    shift
    ;;
    -*)
    echo "Unknown option: $1"
    exit 1
    ;;
    *)
    arg_num=$(( $arg_num + 1 ))
    case $arg_num in
        1)
        first_normal_arg="$1"
        shift
        ;;
        2)
        second_normal_arg="$1"
        shift
        ;;
        *)
        bad_args=TRUE
    esac
    ;;
esac
done

# Handy to have this here when adding arguments to
# see if they're working. Just edit the '0' to be '1'.
if [[ 0 == 1 ]]; then
    echo "first_normal_arg: $first_normal_arg"
    echo "second_normal_arg: $second_normal_arg"
    echo "boolean_arg: $boolean_arg"
    echo "arg_with_value: $arg_with_value"
    exit 0
fi

if [[ $bad_args == TRUE || $arg_num < 2 ]]; then
    echo "Usage: $(basename "$0") <first-normal-arg> <second-normal-arg> [--boolean-arg] [--arg-with-value VALUE]"
    exit 1
fi

Mongodb: failed to connect to server on first connect

I was trying to connect mlab with my company wifi connection and it was giving this error. But when I switched to personal network it worked and got connected.

How to update parent's state in React?

Most of the answers given above are for React.Component based designs. If your are using useState in the recent upgrades of React library, then follow this answer

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

What is the difference between AF_INET and PF_INET in socket programming?

In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

Java 8 LocalDate Jackson format

https://stackoverflow.com/a/53251526/1282532 is the simplest way to serialize/deserialize property. I have two concerns regarding this approach - up to some point violation of DRY principle and high coupling between pojo and mapper.

public class Trade {
    @JsonFormat(pattern = "yyyyMMdd")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate tradeDate;
    @JsonFormat(pattern = "yyyyMMdd")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate maturityDate;
    @JsonFormat(pattern = "yyyyMMdd")
    @JsonDeserialize(using = LocalDateDeserializer.class)
    @JsonSerialize(using = LocalDateSerializer.class)
    private LocalDate entryDate;
}

In case you have POJO with multiple LocalDate fields it's better to configure mapper instead of POJO. It can be as simple as https://stackoverflow.com/a/35062824/1282532 if you are using ISO-8601 values ("2019-01-31")

In case you need to handle custom format the code will be like this:

ObjectMapper mapper = new ObjectMapper();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyyMMdd")));
mapper.registerModule(javaTimeModule);

The logic is written just once, it can be reused for multiple POJO

Mipmaps vs. drawable folders

The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.

According to this Google blogpost:

It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.

When referencing the mipmap- folders ensure you are using the following reference:

android:icon="@mipmap/ic_launcher"

The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.

How to create a remote Git repository from a local one?

A remote repository is generally a bare repository — a Git repository that has no working directory. Because the repository is only used as a collaboration point, there is no reason to have a snapshot checked out on disk; it’s just the Git data. In the simplest terms, a bare repository is the contents of your project’s .git directory and nothing else.

You can make a bare git repository with the following code:

$ git clone --bare /path/to/project project.git

One options for having a remote git repository is using SSH protocol:

A common transport protocol for Git when self-hosting is over SSH. This is because SSH access to servers is already set up in most places — and if it isn’t, it’s easy to do. SSH is also an authenticated network protocol and, because it’s ubiquitous, it’s generally easy to set up and use.

To clone a Git repository over SSH, you can specify an ssh:// URL like this:

$ git clone ssh://[user@]server/project.git

Or you can use the shorter scp-like syntax for the SSH protocol:

$ git clone [user@]server:project.git

In both cases above, if you don’t specify the optional username, Git assumes the user you’re currently logged in as.

The Pros

The pros of using SSH are many. First, SSH is relatively easy to set up — SSH daemons are commonplace, many network admins have experience with them, and many OS distributions are set up with them or have tools to manage them. Next, access over SSH is secure — all data transfer is encrypted and authenticated. Last, like the HTTPS, Git and Local protocols, SSH is efficient, making the data as compact as possible before transferring it.

The Cons

The negative aspect of SSH is that it doesn’t support anonymous access to your Git repository. If you’re using SSH, people must have SSH access to your machine, even in a read-only capacity, which doesn’t make SSH conducive to open source projects for which people might simply want to clone your repository to examine it. If you’re using it only within your corporate network, SSH may be the only protocol you need to deal with. If you want to allow anonymous read-only access to your projects and also want to use SSH, you’ll have to set up SSH for you to push over but something else for others to fetch from.

For more information, check the reference: Git on the Server - The Protocols

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Using Alert in Response.Write Function in ASP.NET

Use this....

string popupScript = "<script language=JavaScript>";
popupScript += "alert('Please enter valid Email Id');";
popupScript += "</";
popupScript += "script>";
Page.RegisterStartupScript("PopupScript", popupScript);

How to use wget in php?

If the aim is to just load the contents inside your application, you don't even need to use wget:

$xmlData = file_get_contents('http://user:[email protected]/file.xml');

Note that this function will not work if allow_url_fopen is disabled (it's enabled by default) inside either php.ini or the web server configuration (e.g. httpd.conf).

If your host explicitly disables it or if you're writing a library, it's advisable to either use cURL or a library that abstracts the functionality, such as Guzzle.

use GuzzleHttp\Client;

$client = new Client([
  'base_url' => 'http://example.com',
  'defaults' => [
    'auth'    => ['user', 'pass'],
]]);

$xmlData = $client->get('/file.xml');

PHP Fatal Error Failed opening required File

I was having the exact same issue, I triple checked the include paths, I also checked that pear was installed and everything looked OK and I was still getting the errors, after a few hours of going crazy looking at this I realized that in my script had this:

include_once "../Mail.php";

instead of:

include_once ("../Mail.php");

Yup, the stupid parenthesis was missing, but there was no generated error on this line of my script which was odd to me

How do I check if there are duplicates in a flat list?

If you are fond of functional programming style, here is a useful function, self-documented and tested code using doctest.

def decompose(a_list):
    """Turns a list into a set of all elements and a set of duplicated elements.

    Returns a pair of sets. The first one contains elements
    that are found at least once in the list. The second one
    contains elements that appear more than once.

    >>> decompose([1,2,3,5,3,2,6])
    (set([1, 2, 3, 5, 6]), set([2, 3]))
    """
    return reduce(
        lambda (u, d), o : (u.union([o]), d.union(u.intersection([o]))),
        a_list,
        (set(), set()))

if __name__ == "__main__":
    import doctest
    doctest.testmod()

From there you can test unicity by checking whether the second element of the returned pair is empty:

def is_set(l):
    """Test if there is no duplicate element in l.

    >>> is_set([1,2,3])
    True
    >>> is_set([1,2,1])
    False
    >>> is_set([])
    True
    """
    return not decompose(l)[1]

Note that this is not efficient since you are explicitly constructing the decomposition. But along the line of using reduce, you can come up to something equivalent (but slightly less efficient) to answer 5:

def is_set(l):
    try:
        def func(s, o):
            if o in s:
                raise Exception
            return s.union([o])
        reduce(func, l, set())
        return True
    except:
        return False

How to find the serial port number on Mac OS X?

Found the port esp32 was connected to by -

ls /dev/*

You would get a long list and you can find the port you need

How to check sbt version?

sbt about then enter to get SBT version

enter image description here

Calling method using JavaScript prototype

Well one way to do it would be saving the base method and then calling it from the overriden method, like so

MyClass.prototype._do_base = MyClass.prototype.do;
MyClass.prototype.do = function(){  

    if (this.name === 'something'){

        //do something new

    }else{
        return this._do_base();
    }

};

Detect if page has finished loading

Is this what you had in mind?

$("document").ready( function() {
    // do your stuff
}

How to unset (remove) a collection element after fetching it?

You would want to use ->forget()

$collection->forget($key);

Link to the forget method documentation

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

Combining "LIKE" and "IN" for SQL Server

I know this is old but I got a kind of working solution

SELECT Tbla.* FROM Tbla
INNER JOIN Tblb ON
Tblb.col1 Like '%'+Tbla.Col2+'%'

You can expand it further with your where clause etc. I only answered this because this is what I was looking for and I had to figure out a way of doing it.

How to remove pip package after deleting it manually

packages installed using pip can be uninstalled completely using

pip uninstall <package>

refrence link

pip uninstall is likely to fail if the package is installed using python setup.py install as they do not leave behind metadata to determine what files were installed.

packages still show up in pip list if their paths(.pth file) still exist in your site-packages or dist-packages folder. You'll need to remove them as well in case you're removing using rm -rf

How to get the input from the Tkinter Text Widget?

I would argue that creating a simple extension of Text and turning text into a property is the cleanest way to go. You can then stick that extension in some file that you always import, and use it instead of the original Text widget. This way, instead of having to remember, write, repeat, etc all the hoops tkinter makes you jump through to do the simplest things, you have a butt-simple interface that can be reused in any project. You can do this for Entry, as well, but the syntax is slightly different.

import tkinter as tk

root = tk.Tk()    
    
class Text(tk.Text):
    @property
    def text(self) -> str:
        return self.get('1.0', 'end-1c')
        
    @text.setter
    def text(self, value) -> None:
        self.replace('1.0', 'end-1c', value)
        
    def __init__(self, master, **kwargs):
        tk.Text.__init__(self, master, **kwargs)

#Entry version of the same concept as above      
class Entry(tk.Entry):
    @property
    def text(self) -> str:
        return self.get()
        
    @text.setter
    def text(self, value) -> None:
        self.delete(0, 'end')
        self.insert(0, value)
        
    def __init__(self, master, **kwargs):
        tk.Entry.__init__(self, master, **kwargs)      
      
textbox = Text(root)
textbox.grid()

textbox.text = "this is text" #set
print(textbox.text)           #get  

entry = Entry(root)
entry.grid()

entry.text = 'this is text'   #set
print(entry.text)             #get

root.mainloop()

How can I "disable" zoom on a mobile web page?

This should be everything you need :

<meta name='viewport' 
     content='width=device-width, initial-scale=1.0, maximum-scale=1.0, 
     user-scalable=0' >

What's the difference between SHA and AES encryption?

SHA doesn't require anything but an input to be applied, while AES requires at least 3 things - what you're encrypting/decrypting, an encryption key, and the initialization vector.

og:type and valid values : constantly being parsed as og:type=website

Make sure your article:author data is a Facebook author URL. Unfortunately, that conflicts with what Pinterest is expecting. It's the best thing about standards, there are so many ways to implement them!

<meta property="article:author" content="https://www.facebook.com/mpatnode76">

But Pinterest wants to see something like this:

<meta property="article:author" content="Mike Patnode">

We ended up swapping the formats depending upon the user agent. Hopefully, that doesn't screw up your page cache. That fixed it for us.

Full disclosure. Found this here: https://surniaulula.com/2014/03/01/pinterest-articleauthor-incompatible-with-open-graph/

How to export a MySQL database to JSON?

Also, If you are exporting in application layer don't forget to limit results. For example if you've 10M rows, you should get results part by part.

Check if checkbox is NOT checked on click - jQuery

<script type="text/javascript">

 if(jQuery('input[id=input_id]').is(':checked')){
  // Your Statment
 }else{
  // Your Statment
 }

 OR

 if(jQuery('input[name=input_name]').is(':checked')){
  // Your Statment
 }else{
  // Your Statment
 }

</script>

Code taken from here : http://chandreshrana.blogspot.in/2015/10/how-to-check-if-checkbox-is-checked-or.html

How to get the selected row values of DevExpress XtraGrid?

All you have to do is use the GetFocusedRowCellValue method of the gridView control and put it into the RowClick event.

For example:

private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
{
    if (this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni") == null)
        return;
    MessageBox.Show(""+this.gvCodigoNombres.GetFocusedRowCellValue("EMP_dni").ToString());            
}

How do you list all triggers in a MySQL database?

The command for listing all triggers is:

show triggers;

or you can access the INFORMATION_SCHEMA table directly by:

select trigger_schema, trigger_name, action_statement
from information_schema.triggers

how to hide the content of the div in css

sounds silly but font-size:0; might just work. It did for me. And you can easily override this with the child element you need to show.

React - changing an uncontrolled input

When you first render your component, this.state.name isn't set, so it evaluates to undefined or null, and you end up passing value={undefined} or value={null}to your input.

When ReactDOM checks to see if a field is controlled, it checks to see if value != null (note that it's !=, not !==), and since undefined == null in JavaScript, it decides that it's uncontrolled.

So, when onFieldChange() is called, this.state.name is set to a string value, your input goes from being uncontrolled to being controlled.

If you do this.state = {name: ''} in your constructor, because '' != null, your input will have a value the whole time, and that message will go away.

Implode an array with JavaScript?

You can do this in plain JavaScript, use Array.prototype.join:

arrayName.join(delimiter);

MySQL date format DD/MM/YYYY select query?

SELECT DATE_FORMAT(somedate, "%d/%m/%Y") AS formatted_date
..........
ORDER BY formatted_date DESC

Finding the index of an item in a list

Since Python lists are zero-based, we can use the zip built-in function as follows:

>>> [i for i,j in zip(range(len(haystack)), haystack) if j == 'needle' ]

where "haystack" is the list in question and "needle" is the item to look for.

(Note: Here we are iterating using i to get the indexes, but if we need rather to focus on the items we can switch to j.)

Using Panel or PlaceHolder

I weird bug* in visual studio 2010, if you put controls inside a Placeholder it does not render them in design view mode.

This is especially true for Hidenfields and Empty labels.

I would love to use placeholders instead of panels but I hate the fact I cant put other controls inside placeholders at design time in the GUI.

UPDATE multiple tables in MySQL using LEFT JOIN

UPDATE  t1
LEFT JOIN
        t2
ON      t2.id = t1.id
SET     t1.col1 = newvalue
WHERE   t2.id IS NULL

Note that for a SELECT it would be more efficient to use NOT IN / NOT EXISTS syntax:

SELECT  t1.*
FROM    t1
WHERE   t1.id NOT IN
        (
        SELECT  id
        FROM    t2
        )

See the article in my blog for performance details:

Unfortunately, MySQL does not allow using the target table in a subquery in an UPDATE statement, that's why you'll need to stick to less efficient LEFT JOIN syntax.

XAMPP, Apache - Error: Apache shutdown unexpectedly

Open Skype.

Tools -> Options -> Advanced -> Connection.

Uncheck the "Use port 80 and 443 for alternatives for incoming connections" checkbox

Sign Out and Close all Skype windows. Try restarting your Apache.

Excel formula to get cell color

Color is not data.

The Get.cell technique has flaws.

  1. It does not update as soon as the cell color changes, but only when the cell (or the sheet) is recalculated.
  2. It does not have sufficient numbers for the millions of colors that are available in modern Excel. See the screenshot and notice how the different intensities of yellow or purple all have the same number.

enter image description here

That does not surprise, since the Get.cell uses an old XML command, i.e. a command from the macro language Excel used before VBA was introduced. At that time, Excel colors were limited to less than 60.

Again: Color is not data.

If you want to color-code your cells, use conditional formatting based on the cell values or based on rules that can be expressed with logical formulas. The logic that leads to conditional formatting can also be used in other places to report on the data, regardless of the color value of the cell.

laravel the requested url was not found on this server

I have faced the same problem in cPanel and I fixed my problem to add in .htaccess file below these line

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

Get a random item from a JavaScript array

If you really must use jQuery to solve this problem (NB: you shouldn't):

(function($) {
    $.rand = function(arg) {
        if ($.isArray(arg)) {
            return arg[$.rand(arg.length)];
        } else if (typeof arg === "number") {
            return Math.floor(Math.random() * arg);
        } else {
            return 4;  // chosen by fair dice roll
        }
    };
})(jQuery);

var items = [523, 3452, 334, 31, ..., 5346];
var item = jQuery.rand(items);

This plugin will return a random element if given an array, or a value from [0 .. n) given a number, or given anything else, a guaranteed random value!

For extra fun, the array return is generated by calling the function recursively based on the array's length :)

Working demo at http://jsfiddle.net/2eyQX/

How to quietly remove a directory with content in PowerShell

Remove-Item -LiteralPath "foldertodelete" -Force -Recurse

Getting first and last day of the current month

An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by @Jade

Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.

var now = DateTime.Now; // get the current DateTime 

//Get the number of days in the current month
int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month); 
    
//First day of the month is always 1
var firstDay = new DateTime(now.Year,now.Month,1); 
    
//Last day will be similar to the number of days calculated above
var lastDay = new DateTime(now.Year,now.Month,daysInMonth);

//So
rdpStartDate.SelectedDate = firstDay;
rdpEndDate.SelectedDate = lastDay; 

C++ Dynamic Shared Library on Linux

The following shows an example of a shared class library shared.[h,cpp] and a main.cpp module using the library. It's a very simple example and the makefile could be made much better. But it works and may help you:

shared.h defines the class:

class myclass {
   int myx;

  public:

    myclass() { myx=0; }
    void setx(int newx);
    int  getx();
};

shared.cpp defines the getx/setx functions:

#include "shared.h"

void myclass::setx(int newx) { myx = newx; }
int  myclass::getx() { return myx; }

main.cpp uses the class,

#include <iostream>
#include "shared.h"

using namespace std;

int main(int argc, char *argv[])
{
  myclass m;

  cout << m.getx() << endl;
  m.setx(10);
  cout << m.getx() << endl;
}

and the makefile that generates libshared.so and links main with the shared library:

main: libshared.so main.o
    $(CXX) -o main  main.o -L. -lshared

libshared.so: shared.cpp
    $(CXX) -fPIC -c shared.cpp -o shared.o
    $(CXX) -shared  -Wl,-soname,libshared.so -o libshared.so shared.o

clean:
    $rm *.o *.so

To actual run 'main' and link with libshared.so you will probably need to specify the load path (or put it in /usr/local/lib or similar).

The following specifies the current directory as the search path for libraries and runs main (bash syntax):

export LD_LIBRARY_PATH=.
./main

To see that the program is linked with libshared.so you can try ldd:

LD_LIBRARY_PATH=. ldd main

Prints on my machine:

  ~/prj/test/shared$ LD_LIBRARY_PATH=. ldd main
    linux-gate.so.1 =>  (0xb7f88000)
    libshared.so => ./libshared.so (0xb7f85000)
    libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0xb7e74000)
    libm.so.6 => /lib/libm.so.6 (0xb7e4e000)
    libgcc_s.so.1 => /usr/lib/libgcc_s.so.1 (0xb7e41000)
    libc.so.6 => /lib/libc.so.6 (0xb7cfa000)
    /lib/ld-linux.so.2 (0xb7f89000)

Check if key exists and iterate the JSON array using Python

import json

jsonData = """{"from": {"id": "8", "name": "Mary Pinter"}, "message": "How ARE you?", "comments": {"count": 0}, "updated_time": "2012-05-01", "created_time": "2012-05-01", "to": {"data": [{"id": "1543", "name": "Honey Pinter"}]}, "type": "status", "id": "id_7"}"""

def getTargetIds(jsonData):
    data = json.loads(jsonData)
    if 'to' not in data:
        raise ValueError("No target in given data")
    if 'data' not in data['to']:
        raise ValueError("No data for target")

    for dest in data['to']['data']:
        if 'id' not in dest:
            continue
        targetId = dest['id']
        print("to_id:", targetId)

Output:

In [9]: getTargetIds(s)
to_id: 1543

Get first line of a shell command's output

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

Difference between iCalendar (.ics) and the vCalendar (.vcs)

Both .ics and .vcs files are in ASCII. If you use "Save As" option to save a calendar entry (Appt, Meeting Request/Response/Postpone/Cancel and etc) in both .ics and .vcs format and use vimdiff, you can easily see the difference.

Both .vcs (vCal) and .ics (iCal) belongs to the same VCALENDAR camp, but .vcs file shows "VERSION:1.0" whereas .ics file uses "VERSION:2.0".

The spec for vCalendar v1.0 can be found at http://www.imc.org/pdi/pdiproddev.html. The spec for iCalendar (vCalendar v2.0) is in RFC5545. In general, the newer is better, and that is true for Outlook 2007 and onward, but not for Outlook 2003.

For Outlook 2003, the behavior is peculiar. It can save the same calendar entry in both .ics and .vcs format, but it only read & display .vcs file correctly. It can read .ics file but it omits some fields and does not display it in calendar mode. My guess is that back then Microsoft wanted to provide .ics to be compatible with Mac's iCal but not quite committed to v2.0 yet.

So I would say for Outlook 2003, .vcs is the native format.

What's the difference between @Component, @Repository & @Service annotations in Spring?

Good enough answers are here to explain the whats-the-difference-between-component-repository-service-annotations. I would like to share the difference between @Controller & @RestController

@Controller vs RestController

@RestController:

enter image description here

  • This annotation is a specialized version of @Controller which adds @Controller and @ResponseBody annotation automatically. so we do not have to add @ResponseBody to our mapping methods. That means @ResponseBody is default active.
  • If you use @RestController you cannot return a view (By using Viewresolver in Spring/Spring-Boot)
  • @RestController also converts the response to JSON/XML automatically as @ResponseBody makes the returned objects to something that could be in the body, e.g. JSON or XML

@Controller

enter image description here

  • @Controller is used to mark classes as Spring MVC Controller. This annotation is just a specialized version of @Component and it allows the controller classes to be auto-detected based on classpath scanning.
  • @Controller you can return a view in Spring web MVC.

More Detailed View

Emulator error: This AVD's configuration is missing a kernel file

I tried what ChrLipp suggested, but that wasn't the problem, as the image was already installed. What I did was run:

android avd

to start the emulator manually. Then I stopped the emulator, and form that point on the

cca emulate android

app started working, without the "missing a kernel file" error.

I want to add a JSONObject to a JSONArray and that JSONArray included in other JSONObject

org.json.simple.JSONArray resultantJson = new org.json.simple.JSONArray();

        org.json.JSONArray o1 = new org.json.JSONArray("[{\"one\":[],\"two\":\"abc\"}]");
        org.json.JSONArray o2 = new org.json.JSONArray("[{\"three\":[1,2],\"four\":\"def\"}]");


        resultantJson.addAll(o1.toList());
        resultantJson.addAll(o2.toList());

Unable to import path from django.urls

Python 2 doesn't support Django 2. On a Mac once you've installed Python 3 and Django 2 run the following command from shell to run your app while keeping path:

python3 manage.py runserver

Even if you have upgraded and are on a mac you will, by default, run Python 2 if you're entering the following command:

python manage.py runserver

The version of Django will then be wrong and you will see import errors for path

Match all elements having class name starting with a specific string

The following should do the trick:

div[class^='myclass'], div[class*=' myclass']{
    color: #F00;
}

Edit: Added wildcard (*) as suggested by David

Cannot lower case button text in android studio

In your .xml file within Button add this line--

android:textAllCaps="false"

How to make asynchronous HTTP requests in PHP

Well, the timeout can be set in milliseconds, see "CURLOPT_CONNECTTIMEOUT_MS" in http://www.php.net/manual/en/function.curl-setopt

++i or i++ in for loops ??

++i is a pre-increment; i++ is post-increment.
The downside of post-increment is that it generates an extra value; it returns a copy of the old value while modifying i. Thus, you should avoid it when possible.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

Having sequential ID's makes it a LOT easier for a hacker or data miner to compromise your site and data. Keep that in mind when choosing a PK for a website.

How to expand a list to function arguments in Python

Try the following:

foo(*values)

This can be found in the Python docs as Unpacking Argument Lists.

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

How to create a string with format?

The beauty of String(format:) is that you can save a formatting string and then reuse it later in dozen of places. It also can be localized in this single place. Where as in case of the interpolation approach you must write it again and again.

How can I use Guzzle to send a POST request in JSON?

For Guzzle <= 4:

It's a raw post request so putting the JSON in the body solved the problem

$request = $this->client->post(
    $url,
    [
        'content-type' => 'application/json'
    ],
);
$request->setBody($data); #set body!
$response = $request->send();

How can I indent multiple lines in Xcode?

For those of you with Spanish keyboard on mac this are the shortcuts:

? + ? + [ for un-indent

? + ? + ] for indent

Redirect pages in JSP?

Just define the target page in the action attribute of the <form> containing the submit button.

So, in page1.jsp:

<form action="page2.jsp">
    <input type="submit">
</form>

Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.

How to write "not in ()" sql query using join

SELECT d1.Short_Code 
FROM domain1 d1
LEFT JOIN domain2 d2
ON d1.Short_Code = d2.Short_Code
WHERE d2.Short_Code IS NULL

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

I was just wrestling with a similar problem myself, but didn't want the overhead of a function. I came up with the following query:

SELECT myfield::integer FROM mytable WHERE myfield ~ E'^\\d+$';

Postgres shortcuts its conditionals, so you shouldn't get any non-integers hitting your ::integer cast. It also handles NULL values (they won't match the regexp).

If you want zeros instead of not selecting, then a CASE statement should work:

SELECT CASE WHEN myfield~E'^\\d+$' THEN myfield::integer ELSE 0 END FROM mytable;

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

With CSS, use "..." for overflowed block of multi-lines

Here's a recent css-tricks article which discusses this.

Some of the solutions in the above article (which are not mentioned here) are

1) -webkit-line-clamp and 2) Place an absolutely positioned element to the bottom right with fade out

Both methods assume the following markup:

<div class="module"> /* Add line-clamp/fade class here*/
  <p>Text here</p>
</div>

with css

.module {
  width: 250px;
  overflow: hidden;
}

1) -webkit-line-clamp

line-clamp FIDDLE (..for a maximum of 3 lines)

.line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;  
  max-height: 3.6em; /* I needed this to get it to work */
}

2) fade out

Let's say you set the line-height to 1.2em. If we want to expose three lines of text, we can just make the height of the container 3.6em (1.2em × 3). The hidden overflow will hide the rest.

Fade out FIDDLE

p
{
    margin:0;padding:0;
}
.module {
  width: 250px;
  overflow: hidden;
  border: 1px solid green;
  margin: 10px;
}

.fade {
  position: relative;
  height: 3.6em; /* exactly three lines */
}
.fade:after {
  content: "";
  text-align: right;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 70%;
  height: 1.2em;
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
}

Solution #3 - A combination using @supports

We can use @supports to apply webkit's line-clamp on webkit browsers and apply fade out in other browsers.

@supports line-clamp with fade fallback fiddle

<div class="module line-clamp">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>

CSS

.module {
  width: 250px;
  overflow: hidden;
  border: 1px solid green;
  margin: 10px;
}

.line-clamp {
      position: relative;
      height: 3.6em; /* exactly three lines */
    }
.line-clamp:after {
      content: "";
      text-align: right;
      position: absolute;
      bottom: 0;
      right: 0;
      width: 70%;
      height: 1.2em;
      background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
 }

@supports (-webkit-line-clamp: 3) {
    .line-clamp {
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;  
        max-height:3.6em; /* I needed this to get it to work */
        height: auto;
    }
    .line-clamp:after {
        display: none;
    }
}

How do I check if a column is empty or null in MySQL?

You can also do

SELECT * FROM table WHERE column_name LIKE ''

The inverse being

SELECT * FROM table WHERE column_name NOT LIKE ''

Pandas count(distinct) equivalent

I believe this is what you want:

table.groupby('YEARMONTH').CLIENTCODE.nunique()

Example:

In [2]: table
Out[2]: 
   CLIENTCODE  YEARMONTH
0           1     201301
1           1     201301
2           2     201301
3           1     201302
4           2     201302
5           2     201302
6           3     201302

In [3]: table.groupby('YEARMONTH').CLIENTCODE.nunique()
Out[3]: 
YEARMONTH
201301       2
201302       3

What type of hash does WordPress use?

For manually resetting the password in Wordpress DB, a simple MD5 hash is sufficient. (see reason below)

To prevent breaking backwards compatibility, MD5-hashed passwords stored in the database are still valid. When a user logs in with such a password, WordPress detects MD5 was used, rehashes the password using the more secure method, and stores the new hash in the database.

Source: http://eamann.com/tech/wordpress-password-hashing/

Update: this was an answer posted in 2014. I don't know if it still works for the latest version of WP since I don't work with WP anymore.

When use ResponseEntity<T> and @RestController for Spring RESTful applications

To complete the answer from Sotorios Delimanolis.

It's true that ResponseEntity gives you more flexibility but in most cases you won't need it and you'll end up with these ResponseEntity everywhere in your controller thus making it difficult to read and understand.

If you want to handle special cases like errors (Not Found, Conflict, etc.), you can add a HandlerExceptionResolver to your Spring configuration. So in your code, you just throw a specific exception (NotFoundException for instance) and decide what to do in your Handler (setting the HTTP status to 404), making the Controller code more clear.

Organizing a multiple-file Go project

jdi has the right information concerning the use of GOPATH. I would add that if you intend to have a binary as well you might want to add one additional level to the directories.

~/projects/src/
    myproj/
        mypack/
            lib.go
            lib_test.go
            ...
        myapp/
            main.go

running go build myproj/mypack will build the mypack package along with it's dependencies running go build myproj/myapp will build the myapp binary along with it's dependencies which probably includes the mypack library.

How do I extend a class with c# extension methods?

I was looking for something similar - a list of constraints on classes that provide Extension Methods. Seems tough to find a concise list so here goes:

  1. You can't have any private or protected anything - fields, methods, etc.

  2. It must be a static class, as in public static class....

  3. Only methods can be in the class, and they must all be public static.

  4. You can't have conventional static methods - ones that don't include a this argument aren't allowed.

  5. All methods must begin:

    public static ReturnType MethodName(this ClassName _this, ...)

So the first argument is always the this reference.

There is an implicit problem this creates - if you add methods that require a lock of any sort, you can't really provide it at the class level. Typically you'd provide a private instance-level lock, but it's not possible to add any private fields, leaving you with some very awkward options, like providing it as a public static on some outside class, etc. Gets dicey. Signs the C# language had kind of a bad turn in the design for these.

The workaround is to use your Extension Method class as just a Facade to a regular class, and all the static methods in your Extension class just call the real class, probably using a Singleton.

Save plot to image file instead of displaying it using Matplotlib

Additionally to those above, I added __file__ for the name so the picture and Python file get the same names. I also added few arguments to make It look better:

# Saves a PNG file of the current graph to the folder and updates it every time
# (nameOfimage, dpi=(sizeOfimage),Keeps_Labels_From_Disappearing)
plt.savefig(__file__+".png",dpi=(250), bbox_inches='tight')
# Hard coded name: './test.png'

How to show math equations in general github's markdown(not github's blog)

But github show nothing for the math symbols! please help me, thanks!

GitHub markdown parsing is performed by the SunDown (ex libUpSkirt) library.

The motto of the library is "Standards compliant, fast, secure markdown processing library in C". The important word being "secure" there, considering your question :).

Indeed, allowing javascript to be executed would be a bit off of the MarkDown standard text-to-HTML contract.

Moreover, everything that looks like a HTML tag is either escaped or stripped out.

Tell me how to show math symbols in general github markdown.

Your best bet would be to find a website similar to yuml.me which can generate on-the-fly images from by parsing the provided URL querystring.

Update

I've found some sites providing users with such service: codedogs.com (no longer seems to support embedding) or iTex2Img. You may want to try them out. Of course, others may exist and some Google-fu will help you find them.

given the following markdown syntax

![equation](http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)

it will display the following image

equation http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

Note: In order for the image to be properly displayed, you'll have to ensure the querystring part of the url is percent encoded. You can easily find online tools to help you with that task, such as www.url-encode-decode.com

changing visibility using javascript

If you just want to display it when you get a response add this to your loadpage()

function loadpage(page_request, containerid){
   if (page_request.readyState == 4 && page_request.status==200) { 
      var container = document.getElementById(containerid);
      container.innerHTML=page_request.responseText;
      container.style.visibility = 'visible';
      // or 
      container.style.display = 'block';
}

but this depend entirely on how you hid the div in the first place

Bootstrap 4 File Input

For changing the language of the file browser:
As an alternate to what ZimSystem mentioned (override the CSS), a more elegant solution is suggested by the bootstrap docs: build your custom bootstrap styles by adding languages in SCSS
Read about it here: https://getbootstrap.com/docs/4.0/components/forms/#file-browser

Note: you need to have the lang attribute properly set in your document for this to work

For updating the value on file selection:
You could do it with inline js like this:

   <label class="custom-file">
      <input type="file" id="myfile" class="custom-file-input" onchange="$(this).next().after().text($(this).val().split('\\').slice(-1)[0])">
      <span class="custom-file-control"></span>
   </label>

Note: the .split('\\').slice(-1)[0] part removes the C:\fakepath\ prefix

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

Store both as float, and use unique key words on them.i.em

create table coordinates(
coord_uid counter primary key,
latitude float,
longitude float,
constraint la_long unique(latitude, longitude)
);

SQL NVARCHAR and VARCHAR Limits

declare @p varbinary(max)
set @p = 0x
declare @local table (col text)

SELECT   @p = @p + 0x3B + CONVERT(varbinary(100), Email)
 FROM tbCarsList
 where email <> ''
 group by email
 order by email

 set @p = substring(@p, 2, 100000)

 insert @local values(cast(@p as varchar(max)))
 select DATALENGTH(col) as collen, col from @local

result collen > 8000, length col value is more than 8000 chars

How to build a JSON array from mysql database

Just an update for Mysqli users :

$base= mysqli_connect($dbhost,  $dbuser, $dbpass, $dbbase);

if (mysqli_connect_errno()) 
  die('Could not connect: ' . mysql_error());

$return_arr = array();

if ($result = mysqli_query( $base, $sql )){
    while ($row = mysqli_fetch_assoc($result)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
   }
 }

mysqli_close($base);

echo json_encode($return_arr);

How to watch for a route change in AngularJS?

Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.

$scope.$on('$routeChangeStart', function($event, next, current) { 
   // ... you could trigger something here ...
 });

The following events are also available (their callback functions take different arguments):

  • $routeChangeSuccess
  • $routeChangeError
  • $routeUpdate - if reloadOnSearch property has been set to false

See the $route docs.

There are two other undocumented events:

  • $locationChangeStart
  • $locationChangeSuccess

See What's the difference between $locationChangeSuccess and $locationChangeStart?

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Copying and pasting data using VBA code

'So from this discussion i am thinking this should be the code then.

Sub Button1_Click()
    Dim excel As excel.Application
    Dim wb As excel.Workbook
    Dim sht As excel.Worksheet
    Dim f As Object

    Set f = Application.FileDialog(3)
    f.AllowMultiSelect = False
    f.Show

    Set excel = CreateObject("excel.Application")
    Set wb = excel.Workbooks.Open(f.SelectedItems(1))
    Set sht = wb.Worksheets("Data")

    sht.Activate
    sht.Columns("A:G").Copy
    Range("A1").PasteSpecial Paste:=xlPasteValues


    wb.Close
End Sub

'Let me know if this is correct or a step was missed. Thx.

Import Google Play Services library in Android Studio

After hours of having the same problem, notice that if your jar is on the libs folder will cause problem once you set it upon the "Dependencies ", so i just comment the file tree dependencies and keep the one using

dependencies

//compile fileTree(dir: 'libs', include: ['*.jar'])  <-------- commented one 
compile 'com.google.android.gms:play-services:8.1.0'
compile 'com.android.support:appcompat-v7:22.2.1'

and the problem was solved.

How do I initialize a byte array in Java?

You can use this utility function:

public static byte[] fromHexString(String src) {
    byte[] biBytes = new BigInteger("10" + src.replaceAll("\\s", ""), 16).toByteArray();
    return Arrays.copyOfRange(biBytes, 1, biBytes.length);
}

Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.

Example of usage:

private static final byte[] CDRIVES
    = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
private static final byte[] CMYDOCS
    = fromHexString("BA8A0D4525ADD01198A80800361B1103");
private static final byte[] IEFRAME
    = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");

Avoiding "resource is out of sync with the filesystem"

If this occurs trying to delete a folder (on *nix) and Refresh does not help, open a terminal and look for a symlink below the folder you are trying to delete and remove this manually. This solved my issues.

How to clear APC cache entries?

The stable of APC is having option to clear a cache in its interface itself. To clear those entries you must login to apc interface.

APC is having option to set username and password in apc.php file.

enter image description here

HTML/CSS: Making two floating divs the same height

This is a classic problem in CSS. There's not really a solution for this.

This article from A List Apart is a good read on this problem. It uses a technique called "faux columns", based on having one vertically tiled background image on the element containing the columns that creates the illusion of equal-length columns. Since it is on the floated elements' wrapper, it is as long as the longest element.


The A List Apart editors have this note on the article:

A note from the editors: While excellent for its time, this article may not reflect modern best practices.

The technique requires completely static width designs that doesn't work well with the liquid layouts and responsive design techniques that are popular today for cross-device sites. For static width sites, however, it's a reliable option.

How to delete items from a dictionary while iterating over it?

You can use a dictionary comprehension.

d = {k:d[k] for k in d if d[k] != val}

How to convert NSDate into unix timestamp iphone sdk?

A Unix timestamp is the number of seconds since 00:00:00 UTC January 1, 1970. It's represented by the type time_t, which is usually a signed 32-bit integer type (long or int).

iOS provides -(NSTimeInterval)timeIntervalSince1970 for NSDate objects which returns the number of seconds since 00:00:00 GMT January 1, 1970. NSTimeInterval is a double floating point type so you get the seconds and fractions of a second.

Since they both have the same reference (midnight 1Jan1970 UTC) and are both in seconds the conversion is easy, convert the NSTimeInterval to a time_t, rounding or truncating depending on your needs:

time_t unixTime = (time_t) [[NSDate date] timeIntervalSince1970];

node.js: read a text file into an array. (Each line an item in the array.)

I had the same problem, and I have solved it with the module line-by-line

https://www.npmjs.com/package/line-by-line

At least for me works like a charm, both in synchronous and asynchronous mode.

Also, the problem with lines terminating not terminating \n can be solved with the option:

{ encoding: 'utf8', skipEmptyLines: false }

Synchronous processing of lines:

var LineByLineReader = require('line-by-line'),
    lr = new LineByLineReader('big_file.txt');

lr.on('error', function (err) {
    // 'err' contains error object
});

lr.on('line', function (line) {
    // 'line' contains the current line without the trailing newline character.
});

lr.on('end', function () {
    // All lines are read, file is closed now.
}); 

How do you round a double in Dart to a given degree of precision AFTER the decimal point?

num.toStringAsFixed() rounds. This one turns you num (n) into a string with the number of decimals you want (2), and then parses it back to your num in one sweet line of code:

n = num.parse(n.toStringAsFixed(2));

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

How to crop an image in OpenCV using Python

It's very simple. Use numpy slicing.

import cv2
img = cv2.imread("lenna.png")
crop_img = img[y:y+h, x:x+w]
cv2.imshow("cropped", crop_img)
cv2.waitKey(0)

What is "entropy and information gain"?

When I was implementing an algorithm to calculate the entropy of an image I found these links, see here and here.

This is the pseudo-code I used, you'll need to adapt it to work with text rather than images but the principles should be the same.

//Loop over image array elements and count occurrences of each possible
//pixel to pixel difference value. Store these values in prob_array
for j = 0, ysize-1 do $
    for i = 0, xsize-2 do begin
       diff = array(i+1,j) - array(i,j)
       if diff lt (array_size+1)/2 and diff gt -(array_size+1)/2 then begin
            prob_array(diff+(array_size-1)/2) = prob_array(diff+(array_size-1)/2) + 1
       endif
     endfor

//Convert values in prob_array to probabilities and compute entropy
n = total(prob_array)

entrop = 0
for i = 0, array_size-1 do begin
    prob_array(i) = prob_array(i)/n

    //Base 2 log of x is Ln(x)/Ln(2). Take Ln of array element
    //here and divide final sum by Ln(2)
    if prob_array(i) ne 0 then begin
        entrop = entrop - prob_array(i)*alog(prob_array(i))
    endif
endfor

entrop = entrop/alog(2)

I got this code from somewhere, but I can't dig out the link.

Hex-encoded String to Byte Array

That should do the trick :

byte[] bytes = toByteArray(Str.toCharArray());

public static byte[] toByteArray(char[] array) {
    return toByteArray(array, Charset.defaultCharset());
}

public static byte[] toByteArray(char[] array, Charset charset) {
    CharBuffer cbuf = CharBuffer.wrap(array);
    ByteBuffer bbuf = charset.encode(cbuf);
    return bbuf.array();
}

Call a function after previous function is complete

This depends on what function1 is doing.

If function1 is doing some simple synchrounous javascript, like updating a div value or something, then function2 will fire after function1 has completed.

If function1 is making an asynchronous call, such as an AJAX call, you will need to create a "callback" method (most ajax API's have a callback function parameter). Then call function2 in the callback. eg:

function1()
{
  new AjaxCall(ajaxOptions, MyCallback);
}

function MyCallback(result)
{
  function2(result);
}

How to get selected path and name of the file opened with file dialog?

Try this

Sub Demo()
    Dim lngCount As Long
    Dim cl As Range

    Set cl = ActiveCell
    ' Open the file dialog
    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True
        .Show
        ' Display paths of each file selected
        For lngCount = 1 To .SelectedItems.Count
            ' Add Hyperlinks
            cl.Worksheet.Hyperlinks.Add _
                Anchor:=cl, Address:=.SelectedItems(lngCount), _
                TextToDisplay:=.SelectedItems(lngCount)
            ' Add file name
            'cl.Offset(0, 1) = _
            '    Mid(.SelectedItems(lngCount), InStrRev(.SelectedItems(lngCount), "\") + 1)
            ' Add file as formula
            cl.Offset(0, 1).FormulaR1C1 = _
                 "=TRIM(RIGHT(SUBSTITUTE(RC[-1],""\"",REPT("" "",99)),99))"


            Set cl = cl.Offset(1, 0)
        Next lngCount
    End With
End Sub

Get time of specific timezone

The .getTimezoneOffset() method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.

Difference between Console.Read() and Console.ReadLine()?

The basic difference is:

int i = Console.Read();
Console.WriteLine(i);

paste above code and give input 'c', and the output will be 99. That is Console.Read give int value but that value will be the ASCII value of that..

On the other side..

string s = Console.ReadLine();
Console.WriteLine(s);

It gives the string as it is given in the input stream.

Nginx serves .php files as downloads, instead of executing them

Uncomment the .php location in /etc/nginx/sites-available/default

sudo vi /etc/nginx/sites-available/default:

location ~ \.php$ {
            include snippets/fastcgi-php.conf;

            # With php5-cgi alone:
    #       fastcgi_pass 127.0.0.1:9000;
            # With php5-fpm:
            fastcgi_pass unix:/var/run/php5-fpm.sock;
    }

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

In my case I am using ionic and I simply closed the dialog went to apps in the emulator and ran my app from there instead. This worked. I got the idea of that from here since it was just a time out issue.

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

RESTful Authentication

It's certainly not about "session keys" as it is generally used to refer to sessionless authentication which is performed within all of the constraints of REST. Each request is self-describing, carrying enough information to authorize the request on its own without any server-side application state.

The easiest way to approach this is by starting with HTTP's built-in authentication mechanisms in RFC 2617.