Programs & Examples On #Whitelist

A whitelist is a list of entities that have been authorized for some access or action.

"No Content-Security-Policy meta tag found." error in my phonegap application

There is an another issue about connection. Some android versions can connect but some cannot. So there is an another solution

in AndroidManifest.xml:

_x000D_
_x000D_
<application ... android:usesCleartextTraffic="true">_x000D_
        ..._x000D_
    </application>
_x000D_
_x000D_
_x000D_

Just add 'android:usesCleartextTraffic="true"'

and problem solved finally.

How do I combine the first character of a cell with another cell in Excel?

QUESTION was: suppose T john is to be converted john T, how to change in excel?

If text "T john" is in cell A1

=CONCATENATE(RIGHT(A1,LEN(A1)-2)," ",LEFT(A1,1))

and with a nod to the & crowd

=RIGHT(A1,LEN(A1)-2)&" "&LEFT(A1,1)

takes the right part of the string excluding the first 2 characters, adds a space, adds the first character.

file_put_contents(meta/services.json): failed to open stream: Permission denied

If using laradock, try chown -R laradock:www-data ./storage in your workspace container

How to read file using NPOI

It might be helpful to rely on the Workbook factory to instantiate the workbook object since the factory method will do the detection of xls or xlsx for you. Reference: http://apache-poi.1045710.n5.nabble.com/How-to-check-for-valid-excel-files-using-POI-without-checking-the-file-extension-td2341055.html

IWorkbook workbook = WorkbookFactory.Create(inputStream);

If you're not sure of the Sheet's name but you are sure of the index (0 based), you can grab the sheet like this:

ISheet sheet = workbook.GetSheetAt(sheetIndex);

You can then iterate through the rows using code supplied by the accepted answer from mj82

Problems with jQuery getJSON using local files in Chrome

On Windows, Chrome might be installed in your AppData folder:

"C:\Users\\AppData\Local\Google\Chrome\Application"

Before you execute the command, make sure all of your Chrome windows are closed and not otherwise running. Or, the command line param would not be effective.

chrome.exe --allow-file-access-from-files

Program to find largest and smallest among 5 numbers without using array

Use a sorting network!

#include <iostream>
#include <utility>

int main()
{
    int a, b, c, d, e;
    std::cin >> a >> b >> c >> d >> e;

    if (a < b) std::swap(a, b);
    if (d < e) std::swap(d, e);
    if (c < e) std::swap(c, e);
    if (c < d) std::swap(c, d);
    if (b < e) std::swap(b, e);
    if (a < d) std::swap(a, d);
    if (a < c) std::swap(a, c);
    if (b < d) std::swap(b, d);
    if (b < c) std::swap(b, c);

    std::cout << "largest = " << a << '\n';
    std::cout << "smallest = " << e << '\n';
}

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

How to change the playing speed of videos in HTML5?

You can use this code:

var vid = document.getElementById("video1");

function slowPlaySpeed() { 
    vid.playbackRate = 0.5;
} 

function normalPlaySpeed() { 
    vid.playbackRate = 1;
} 

function fastPlaySpeed() { 
    vid.playbackRate = 2;
}

CSV API for Java

Apache Commons CSV

Check out Apache Common CSV.

This library reads and writes several variations of CSV, including the standard one RFC 4180. Also reads/writes Tab-delimited files.

  • Excel
  • InformixUnload
  • InformixUnloadCsv
  • MySQL
  • Oracle
  • PostgreSQLCsv
  • PostgreSQLText
  • RFC4180
  • TDF

What are "named tuples" in Python?

In Python inside there is a good use of container called a named tuple, it can be used to create a definition of class and has all the features of the original tuple.

Using named tuple will be directly applied to the default class template to generate a simple class, this method allows a lot of code to improve readability and it is also very convenient when defining a class.

Register DLL file on Windows Server 2008 R2

You might need to register this DLL using the 32 bit version of regsvr32.exe:

c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll

String comparison in Python: is vs. ==

The logic is not flawed. The statement

if x is y then x==y is also True

should never be read to mean

if x==y then x is y

It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)

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

You can download older versions of XAMPP here. PHP 5.3 was added in version 1.7.2, so anything older would be good.

ASP.NET custom error page - Server.GetLastError() is null

It worked for me. in MVC 5


in ~\Global.asax

void Application_Error(object sender, EventArgs e)
{
    FTools.LogException();
    Response.Redirect("/Error");
}


in ~\Controllers Create ErrorController.cs

using System.Web.Mvc;

namespace MVC_WebApp.Controllers
{
    public class ErrorController : Controller
    {
        // GET: Error
        public ActionResult Index()
        {
            return View("Error");
        }
    }
}


in ~\Models Create FunctionTools.cs

using System;
using System.Web;

namespace MVC_WebApp.Models
{
    public static class FTools
    {
        private static string _error;
        private static bool _isError;

        public static string GetLastError
        {
            get
            {
                string cashe = _error;
                HttpContext.Current.Server.ClearError();
                _error = null;
                _isError = false;
                return cashe;
            }
        }
        public static bool ThereIsError => _isError;

        public static void LogException()
        {
            Exception exc = HttpContext.Current.Server.GetLastError();
            if (exc == null) return;
            string errLog = "";
            errLog += "**********" + DateTime.Now + "**********\n";
            if (exc.InnerException != null)
            {
                errLog += "Inner Exception Type: ";
                errLog += exc.InnerException.GetType() + "\n";
                errLog += "Inner Exception: ";
                errLog += exc.InnerException.Message + "\n";
                errLog += "Inner Source: ";
                errLog += exc.InnerException.Source + "\n";
                if (exc.InnerException.StackTrace != null)
                {
                    errLog += "\nInner Stack Trace: " + "\n";
                    errLog += exc.InnerException.StackTrace + "\n";
                }
            }
            errLog += "Exception Type: ";
            errLog += exc.GetType().ToString() + "\n";
            errLog += "Exception: " + exc.Message + "\n";
            errLog += "\nStack Trace: " + "\n";
            if (exc.StackTrace != null)
            {
                errLog += exc.StackTrace + "\n";
            }
            _error = errLog;
            _isError = true;
        }
    }
}


in ~\Views Create Folder Error and in ~\Views\Error Create Error.cshtml

@using MVC_WebApp.Models
@{
    ViewBag.Title = "Error";
    if (FTools.ThereIsError == false)
    {
        if (Server.GetLastError() != null)
        {
            FTools.LogException();
        }
    }
    if (FTools.ThereIsError == false)
    {
        <br />
        <h1>No Problem!</h1>
    }
    else
    {
        string log = FTools.GetLastError;
        <div>@Html.Raw(log.Replace("\n", "<br />"))</div>
    }
}


If you enter this address localhost/Error open page Whithout Error



And if an error occurs error occurs

As can be instead of displaying errors, variable 'log' to be stored in the database


Source: Microsoft ASP.Net

Difference between break and continue statement

The break statement breaks out of the loop (the next statement to be executed is the first one after the closing brace), while continue starts the loop over at the next iteration.

How can I add items to an empty set in python

When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

VueJS conditionally add an attribute for an element

It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:

<input v-bind="attrs" />

where attrs is declared as an object:

data() {
    return {
        attrs: {
            required: true,
            type: "text"
        }
    }
}

Which will result in:

<input required type="text"/>

Ideal in cases with multiple attributes.

How to update /etc/hosts file in Docker image during "docker build"

Following worked for me by mounting the file during docker run instead of docker build

docker service create --name <name>  --mount type=bind,source=/etc/hosts,dst=/etc/hosts   <image>

Android Use Done button on Keyboard to click button

max.setOnKeyListener(new OnKeyListener(){
  @Override
  public boolean onKey(View v, int keyCode, KeyEvent event){
    if(keyCode == event.KEYCODE_ENTER){
        //do what you want
    }
  }
});

How to compute the sum and average of elements in an array?

generally average using one-liner reduce is like this

elements.reduce(function(sum, a,i,ar) { sum += a;  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

specifically to question asked

elements.reduce(function(sum, a,i,ar) { sum += parseFloat(a);  return i==ar.length-1?(ar.length==0?0:sum/ar.length):sum},0);

an efficient version is like

elements.reduce(function(sum, a) { return sum + a },0)/(elements.length||1);

Understand Javascript Array Reduce in 1 Minute http://www.airpair.com/javascript/javascript-array-reduce

as gotofritz pointed out seems Array.reduce skips undefined values. so here is a fix:

(function average(arr){var finalstate=arr.reduce(function(state,a) { state.sum+=a;state.count+=1; return state },{sum:0,count:0}); return finalstate.sum/finalstate.count})([2,,,6])

select2 changing items dynamically

In my project I use following code:

$('#attribute').select2();
$('#attribute').bind('change', function(){
    var $options = $();
    for (var i in data) {
        $options = $options.add(
            $('<option>').attr('value', data[i].id).html(data[i].text)
        );
    }
    $('#value').html($options).trigger('change');
});

Try to comment out the select2 part. The rest of the code will still work.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Use this code. This works like a champ.

Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();

LaTeX table positioning

At the beginning with the usepackage definitions include:

\usepackage{placeins}

And before and after add:

\FloatBarrier
\begin{table}[h]
    \begin{tabular}{llll}
      .... 
    \end{tabular}
\end{table}
\FloatBarrier

This places the table exactly where you want in the text.

Retrieving a Foreign Key value with django-rest-framework serializers

Simple solution source='category.name' where category is foreign key and .name it's attribute.

from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item

class ItemSerializer(ModelSerializer):
    category_name = ReadOnlyField(source='category.name')

    class Meta:
        model = Item
        fields = "__all__"

Find the nth occurrence of substring in a string

Here's a more Pythonic version of the straightforward iterative solution:

def find_nth(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+len(needle))
        n -= 1
    return start

Example:

>>> find_nth("foofoofoofoo", "foofoo", 2)
6

If you want to find the nth overlapping occurrence of needle, you can increment by 1 instead of len(needle), like this:

def find_nth_overlapping(haystack, needle, n):
    start = haystack.find(needle)
    while start >= 0 and n > 1:
        start = haystack.find(needle, start+1)
        n -= 1
    return start

Example:

>>> find_nth_overlapping("foofoofoofoo", "foofoo", 2)
3

This is easier to read than Mark's version, and it doesn't require the extra memory of the splitting version or importing regular expression module. It also adheres to a few of the rules in the Zen of python, unlike the various re approaches:

  1. Simple is better than complex.
  2. Flat is better than nested.
  3. Readability counts.

CSS Cell Margin

If you have control of the width of the table, insert a padding-left on all table cells and insert a negative margin-left on the whole table.

table {
    margin-left: -20px;
    width: 720px;
}

table td {
    padding-left: 20px;
}

Note, the width of the table needs to include the padding/margin width. Using the above as an example, the visual width of the table will be 700px.

This is not the best solution if you're using borders on your table cells.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

For those browsers that do support "position: fixed" you can simply use javascript (jQuery) to change the position to "fixed" when scrolling. This eliminates the jumpiness when scrolling with the $(window).scroll(function()) solutions listed here.

Ben Nadel demonstrates this in his tutorial: Creating A Sometimes-Fixed-Position Element With jQuery

System.drawing namespace not found under console application

  1. Right click on properties of Console Application.
  2. Check Target framework
  3. If it is .Net framework 4.0 Client Profile then change it to .Net Framework 4.0

It works now

Python Pandas Counting the Occurrences of a Specific value

You can create subset of data with your condition and then use shape or len:

print df
  col1 education
0    a       9th
1    b       9th
2    c       8th

print df.education == '9th'
0     True
1     True
2    False
Name: education, dtype: bool

print df[df.education == '9th']
  col1 education
0    a       9th
1    b       9th

print df[df.education == '9th'].shape[0]
2
print len(df[df['education'] == '9th'])
2

Performance is interesting, the fastest solution is compare numpy array and sum:

graph

Code:

import perfplot, string
np.random.seed(123)


def shape(df):
    return df[df.education == 'a'].shape[0]

def len_df(df):
    return len(df[df['education'] == 'a'])

def query_count(df):
    return df.query('education == "a"').education.count()

def sum_mask(df):
    return (df.education == 'a').sum()

def sum_mask_numpy(df):
    return (df.education.values == 'a').sum()

def make_df(n):
    L = list(string.ascii_letters)
    df = pd.DataFrame(np.random.choice(L, size=n), columns=['education'])
    return df

perfplot.show(
    setup=make_df,
    kernels=[shape, len_df, query_count, sum_mask, sum_mask_numpy],
    n_range=[2**k for k in range(2, 25)],
    logx=True,
    logy=True,
    equality_check=False, 
    xlabel='len(df)')

Number of times a particular character appears in a string

function for sql server:

CREATE function NTSGetCinC(@Cadena nvarchar(4000), @UnChar nvarchar(100)) 
Returns int 

 as  

 begin 

 declare @t1 int 

 declare @t2 int 

 declare @t3 int 

 set @t1 = len(@Cadena) 

 set @t2 = len(replace(@Cadena,@UnChar,'')) 

 set @t3 = len(@UnChar) 


 return (@t1 - @t2)  / @t3 

 end 

Code for visual basic and others:

Public Function NTSCuentaChars(Texto As String, CharAContar As String) As Long

NTSCuentaChars = (Len(Texto) - Len(Replace(Texto, CharAContar, ""))) / Len(CharAContar)

End Function

How can I selectively escape percent (%) in Python strings?

>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.

How to use a WSDL file to create a WCF service (not make a call)

There are good resources out there if you know what to search for. Try "Contract First" and WCF. or "WSDL First" and WCF.

Here is a selection:

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

If we encapsulate that in a function we could use recursion and state clearly the purpose by naming the function properly (not sure if getAny is actually a good name):

def getAny(dic, keys, default=None):
    return (keys or default) and dic.get(keys[0], 
                                         getAny( dic, keys[1:], default=default))

or even better, without recursion and more clear:

def getAny(dic, keys, default=None):
    for k in keys: 
        if k in dic:
           return dic[k]
    return default

Then that could be used in a way similar to the dict.get method, like:

getAny(myDict, keySet)

and even have a default result in case of no keys found at all:

getAny(myDict, keySet, "not found")

Get key and value of object in JavaScript?

Change your object.

var top_brands = [ 
  { key: 'Adidas', value: 100 }, 
  { key: 'Nike', value: 50 }
];

var $brand_options = $("#top-brands");

$.each(top_brands, function(brand) {
  $brand_options.append(
    $("<option />").val(brand.key).text(brand.key + " " + brand.value)
  );
});

As a rule of thumb:

  • An object has data and structure.
  • 'Adidas', 'Nike', 100 and 50 are data.
  • Object keys are structure. Using data as the object key is semantically wrong. Avoid it.

There are no semantics in {Nike: 50}. What's "Nike"? What's 50?

{key: 'Nike', value: 50} is a little better, since now you can iterate an array of these objects and values are at predictable places. This makes it easy to write code that handles them.

Better still would be {vendor: 'Nike', itemsSold: 50}, because now values are not only at predictable places, they also have meaningful names. Technically that's the same thing as above, but now a person would also understand what the values are supposed to mean.

How to remove duplicates from Python list and keep order?

If it's clarity you're after, rather than speed, I think this is very clear:

def sortAndUniq(input):
  output = []
  for x in input:
    if x not in output:
      output.append(x)
  output.sort()
  return output

It's O(n^2) though, with the repeated use of not in for each element of the input list.

Add a property to a JavaScript object using a variable as the name?

With ECMAScript 2015 you can do it directly in object declaration using bracket notation:

var obj = {
  [key]: value
}

Where key can be any sort of expression (e.g. a variable) returning a value:

var obj = {
  ['hello']: 'World',
  [x + 2]: 42,
  [someObject.getId()]: someVar
}

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

Will iOS launch my app into the background if it was force-quit by the user?

For iOS13

For background pushes in iOS13, you must set below parameters:

apns-priority = 5
apns-push-type = background
//Required for WatchOS
//Highly recommended for Other platforms 

Background PUSHES The video link: https://developer.apple.com/videos/play/wwdc2019/707/

Case-insensitive string comparison in C++

You can use strcasecmp on Unix, or stricmp on Windows.

One thing that hasn't been mentioned so far is that if you are using stl strings with these methods, it's useful to first compare the length of the two strings, since this information is already available to you in the string class. This could prevent doing the costly string comparison if the two strings you are comparing aren't even the same length in the first place.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

I wrote a validator of mime type. Kindly share it with you.

private readonly Dictionary<string, byte[]> _mimeTypes = new Dictionary<string, byte[]>
    {
        {"image/jpeg", new byte[] {255, 216, 255}},
        {"image/jpg", new byte[] {255, 216, 255}},
        {"image/pjpeg", new byte[] {255, 216, 255}},
        {"image/apng", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},
        {"image/png", new byte[] {137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82}},
        {"image/bmp", new byte[] {66, 77}},
        {"image/gif", new byte[] {71, 73, 70, 56}},
    };

private bool ValidateMimeType(byte[] file, string contentType)
    {
        var imageType = _mimeTypes.SingleOrDefault(x => x.Key.Equals(contentType));

        return file.Take(imageType.Value.Length).SequenceEqual(imageType.Value);
    }

What is the difference between Cygwin and MinGW?

Cygwin uses a compatibility layer, while MinGW is native. That is one of the main differences.

twitter bootstrap 3.0 typeahead ajax example

<input id="typeahead-input" type="text" data-provide="typeahead" />

<script type="text/javascript">
var data = ["Aamir", "Amol", "Ayesh", "Sameera", "Sumera", "Kajol", "Kamal",
  "Akash", "Robin", "Roshan", "Aryan"];
$(function() {
    $('#typeahead-input').typeahead({
        source: function (query, process) {
               process(data);
            });
        }
    });
});
</script>

Meaning of = delete after function declaration

The coding standards I've worked with have had the following for most of class declarations.

//  coding standard: disallow when not used
T(void)                  = delete; // default ctor    (1)
~T(void)                 = delete; // default dtor    (2)
T(const T&)              = delete; // copy ctor       (3)
T(const T&&)             = delete; // move ctor       (4)
T& operator= (const T&)  = delete; // copy assignment (5)
T& operator= (const T&&) = delete; // move assignment (6)

If you use any of these 6, you simply comment out the corresponding line.

Example: class FizzBus require only dtor, and thus do not use the other 5.

//  coding standard: disallow when not used
FizzBuzz(void)                         = delete; // default ctor (1)
// ~FizzBuzz(void);                              // dtor         (2)
FizzBuzz(const FizzBuzz&)              = delete; // copy ctor    (3)
FizzBuzz& operator= (const FizzBuzz&)  = delete; // copy assig   (4)
FizzBuzz(const FizzBuzz&&)             = delete; // move ctor    (5)
FizzBuzz& operator= (const FizzBuzz&&) = delete; // move assign  (6)

We comment out only 1 here, and install the implementation of it else where (probably where the coding standard suggests). The other 5 (of 6) are disallowed with delete.

You can also use '= delete' to disallow implicit promotions of different sized values ... example

// disallow implicit promotions 
template <class T> operator T(void)              = delete;
template <class T> Vuint64& operator=  (const T) = delete;
template <class T> Vuint64& operator|= (const T) = delete;
template <class T> Vuint64& operator&= (const T) = delete;

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

How to collapse blocks of code in Eclipse?

For Python it is as follows:

  • collapse all 1 level: Ctrl+9
  • expand all 1 level: Ctrl+0
  • collapse current: Ctrl+-
  • expand current: Ctrl++

Hope that helps.

How to make FileFilter in java?

Here you will find some working examples. This is also a good example of FileFilter used in JFileChooser.

The basics are, you need to override FileFilter class and write your custom code in its accpet method. The accept method in above example is doing filtration based on file types:

public boolean accept(File file) {
    if (file.isDirectory()) {
      return true;
    } else {
      String path = file.getAbsolutePath().toLowerCase();
      for (int i = 0, n = extensions.length; i < n; i++) {
        String extension = extensions[i];
        if ((path.endsWith(extension) && (path.charAt(path.length() 
                  - extension.length() - 1)) == '.')) {
          return true;
        }
      }
    }
    return false;
}

Or more simpler to use is FileNameFilter which has accept method with filename as argument, so you don't need to get it manually.

How to check sbt version?

Doing sbt sbt-version led to some error as

[error] Not a valid command: sbt-version (similar: writeSbtVersion, session)
[error] Not a valid project ID: sbt-version
[error] Expected ':'
[error] Not a valid key: sbt-version (similar: sbtVersion, version, sbtBinaryVersion)
[error] sbt-version
[error]            ^

As you can see the hint similar: sbtVersion, version, sbtBinaryVersion, all of them work but the correct one is generated by sbt sbtVersion

Changing fonts in ggplot2

To change the font globally for ggplot2 plots.

theme_set(theme_gray(base_size = 20, base_family = 'Font Name' ))

Import an Excel worksheet into Access using VBA

Pass the sheet name with the Range parameter of the DoCmd.TransferSpreadsheet Method. See the box titled "Worksheets in the Range Parameter" near the bottom of that page.

This code imports from a sheet named "temp" in a workbook named "temp.xls", and stores the data in a table named "tblFromExcel".

Dim strXls As String
strXls = CurrentProject.Path & Chr(92) & "temp.xls"
DoCmd.TransferSpreadsheet acImport, , "tblFromExcel", _
    strXls, True, "temp!"

Submitting a form on 'Enter' with jQuery?

I use now

$("form").submit(function(event){
...
}

At first I added an eventhandler to the submit button which produced an error for me.

Drawing an image from a data URL to a canvas

in javascript , using jquery for canvas id selection :

 var Canvas2 = $("#canvas2")[0];
        var Context2 = Canvas2.getContext("2d");
        var image = new Image();
        image.src = "images/eye.jpg";
        Context2.drawImage(image, 0, 0);

html5:

<canvas id="canvas2"></canvas>

Update int column in table with unique incrementing values

declare @i int  = (SELECT ISNULL(MAX(interfaceID),0) + 1 FROM prices)


update prices
set interfaceID  = @i , @i = @i + 1
where interfaceID is null

should do the work

wkhtmltopdf: cannot connect to X server

sudo -i
apt-get install wkhtmltopdf xvfb libicu48
mv /usr/bin/wkhtmltopdf /usr/bin/wkhtmltopdf-origin
touch /usr/bin/wkhtmltopdf && chmod +x /usr/bin/wkhtmltopdf && cat > /usr/bin/wkhtmltopdf << END
#!/bin/bash

/usr/bin/xvfb-run -a -s "-screen 0 1024x768x24" /usr/bin/wkhtmltopdf-origin  "\$@"
END

HTML5 record audio to file

There is a fairly complete recording demo available at: http://webaudiodemos.appspot.com/AudioRecorder/index.html

It allows you to record audio in the browser, then gives you the option to export and download what you've recorded.

You can view the source of that page to find links to the javascript, but to summarize, there's a Recorder object that contains an exportWAV method, and a forceDownload method.

How to load a tsv file into a Pandas DataFrame?

Try this:

import pandas as pd
DataFrame = pd.read_csv("dataset.tsv", sep="\t")

Android: keep Service running when app is killed

If your Service is started by your app then actually your service is running on main process. so when app is killed service will also be stopped. So what you can do is, send broadcast from onTaskRemoved method of your service as follows:

 Intent intent = new Intent("com.android.ServiceStopped");
 sendBroadcast(intent);

and have an broadcast receiver which will again start a service. I have tried it. service restarts from all type of kills.

How to extract table as text from the PDF using Python?

This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.

Here are the steps I found to work.

  1. Use pdfimages from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.

  2. Use Tesseract to detect rotation and ImageMagick mogrify to fix it.

  3. Use OpenCV to find and extract tables.

  4. Use OpenCV to find and extract each cell from the table.

  5. Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.

  6. Use Tesseract to OCR each cell.

  7. Combine the extracted text of each cell into the format you need.

I wrote a python package with modules that can help with those steps.

Repo: https://github.com/eihli/image-table-ocr

Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html

Some of the steps don't require code, they take advantage of external tools like pdfimages and tesseract. I'll provide some brief examples for a couple of the steps that do require code.

  1. Finding tables:

This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/

import cv2

def find_tables(image):
    BLUR_KERNEL_SIZE = (17, 17)
    STD_DEV_X_DIRECTION = 0
    STD_DEV_Y_DIRECTION = 0
    blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
    MAX_COLOR_VAL = 255
    BLOCK_SIZE = 15
    SUBTRACT_FROM_MEAN = -2

    img_bin = cv2.adaptiveThreshold(
        ~blurred,
        MAX_COLOR_VAL,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        BLOCK_SIZE,
        SUBTRACT_FROM_MEAN,
    )
    vertical = horizontal = img_bin.copy()
    SCALE = 5
    image_width, image_height = horizontal.shape
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
    horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
    vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)

    horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
    vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))

    mask = horizontally_dilated + vertically_dilated
    contours, hierarchy = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
    )

    MIN_TABLE_AREA = 1e5
    contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
    perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
    epsilons = [0.1 * p for p in perimeter_lengths]
    approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
    bounding_rects = [cv2.boundingRect(a) for a in approx_polys]

    # The link where a lot of this code was borrowed from recommends an
    # additional step to check the number of "joints" inside this bounding rectangle.
    # A table should have a lot of intersections. We might have a rectangular image
    # here though which would only have 4 intersections, 1 at each corner.
    # Leaving that step as a future TODO if it is ever necessary.
    images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
    return images
  1. Extract cells from table.

This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.

We want to identify the cells from left-to-right, top-to-bottom.

We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.

def cell_in_same_row(c1, c2):
    c1_center = c1[1] + c1[3] - c1[3] / 2
    c2_bottom = c2[1] + c2[3]
    c2_top = c2[1]
    return c2_top < c1_center < c2_bottom

orig_cells = [c for c in cells]
rows = []
while cells:
    first = cells[0]
    rest = cells[1:]
    cells_in_same_row = sorted(
        [
            c for c in rest
            if cell_in_same_row(c, first)
        ],
        key=lambda c: c[0]
    )

    row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
    rows.append(row_cells)
    cells = [
        c for c in rest
        if not cell_in_same_row(c, first)
    ]

# Sort rows by average height of their center.
def avg_height_of_center(row):
    centers = [y + h - h / 2 for x, y, w, h in row]
    return sum(centers) / len(centers)

rows.sort(key=avg_height_of_center)

How to check if a Unix .tar.gz file is a valid file without uncompressing?

you could probably use the gzip -t option to test the files integrity

http://linux.about.com/od/commands/l/blcmdl1_gzip.htm

from: http://unix.ittoolbox.com/groups/technical-functional/shellscript-l/how-to-test-file-integrity-of-targz-1138880

To test the gzip file is not corrupt:

gunzip -t file.tar.gz

To test the tar file inside is not corrupt:

gunzip -c file.tar.gz | tar -t > /dev/null

As part of the backup you could probably just run the latter command and check the value of $? afterwards for a 0 (success) value. If either the tar or the gzip has an issue, $? will have a non zero value.

Simpler way to create dictionary of separate variables?

On python3, this function will get the outer most name in the stack:

import inspect


def retrieve_name(var):
        """
        Gets the name of var. Does it from the out most frame inner-wards.
        :param var: variable to get name from.
        :return: string
        """
        for fi in reversed(inspect.stack()):
            names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
            if len(names) > 0:
                return names[0]

It is useful anywhere on the code. Traverses the reversed stack looking for the first match.

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

Why is Java's SimpleDateFormat not thread-safe?

Here is a code example that proves the fault in the class. I've checked: the problem occurs when using parse and also when you are only using format.

Best implementation for hashCode method for a collection

As you specifically asked for collections, I'd like to add an aspect that the other answers haven't mentioned yet: A HashMap doesn't expect their keys to change their hashcode once they are added to the collection. Would defeat the whole purpose...

How to run a PowerShell script from a batch file

Small sample test.cmd

<# :
  @echo off
    powershell /nologo /noprofile /command ^
         "&{[ScriptBlock]::Create((cat """%~f0""") -join [Char[]]10).Invoke(@(&{$args}%*))}"
  exit /b
#>
Write-Host Hello, $args[0] -fo Green
#You programm...

Clearing NSUserDefaults

Try This, It's working for me .

Single line of code

[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:[[NSBundle mainBundle] bundleIdentifier]];

Clean out Eclipse workspace metadata

The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?

For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.

How to sort two lists (which reference each other) in the exact same way

You can use the zip() and sort() functions to accomplish this:

Python 2.6.5 (r265:79063, Jun 12 2010, 17:07:01)
[GCC 4.3.4 20090804 (release) 1] on cygwin
>>> list1 = [3,2,4,1,1]
>>> list2 = ['three', 'two', 'four', 'one', 'one2']
>>> zipped = zip(list1, list2)
>>> zipped.sort()
>>> slist1 = [i for (i, s) in zipped]
>>> slist1
[1, 1, 2, 3, 4]
>>> slist2 = [s for (i, s) in zipped]
>>> slist2
['one', 'one2', 'two', 'three', 'four']

Hope this helps

What's the fastest way to delete a large folder in Windows?

and to delete a lot of folders, you could also create a batch file with the command spdenne posted.

1) make a text file that has the following contents replacing the folder names in quotes with your folder names:

rmdir /s /q "My Apps"  
rmdir /s /q "My Documents"  
rmdir /s /q "My Pictures"  
rmdir /s /q "My Work Files"

2) save the batch file with a .bat extension (for example deletefiles.bat)
3) open a command prompt (Start > Run > Cmd) and execute the batch file. you can do this like so from the command prompt (substituting X for your drive letter):

X:  
deletefiles.bat

Set height of chart in Chart.js

Set the aspectRatio property of the chart to 0 did the trick for me...

    var ctx = $('#myChart');

    ctx.height(500);

    var myChart = new Chart(ctx, {
        type: 'horizontalBar',
        data: {
            labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                backgroundColor: [
                    'rgba(255, 99, 132, 0.2)',
                    'rgba(54, 162, 235, 0.2)',
                    'rgba(255, 206, 86, 0.2)',
                    'rgba(75, 192, 192, 0.2)',
                    'rgba(153, 102, 255, 0.2)',
                    'rgba(255, 159, 64, 0.2)'
                ],
                borderColor: [
                    'rgba(255,99,132,1)',
                    'rgba(54, 162, 235, 1)',
                    'rgba(255, 206, 86, 1)',
                    'rgba(75, 192, 192, 1)',
                    'rgba(153, 102, 255, 1)',
                    'rgba(255, 159, 64, 1)'
                ],
                borderWidth: 1
            }]
        },
        maintainAspectRatio: false,
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
myChart.aspectRatio = 0;

Creating a segue programmatically

A couple of problems, actually:

First, in that project you uploaded for us, the segue does not bear the "segue1" identifier:

no identifier

You should fill in that identifier if you haven't already.

Second, as you're pushing from table view to table view, you're calling initWithNibName to create a view controller. You really want to use instantiateViewControllerWithIdentifier.

How do I mount a remote Linux folder in Windows through SSH?

Back in 2002, Novell developed some software called NetDrive that can map a WebDAV, FTP, SFTP, etc. share to a windows drive letter. It is now abandonware, so it's no longer maintained (and not available on the Novell website), but it's free to use. I found quite a few available to download by searching for "netdrive.exe" I actually downloaded a few and compared their md5sums to make sure that I was getting a common (and hopefully safe) version.

Update 10 Nov 2017 SFTPNetDrive is the current project from the original netdrive project. And they made it free for personal use:

We Made SFTP Net Drive FREE for Personal Use

They have paid options as well on the website.

How to download a file via FTP with Python ftplib

A = filename

ftp = ftplib.FTP("IP")
ftp.login("USR Name", "Pass")
ftp.cwd("/Dir")


try:
    ftp.retrbinary("RETR " + filename ,open(A, 'wb').write)
except:
    print "Error"

Version of Apache installed on a Debian machine

For me apachectl -V did not work, but apachectl fullstatus gave me my version.

How to pass a JSON array as a parameter in URL

You can pass your json Input as a POST request along with authorization header in this way

public static JSONObject getHttpConn(String json){
        JSONObject jsonObject=null;
        try {
            HttpPost httpPost=new HttpPost("http://google.com/");
            org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
            StringEntity stringEntity=new StringEntity("d="+json);

            httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
            String authorization="test:test@123";
            String encodedAuth = "Basic " + Base64.encode(authorization.getBytes());        
            httpPost.addHeader("Authorization", security.get("Authorization"));
            httpPost.setEntity(stringEntity);
            HttpResponse reponse=client.execute(httpPost);
            InputStream inputStream=reponse.getEntity().getContent();
            String jsonResponse=IOUtils.toString(inputStream);
            jsonObject=JSONObject.fromObject(jsonResponse);
            } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return jsonObject;


    }

This Method will return a json response.In same way you can use GET method

How do I run a bat file in the background from another bat file?

Create a new C# Windows application and call this method from main:

public static void RunBatchFile(string filename)
{
    Process process = new Process();

    process.StartInfo.FileName = filename;

    // suppress output (command window still gets created)
    process.StartInfo.Arguments = "> NULL";

    process.Start();
    process.WaitForExit();
}

MySQL case sensitive query

To improve James' excellent answer:

It's better to put BINARY in front of the constant instead:

SELECT * FROM `table` WHERE `column` = BINARY 'value'

Putting BINARY in front of column will prevent the use of any index on that column.

How to convert byte array to string and vice versa?

Here the working code.

            // Encode byte array into string . TemplateBuffer1 is my bytearry variable.

        String finger_buffer = Base64.encodeToString(templateBuffer1, Base64.DEFAULT);
        Log.d(TAG, "Captured biometric device->" + finger_buffer);


        // Decode String into Byte Array. decodedString is my bytearray[] 
        decodedString = Base64.decode(finger_buffer, Base64.DEFAULT);

how to create and call scalar function in sql server 2008

Or you can simply use PRINT command instead of SELECT command. Try this,

PRINT dbo.fn_HomePageSlider(9, 3025)

Retrieving the text of the selected <option> in <select> element

Similar to @artur just without jQuery, with plain javascript:

// Using @Sean-bright's "elt" variable

var selection=elt.options[elt.selectedIndex].innerHTML;

append option to select menu?

$(document).ready(function(){

    $('#mySelect').append("<option>BMW</option>")

})

WhatsApp API (java/python)

This is the developers page of the Open WhatsApp official page: http://openwhatsapp.org/develop/

You can find a lot of information there about Yowsup.

Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): https://github.com/tgalal/yowsup

Enjoy!

How can I pass variable to ansible playbook in the command line?

 s3_sync:
      bucket: ansible-harshika
      file_root: "{{ pathoftsfiles  }}"
      validate_certs: false 
      mode: push
      key_prefix: "{{ folder }}"

here the variables are being used named as 'pathoftsfiles' and 'folder'. Now the value to this variable can be given by the below command

sudo ansible-playbook multiadd.yml --extra-vars "pathoftsfiles=/opt/lampp/htdocs/video/uploads/tsfiles/$2 folder=nitesh"

Note: Don't use the inverted commas while passing the values to the variable in the shell command

How to send cookies in a post request with the Python Requests library?

The latest release of Requests will build CookieJars for you from simple dictionaries.

import requests

cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r = requests.post('http://wikipedia.org', cookies=cookies)

Enjoy :)

How to use Bash to create a folder if it doesn't already exist?

First, in bash "[" is just a command, which expects string "]" as a last argument, so the whitespace before the closing bracket (as well as between "!" and "-d" which need to be two separate arguments too) is important:

if [ ! -d /home/mlzboy/b2c2/shared/db ]; then
  mkdir -p /home/mlzboy/b2c2/shared/db;
fi

Second, since you are using -p switch to mkdir, this check is useless, because this is what does in the first place. Just write:

mkdir -p /home/mlzboy/b2c2/shared/db;

and thats it.

How do I parse command line arguments in Bash?

If you are making scripts that are interchangeable with other utilities, below flexibility may be useful.

Either:

command -x=myfilename.ext --another_switch 

Or:

command -x myfilename.ext --another_switch

Here is the code:

STD_IN=0

prefix=""
key=""
value=""
for keyValue in "$@"
do
  case "${prefix}${keyValue}" in
    -i=*|--input_filename=*)  key="-i";     value="${keyValue#*=}";; 
    -ss=*|--seek_from=*)      key="-ss";    value="${keyValue#*=}";;
    -t=*|--play_seconds=*)    key="-t";     value="${keyValue#*=}";;
    -|--stdin)                key="-";      value=1;;
    *)                                      value=$keyValue;;
  esac
  case $key in
    -i) MOVIE=$(resolveMovie "${value}");  prefix=""; key="";;
    -ss) SEEK_FROM="${value}";          prefix=""; key="";;
    -t)  PLAY_SECONDS="${value}";           prefix=""; key="";;
    -)   STD_IN=${value};                   prefix=""; key="";; 
    *)   prefix="${keyValue}=";;
  esac
done

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

How to initialize a list of strings (List<string>) with many string values

You haven't really asked a question, but the code should be

List<string> optionList = new List<string> { "string1", "string2", ..., "stringN"}; 

i.e. no trailing () after the list.

How to stop/terminate a python script from running?

Press Ctrl+Alt+Delete and Task Manager will pop up. Find the Python command running, right click on it and and click Stop or Kill.

Maximum number of rows of CSV data in excel sheet

Using the Excel Text import wizard to import it if it is a text file, like a CSV file, is another option and can be done based on which row number to which row numbers you specify. See: This link

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

Just Run MySQL Server Installer and Reconfigure the My SQL Server...This worked for me.

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Is there a way to break a list into columns?

The mobile-first way is to use CSS Columns to create an experience for smaller screens then use Media Queries to increase the number of columns at each of your layout's defined breakpoints.

_x000D_
_x000D_
ul {_x000D_
  column-count: 2;_x000D_
  column-gap: 2rem;_x000D_
}_x000D_
@media screen and (min-width: 768px)) {_x000D_
  ul {_x000D_
    column-count: 3;_x000D_
    column-gap: 5rem;_x000D_
  }_x000D_
}
_x000D_
<ul>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

TypeError: Object of type 'bytes' is not JSON serializable

I guess the answer you need is referenced here Python sets are not json serializable

Not all datatypes can be json serialized . I guess pickle module will serve your purpose.

Appending an element to the end of a list in Scala

List(1,2,3) :+ 4

Results in List[Int] = List(1, 2, 3, 4)

Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).

Find nearest value in numpy array

Here is a version that works with 2D arrays, using scipy's cdist function if the user has it, and a simpler distance calculation if they don't.

By default, the output is the index that is closest to the value you input, but you can change that with the output keyword to be one of 'index', 'value', or 'both', where 'value' outputs array[index] and 'both' outputs index, array[index].

For very large arrays, you may need to use kind='euclidean', as the default scipy cdist function may run out of memory.

This is maybe not the absolute fastest solution, but it is quite close.

def find_nearest_2d(array, value, kind='cdist', output='index'):
    # 'array' must be a 2D array
    # 'value' must be a 1D array with 2 elements
    # 'kind' defines what method to use to calculate the distances. Can choose one
    #    of 'cdist' (default) or 'euclidean'. Choose 'euclidean' for very large
    #    arrays. Otherwise, cdist is much faster.
    # 'output' defines what the output should be. Can be 'index' (default) to return
    #    the index of the array that is closest to the value, 'value' to return the
    #    value that is closest, or 'both' to return index,value
    import numpy as np
    if kind == 'cdist':
        try: from scipy.spatial.distance import cdist
        except ImportError:
            print("Warning (find_nearest_2d): Could not import cdist. Reverting to simpler distance calculation")
            kind = 'euclidean'
    index = np.where(array == value)[0] # Make sure the value isn't in the array
    if index.size == 0:
        if kind == 'cdist': index = np.argmin(cdist([value],array)[0])
        elif kind == 'euclidean': index = np.argmin(np.sum((np.array(array)-np.array(value))**2.,axis=1))
        else: raise ValueError("Keyword 'kind' must be one of 'cdist' or 'euclidean'")
    if output == 'index': return index
    elif output == 'value': return array[index]
    elif output == 'both': return index,array[index]
    else: raise ValueError("Keyword 'output' must be one of 'index', 'value', or 'both'")

Select all text inside EditText when it gets focus

Just add this to your editText in the .xml file

android:selectAllOnFocus="true"

How to read if a checkbox is checked in PHP?

<?php

  if (isset($_POST['add'])) {

    $nama      = $_POST['name'];
    $subscribe = isset($_POST['subscribe']) ? $_POST['subscribe'] : "Not Checked";

    echo "Name: {$nama} <br />";
    echo "Subscribe: {$subscribe}";

    echo "<hr />";   

  }

?>

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >

  <input type="text" name="name" /> <br />
  <input type="checkbox" name="subscribe" value="news" /> News <br />

  <input type="submit" name="add" value="Save" />

</form>

Good ways to sort a queryset? - Django

What about

import operator

auths = Author.objects.order_by('-score')[:30]
ordered = sorted(auths, key=operator.attrgetter('last_name'))

In Django 1.4 and newer you can order by providing multiple fields.
Reference: https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by

order_by(*fields)

By default, results returned by a QuerySet are ordered by the ordering tuple given by the ordering option in the model’s Meta. You can override this on a per-QuerySet basis by using the order_by method.

Example:

ordered_authors = Author.objects.order_by('-score', 'last_name')[:30]

The result above will be ordered by score descending, then by last_name ascending. The negative sign in front of "-score" indicates descending order. Ascending order is implied.

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

How to count the number of occurrences of a character in an Oracle varchar value?

SELECT {FN LENGTH('123-345-566')} - {FN LENGTH({FN REPLACE('123-345-566', '#', '')})} FROM DUAL

How to use std::sort to sort an array in C++

you can use sort() in C++ STL. sort() function Syntax :

 sort(array_name, array_name+size)      

 So you use  sort(v, v+2000);

event Action<> vs event EventHandler<>

I realize that this question is over 10 years old, but it appears to me that not only has the most obvious answer not been addressed, but that maybe its not really clear from the question a good understanding of what goes on under the covers. In addition, there are other questions about late binding and what that means with regards to delegates and lambdas (more on that later).

First to address the 800 lb elephant/gorilla in the room, when to choose event vs Action<T>/Func<T>:

  • Use a lambda to execute one statement or method. Use event when you want more of a pub/sub model with multiple statements/lambdas/functions that will execute (this is a major difference right off the bat).
  • Use a lambda when you want to compile statements/functions to expression trees. Use delegates/events when you want to participate in more traditional late binding such as used in reflection and COM interop.

As an example of an event, lets wire up a simple and 'standard' set of events using a small console application as follows:

public delegate void FireEvent(int num);

public delegate void FireNiceEvent(object sender, SomeStandardArgs args);

public class SomeStandardArgs : EventArgs
{
    public SomeStandardArgs(string id)
    {
        ID = id;
    }

    public string ID { get; set; }
}

class Program
{
    public static event FireEvent OnFireEvent;

    public static event FireNiceEvent OnFireNiceEvent;


    static void Main(string[] args)
    {
        OnFireEvent += SomeSimpleEvent1;
        OnFireEvent += SomeSimpleEvent2;

        OnFireNiceEvent += SomeStandardEvent1;
        OnFireNiceEvent += SomeStandardEvent2;


        Console.WriteLine("Firing events.....");
        OnFireEvent?.Invoke(3);
        OnFireNiceEvent?.Invoke(null, new SomeStandardArgs("Fred"));

        //Console.WriteLine($"{HeightSensorTypes.Keyence_IL030}:{(int)HeightSensorTypes.Keyence_IL030}");
        Console.ReadLine();
    }

    private static void SomeSimpleEvent1(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent1)}:{num}");
    }
    private static void SomeSimpleEvent2(int num)
    {
        Console.WriteLine($"{nameof(SomeSimpleEvent2)}:{num}");
    }

    private static void SomeStandardEvent1(object sender, SomeStandardArgs args)
    {

        Console.WriteLine($"{nameof(SomeStandardEvent1)}:{args.ID}");
    }
    private static void SomeStandardEvent2(object sender, SomeStandardArgs args)
    {
        Console.WriteLine($"{nameof(SomeStandardEvent2)}:{args.ID}");
    }
}

The output will look as follows:

enter image description here

If you did the same with Action<int> or Action<object, SomeStandardArgs>, you would only see SomeSimpleEvent2 and SomeStandardEvent2.

So whats going on inside of event?

If we expand out FireNiceEvent, the compiler is actually generating the following (I have omitted some details with respect to thread synchronization that isn't relevant to this discussion):

   private EventHandler<SomeStandardArgs> _OnFireNiceEvent;

    public void add_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Combine(_OnFireNiceEvent, handler);
    }

    public void remove_OnFireNiceEvent(EventHandler<SomeStandardArgs> handler)
    {
        Delegate.Remove(_OnFireNiceEvent, handler);
    }

    public event EventHandler<SomeStandardArgs> OnFireNiceEvent
    {
        add
        {
            add_OnFireNiceEvent(value)
        }
        remove
        {
            remove_OnFireNiceEvent(value)

        }
    }

The compiler generates a private delegate variable which is not visible to the class namespace in which it is generated. That delegate is what is used for subscription management and late binding participation, and the public facing interface is the familiar += and -= operators we have all come to know and love : )

You can customize the code for the add/remove handlers by changing the scope of the FireNiceEvent delegate to protected. This now allows developers to add custom hooks to the hooks, such as logging or security hooks. This really makes for some very powerful features that now allows for customized accessibility to subscription based on user roles, etc. Can you do that with lambdas? (Actually you can by custom compiling expression trees, but that's beyond the scope of this response).

To address a couple of points from some of the responses here:

  • There really is no difference in the 'brittleness' between changing the args list in Action<T> and changing the properties in a class derived from EventArgs. Either will not only require a compile change, they will both change a public interface and will require versioning. No difference.

  • With respect to which is an industry standard, that depends on where this is being used and why. Action<T> and such is often used in IoC and DI, and event is often used in message routing such as GUI and MQ type frameworks. Note that I said often, not always.

  • Delegates have different lifetimes than lambdas. One also has to be aware of capture... not just with closure, but also with the notion of 'look what the cat dragged in'. This does affect memory footprint/lifetime as well as management a.k.a. leaks.

One more thing, something I referenced earlier... the notion of late binding. You will often see this when using framework like LINQ, regarding when a lambda becomes 'live'. That is very different than late binding of a delegate, which can happen more than once (i.e. the lambda is always there, but binding occurs on demand as often as is needed), as opposed to a lambda, which once it occurs, its done -- the magic is gone, and the method(s)/property(ies) will always bind. Something to keep in mind.

'tsc command not found' in compiling typescript

I had this same problem on Ubuntu 19.10 LTS.

To solve this I ran the following command:

$ sudo apt install node-typescript

After that, I was able to use tsc.

Combine two ActiveRecord::Relation objects

If you have an array of activerecord relations and want to merge them all, you can do

array.inject(:merge)

Collection that allows only unique items in .NET?

If all you need is to ensure uniqueness of elements, then HashSet is what you need.

What do you mean when you say "just a set implementation"? A set is (by definition) a collection of unique elements that doesn't save element order.

How to copy a file to a remote server in Python using SCP or SSH?

I used sshfs to mount the remote directory via ssh, and shutil to copy the files:

$ mkdir ~/sshmount
$ sshfs user@remotehost:/path/to/remote/dst ~/sshmount

Then in python:

import shutil
shutil.copy('a.txt', '~/sshmount')

This method has the advantage that you can stream data over if you are generating data rather than caching locally and sending a single large file.

How to check if an app is installed from a web-page on an iPhone?

As of 2017, it seems there's no reliable way to detect an app is installed, and the redirection trick won't work everywhere.

For those like me who needs to deep link directly from emails (quite common), it is worth noting the following:

  • Sending emails with appScheme:// won't work fine because the links will be filtered in Gmail

  • Redirecting automatically to appScheme:// is blocked by Chrome: I suspect Chrome requires the redirection to be synchronous to an user interaction (like a click)

  • You can now deep link without appScheme:// and it's better but it requires a modern platform and additional setup. Android iOS


It is worth noting that other people already thought about this in depth. If you look at how Slack implements his "magic link" feature, you can notice that:

  • It sends an email with a regular http link (ok with Gmail)
  • The web page have a big button that links to appScheme:// (ok with Chrome)

git push vs git push origin <branchname>

First, you need to create your branch locally

git checkout -b your_branch

After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it

git push -u origin your_branch

Your Teammates/colleagues can push to your branch by doing commits and then push explicitly

... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch 

Getting or changing CSS class property with Javascript using DOM style

I think this is not the best way, but in my cases other methods did not work.

stylesheet = document.styleSheets[0]
stylesheet.insertRule(".have-border { border: 1px solid black;}", 0);

Example from https://www.w3.org/wiki/Dynamic_style_-_manipulating_CSS_with_JavaScript

Could not autowire field in spring. why?

I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.

Characters allowed in a URL

The characters allowed in a URI are either reserved or unreserved (or a percent character as part of a percent-encoding)

http://en.wikipedia.org/wiki/Percent-encoding#Types_of_URI_characters

says these are RFC 3986 unreserved characters (sec. 2.3) as well as reserved characters (sec 2.2) if they need to retain their special meaning. And also a percent character as part of a percent-encoding.

How to use glob() to find files recursively?

Here is my solution using list comprehension to search for multiple file extensions recursively in a directory and all subdirectories:

import os, glob

def _globrec(path, *exts):
""" Glob recursively a directory and all subdirectories for multiple file extensions 
    Note: Glob is case-insensitive, i. e. for '\*.jpg' you will get files ending
    with .jpg and .JPG

    Parameters
    ----------
    path : str
        A directory name
    exts : tuple
        File extensions to glob for

    Returns
    -------
    files : list
        list of files matching extensions in exts in path and subfolders

    """
    dirs = [a[0] for a in os.walk(path)]
    f_filter = [d+e for d in dirs for e in exts]    
    return [f for files in [glob.iglob(files) for files in f_filter] for f in files]

my_pictures = _globrec(r'C:\Temp', '\*.jpg','\*.bmp','\*.png','\*.gif')
for f in my_pictures:
    print f

How to deploy a Java Web Application (.war) on tomcat?

As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webappdirectory.

Now, if Tomcat is installed and running on bilgin.ath.cx (as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80 on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk?, mod_proxy?). You should either give us more details or discuss this with your hosting provider.

Update: As expected, the bilgin.ath.cx is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties file to configure the workers and the httpd.conf for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount directive in Apache httpd.conf for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.

1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)

How to check if a date is greater than another in Java?

Parse the string into date, then compare using compareTo, before or after

Date d = new Date();
d.compareTo(anotherDate)

i.e

Date date1 = new SimpleDateFormat("MM/dd/yyyy").parse(date1string)
Date date2 = new SimpleDateFormat("MM/dd/yyyy").parse(date2string)

date1.compareTo(date2);

Copying the comment provided below by @MuhammadSaqib to complete this answer.

Returns the value 0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument, and a value greater than 0 if this Date is after the Date argument. and NullPointerException - if anotherDate is null.

javadoc for compareTo http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#compareTo(java.util.Date)

How to write trycatch in R

Since I just lost two days of my life trying to solve for tryCatch for an irr function, I thought I should share my wisdom (and what is missing). FYI - irr is an actual function from FinCal in this case where got errors in a few cases on a large data set.

  1. Set up tryCatch as part of a function. For example:

    irr2 <- function (x) {
      out <- tryCatch(irr(x), error = function(e) NULL)
      return(out)
    }
    
  2. For the error (or warning) to work, you actually need to create a function. I originally for error part just wrote error = return(NULL) and ALL values came back null.

  3. Remember to create a sub-output (like my "out") and to return(out).

What is the best way to iterate over a dictionary?

As already pointed out on this answer, KeyValuePair<TKey, TValue> implements a Deconstruct method starting on .NET Core 2.0, .NET Standard 2.1 and .NET Framework 5.0 (preview).

With this, it's possible to iterate through a dictionary in a KeyValuePair agnostic way:

var dictionary = new Dictionary<int, string>();

// ...

foreach (var (key, value) in dictionary)
{
    // ...
}

PHP to write Tab Characters inside a file?

This should do:

$chunk = "abc\tdef\tghi";

Here is a link to an article with more extensive examples.

How to get only the date value from a Windows Forms DateTimePicker control?

Following that this question has been already given a good answer, in WinForms we can also set a Custom Format to the DateTimePicker Format property as Vivek said, this allow us to display the date/time in the specified format string within the DateTimePicker, then, it will be simple just as we do to get text from a TextBox.

// Set the Format type and the CustomFormat string.
dateTimePicker1.Format = DateTimePickerFormat.Custom;    
dateTimePicker1.CustomFormat = "yyyy/MM/dd";

dateTimePicker1

We are now able to get Date only easily by getting the Text from the DateTimePicker:

MessageBox.Show("Selected Date: " + dateTimePicker1.Text, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Information);

enter image description here

NOTE: If you are planning to insert Date only data to a date column type in SQL, see this documentation related to the supported String Literal Formats for date. You can not insert a date in the format string ydm because is not supported:

dateTimePicker1.CustomFormat = "yyyy/dd/MM";  
var qr = "INSERT INTO tbl VALUES (@dtp)";
using (var insertCommand = new SqlCommand..
{
   try
   {
     insertCommand.Parameters.AddWithValue("@dtp", dateTimePicker1.Text);
     con.Open();
     insertCommand.ExecuteScalar();
   }
   catch (Exception ex)
   {
      MessageBox.Show("Exception message: " + ex.Message, "DateTimePicker", MessageBoxButtons.OK, MessageBoxIcon.Error);
   }

the above code ends in the following Exception: enter image description here

Be aware. Cheers.

How to convert a DataFrame back to normal RDD in pyspark?

Answer given by kennyut/Kistian works very well but to get exact RDD like output when RDD consist of list of attributes e.g. [1,2,3,4] we can use flatmap command as below,

rdd = df.rdd.flatMap(list)
or 
rdd = df.rdd.flatmap(lambda x: list(x))

CSS3 opacity gradient?

Except using css mask answered by @vals, you can also use transparency gradient background and set background-clip to text.

Create proper gradient:

background: linear-gradient(to bottom, rgba(0, 0, 0, 1) 0%, rgba(0, 0, 0, 0) 100%);

Then clip the backgroud with text:

background-clip: text;
color: transparent;

Demo

https://jsfiddle.net/simonmysun/2h61Ljbn/4/

Tested under Chrome 75 under Windows 10.

Supported platforms:

How to reduce the image file size using PIL

A built-in parameter for saving JPEGs and PNGs is optimize.

 >>> from PIL import Image
 # My image is a 200x374 jpeg that is 102kb large
 >>> foo = Image.open("path\\to\\image.jpg")
 >>> foo.size
  (200,374)
 # I downsize the image with an ANTIALIAS filter (gives the highest quality)
 >>> foo = foo.resize((160,300),Image.ANTIALIAS)
 >>> foo.save("path\\to\\save\\image_scaled.jpg",quality=95)
 # The saved downsized image size is 24.8kb
 >>> foo.save("path\\to\\save\\image_scaled_opt.jpg",optimize=True,quality=95)
 # The saved downsized image size is 22.9kb

The optimize flag will do an extra pass on the image to find a way to reduce its size as much as possible. 1.9kb might not seem like much, but over hundreds/thousands of pictures, it can add up.

Now to try and get it down to 5kb to 10 kb, you can change the quality value in the save options. Using a quality of 85 instead of 95 in this case would yield: Unoptimized: 15.1kb Optimized : 14.3kb Using a quality of 75 (default if argument is left out) would yield: Unoptimized: 11.8kb Optimized : 11.2kb

I prefer quality 85 with optimize because the quality isn't affected much, and the file size is much smaller.

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

To send an mms for Android 4.0 api 14 or higher without permission to write apn settings, you can use this library: Retrieve mnc and mcc codes from android, then call

Carrier c = Carrier.getCarrier(mcc, mnc);
if (c != null) {
    APN a = c.getAPN();
    if (a != null) {
        String mmsc = a.mmsc;
        String mmsproxy = a.proxy; //"" if none
        int mmsport = a.port; //0 if none
    }
}

To use this, add Jsoup and droid prism jar to the build path, and import com.droidprism.*;

document.getElementById replacement in angular4 / typescript?

For Angular 8 or posterior @ViewChild have an additional parameter called opts, which have two properties: read and static, read is optional. You can use it like so:

// ...
@ViewChild('mydiv', { static: false }) public mydiv: ElementRef;

constructor() {
// ...
<div #mydiv></div>

NOTE: Static: false is not required anymore in Angular 9. (just { static: true } when you are going to use that variable inside ngOnInit)

Javascript Error Null is not an Object

I think the error because the elements are undefined ,so you need to add window.onload event which this event will defined your elements when the window is loaded.

window.addEventListener('load',Loaded,false);


    function Loaded(){
    var myButton = document.getElementById("myButton");
    var myTextfield = document.getElementById("myTextfield");

    function greetUser(userName) {
    var greeting = "Hello " + userName + "!";
    document.getElementsByTagName ("h2")[0].innerHTML = greeting;
    }

    myButton.onclick = function() {
    var userName = myTextfield.value;
    greetUser(userName);

    return false;
    }
    }

how to set font size based on container size?

If you want to set the font-size as a percentage of the viewport width, use the vwunit:

#mydiv { font-size: 5vw; }

The other alternative is to use SVG embedded in the HTML. It will just be a few lines. The font-size attribute to the text element will be interpreted as "user units", for instance those the viewport is defined in terms of. So if you define viewport as 0 0 100 100, then a font-size of 1 will be one one-hundredth of the size of the svg element.

And no, there is no way to do this in CSS using calculations. The problem is that percentages used for font-size, including percentages inside a calculation, are interpreted in terms of the inherited font size, not the size of the container. CSS could use a unit called bw (box-width) for this purpose, so you could say div { font-size: 5bw; }, but I've never heard this proposed.

java.lang.NoClassDefFoundError: org/json/JSONObject

No.. It is not proper way. Refer the steps,

For Classpath reference: Right click on project in Eclipse -> Buildpath -> Configure Build path -> Java Build Path (left Pane) -> Libraries(Tab) -> Add External Jars -> Select your jar and select OK.

For Deployment Assembly: Right click on WAR in eclipse-> Buildpath -> Configure Build path -> Deployment Assembly (left Pane) -> Add -> External file system -> Add -> Select your jar -> Add -> Finish.

This is the proper way! Don't forget to remove environment variable. It is not required now.

Try this. Surely it will work. Try to use Maven, it will simplify you task.

Android Push Notifications: Icon not displaying in notification, white square shown instead

Requirements to fix this issue:

  1. Image Format: 32-bit PNG (with alpha)

  2. Image should be Transparent

  3. Transparency Color Index: White (FFFFFF)

Source: http://gr1350.blogspot.com/2017/01/problem-with-setsmallicon.html

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

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

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

How to randomize (shuffle) a JavaScript array?

//one line solution
shuffle = (array) => array.sort(() => Math.random() - 0.5);


//Demo
let arr = [1, 2, 3];
shuffle(arr);
alert(arr);

https://javascript.info/task/shuffle

Math.random() - 0.5 is a random number that may be positive or negative, so the sorting function reorders elements randomly.

PHP Excel Header

Try this

header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header("Content-Disposition: attachment;filename=\"filename.xlsx\"");
header("Cache-Control: max-age=0");

jQuery ajax call to REST service

You are running your HTML from a different host than the host you are requesting. Because of this, you are getting blocked by the same origin policy.

One way around this is to use JSONP. This allows cross-site requests.

In JSON, you are returned:

{a: 5, b: 6}

In JSONP, the JSON is wrapped in a function call, so it becomes a script, and not an object.

callback({a: 5, b: 6})

You need to edit your REST service to accept a parameter called callback, and then to use the value of that parameter as the function name. You should also change the content-type to application/javascript.

For example: http://localhost:8080/restws/json/product/get?callback=process should output:

process({a: 5, b: 6})

In your JavaScript, you will need to tell jQuery to use JSONP. To do this, you need to append ?callback=? to the URL.

$.getJSON("http://localhost:8080/restws/json/product/get?callback=?",
   function(data) {
     alert(data);         
   });

If you use $.ajax, it will auto append the ?callback=? if you tell it to use jsonp.

$.ajax({ 
   type: "GET",
   dataType: "jsonp",
   url: "http://localhost:8080/restws/json/product/get",
   success: function(data){        
     alert(data);
   }
});

Create autoincrement key in Java DB using NetBeans IDE

Found a way of setting auto increment in netbeans 8.0.1 here on StackoOverflow Screenshot below:

see screenshot here

EOL conversion in notepad ++

That functionality is already built into Notepad++. From the "Edit" menu, select "EOL Conversion" -> "UNIX/OSX Format".

screenshot of the option for even quicker finding (or different language versions)

You can also set the default EOL in notepad++ via "Settings" -> "Preferences" -> "New Document/Default Directory" then select "Unix/OSX" under the Format box.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

Do you have access to the command prompt ?

Method 1 : Command Prompt

The specifics of the Java installed on the system can be determined by executing the following command java -version

Method 2 : Folder Structure

In case you do not have access to command prompt then determining the folder where Java.

32 Bit : C:\Program Files (x86)\Java\jdk1.6.0_30

64 Bit : C:\Program Files\Java\jdk1.6.0_25

However during the installation it is possible that the user might change the installation folder.

Method 3 : Registry

You can also see the version installed in registry editor.

  1. Go to registry editor

  2. Edit -> Find

  3. Search for Java. You will get the registry entries for Java.

  4. In the entry with name : DisplayName & DisplayVersion, the installed java version is displayed

substring of an entire column in pandas dataframe

I needed to convert a single column of strings of form nn.n% to float. I needed to remove the % from the element in each row. The attend data frame has two columns.

attend.iloc[:,1:2]=attend.iloc[:,1:2].applymap(lambda x: float(x[:-1]))

Its an extenstion to the original answer. In my case it takes a dataframe and applies a function to each value in a specific column. The function removes the last character and converts the remaining string to float.

html5 audio player - jquery toggle click play/pause?

The reason why your attempt didn't work out is, that you have used a class-selector, which returns a collection of elements, not an (=one!) element, which you need to access the players properties and methods. To make it work there's basically three ways, which have been mentioned, but just for an overview:

Get the element – not a collection – by...

  • Iterating over the colllection and fetching the element with this (like in the accepted answer).

  • Using an id-selector, if available.

  • Getting the element of a collection, by fetching it, via its position in the collection by appending [0] to the selector, which returns the first element of the collection.

Is there a way to create interfaces in ES6 / Node 4?

In comments debiasej wrote the mentioned below article explains more about design patterns (based on interfaces, classes):

http://loredanacirstea.github.io/es6-design-patterns/

Design patterns book in javascript may also be useful for you:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/

Design pattern = classes + interface or multiple inheritance

An example of the factory pattern in ES6 JS (to run: node example.js):

"use strict";

// Types.js - Constructors used behind the scenes

// A constructor for defining new cars
class Car {
  constructor(options){
    console.log("Creating Car...\n");
    // some defaults
    this.doors = options.doors || 4;
    this.state = options.state || "brand new";
    this.color = options.color || "silver";
  }
}

// A constructor for defining new trucks
class Truck {
  constructor(options){
    console.log("Creating Truck...\n");
    this.state = options.state || "used";
    this.wheelSize = options.wheelSize || "large";
    this.color = options.color || "blue";
  }
}


// FactoryExample.js

// Define a skeleton vehicle factory
class VehicleFactory {}

// Define the prototypes and utilities for this factory

// Our default vehicleClass is Car
VehicleFactory.prototype.vehicleClass = Car;

// Our Factory method for creating new Vehicle instances
VehicleFactory.prototype.createVehicle = function ( options ) {

  switch(options.vehicleType){
    case "car":
      this.vehicleClass = Car;
      break;
    case "truck":
      this.vehicleClass = Truck;
      break;
    //defaults to VehicleFactory.prototype.vehicleClass (Car)
  }

  return new this.vehicleClass( options );

};

// Create an instance of our factory that makes cars
var carFactory = new VehicleFactory();
var car = carFactory.createVehicle( {
            vehicleType: "car",
            color: "yellow",
            doors: 6 } );

// Test to confirm our car was created using the vehicleClass/prototype Car

// Outputs: true
console.log( car instanceof Car );

// Outputs: Car object of color "yellow", doors: 6 in a "brand new" state
console.log( car );

var movingTruck = carFactory.createVehicle( {
                      vehicleType: "truck",
                      state: "like new",
                      color: "red",
                      wheelSize: "small" } );

// Test to confirm our truck was created with the vehicleClass/prototype Truck

// Outputs: true
console.log( movingTruck instanceof Truck );

// Outputs: Truck object of color "red", a "like new" state
// and a "small" wheelSize
console.log( movingTruck );

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

<table>
     <ng-container *ngFor="let group of groups">
         <tr><td><h2>{{group.name}}</h2></td></tr>
         <tr *ngFor="let item of group.items"><td>{{item}}</td></tr>
     </ng-container>
</table>

How to code a modulo (%) operator in C/C++/Obj-C that handles negative numbers

Here's a new answer to an old question, based on this Microsoft Research paper and references therein.

Note that from C11 and C++11 onwards, the semantics of div has become truncation towards zero (see [expr.mul]/4). Furthermore, for D divided by d, C++11 guarantees the following about the quotient qT and remainder rT

auto const qT = D / d;
auto const rT = D % d;
assert(D == d * qT + rT);
assert(abs(rT) < abs(d));
assert(signum(rT) == signum(D) || rT == 0);

where signum maps to -1, 0, +1, depending on whether its argument is <, ==, > than 0 (see this Q&A for source code).

With truncated division, the sign of the remainder is equal to the sign of the dividend D, i.e. -1 % 8 == -1. C++11 also provides a std::div function that returns a struct with members quot and rem according to truncated division.

There are other definitions possible, e.g. so-called floored division can be defined in terms of the builtin truncated division

auto const I = signum(rT) == -signum(d) ? 1 : 0;
auto const qF = qT - I;
auto const rF = rT + I * d;
assert(D == d * qF + rF);
assert(abs(rF) < abs(d));
assert(signum(rF) == signum(d));

With floored division, the sign of the remainder is equal to the sign of the divisor d. In languages such as Haskell and Oberon, there are builtin operators for floored division. In C++, you'd need to write a function using the above definitions.

Yet another way is Euclidean division, which can also be defined in terms of the builtin truncated division

auto const I = rT >= 0 ? 0 : (d > 0 ? 1 : -1);
auto const qE = qT - I;
auto const rE = rT + I * d;
assert(D == d * qE + rE);
assert(abs(rE) < abs(d));
assert(signum(rE) >= 0);

With Euclidean division, the sign of the remainder is always non-negative.

Comparing two strings, ignoring case in C#

If you're looking for efficiency, use this:

string.Equals(val, "astringvalue", StringComparison.OrdinalIgnoreCase)

Ordinal comparisons can be significantly faster than culture-aware comparisons.

ToLowerCase can be the better option if you're doing a lot of comparisons against the same string, however.

As with any performance optimization: measure it, then decide!

Creating a Custom Event

Yes you can create events on objects, here is an example;

public class Foo
{
    public delegate void MyEvent(object sender, object param);
    event MyEvent OnMyEvent;

    public Foo()
    {
        this.OnMyEvent += new MyEvent(Foo_OnMyEvent);
    }

    void Foo_OnMyEvent(object sender, object param)
    {
        if (this.OnMyEvent != null)
        {
            //do something
        }
    }



    void RaiseEvent()
    {
        object param = new object();
        this.OnMyEvent(this,param);
    }
}

How to find a value in an array and remove it by using PHP array functions?

You can use array_filter to filter out elements of an array based on a callback function. The callback function takes each element of the array as an argument and you simply return false if that element should be removed. This also has the benefit of removing duplicate values since it scans the entire array.

You can use it like this:

$myArray = array('apple', 'orange', 'banana', 'plum', 'banana');
$output = array_filter($myArray, function($value) { return $value !== 'banana'; });
// content of $output after previous line:
// $output = array('apple', 'orange', 'plum');

And if you want to re-index the array, you can pass the result to array_values like this:

$output = array_values($output);

Inserting data to table (mysqli insert)

Okay, of course the question has been answered, but no-one seems to notice the third line of your code. It continuosly bugged me.

    <?php
    mysqli_connect("localhost","root","","web_table");
    mysql_select_db("web_table") or die(mysql_error());

for some reason, you made a mysqli connection to server, but you are trying to make a mysql connection to database.To get going, rather use

       $link = mysqli_connect("localhost","root","","web_table");
       mysqli_select_db ($link , "web_table" ) or die.....

or for where i began

     <?php $connection = mysqli_connect("localhost","root","","web_table");       
      global $connection; // global connection to databases - kill it once you're done

or just query with a $connection parameter as the other argument like above. Get rid of that third line.

What is :: (double colon) in Python when subscripting sequences?

When slicing in Python the third parameter is the step. As others mentioned, see Extended Slices for a nice overview.

With this knowledge, [::3] just means that you have not specified any start or end indices for your slice. Since you have specified a step, 3, this will take every third entry of something starting at the first index. For example:

>>> '123123123'[::3]
'111'

AssertContains on strings in jUnit

It's too late, but just to update I got it done with below syntax

import org.hamcrest.core.StringContains;
import org.junit.Assert;

Assert.assertThat("this contains test", StringContains.containsString("test"));

Can a JSON value contain a multiline string

I believe it depends on what json interpreter you're using... in plain javascript you could use line terminators

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : "this is a very long line which is not easily readble. \
                  so i would like to write it in multiple lines. \
                  but, i do NOT require any new lines in the output."
    }
  }
}

How do I use method overloading in Python?

You can't, never need to and don't really want to.

In Python, everything is an object. Classes are things, so they are objects. So are methods.

There is an object called A which is a class. It has an attribute called stackoverflow. It can only have one such attribute.

When you write def stackoverflow(...): ..., what happens is that you create an object which is the method, and assign it to the stackoverflow attribute of A. If you write two definitions, the second one replaces the first, the same way that assignment always behaves.

You furthermore do not want to write code that does the wilder of the sorts of things that overloading is sometimes used for. That's not how the language works.

Instead of trying to define a separate function for each type of thing you could be given (which makes little sense since you don't specify types for function parameters anyway), stop worrying about what things are and start thinking about what they can do.

You not only can't write a separate one to handle a tuple vs. a list, but also don't want or need to.

All you do is take advantage of the fact that they are both, for example, iterable (i.e. you can write for element in container:). (The fact that they aren't directly related by inheritance is irrelevant.)

Array and string offset access syntax with curly braces is deprecated

It's really simple to fix the issue, however keep in mind that you should fork and commit your changes for each library you are using in their repositories to help others as well.

Let's say you have something like this in your code:

$str = "test";
echo($str{0});

since PHP 7.4 curly braces method to get individual characters inside a string has been deprecated, so change the above syntax into this:

$str = "test";
echo($str[0]);

Fixing the code in the question will look something like this:

public function getRecordID(string $zoneID, string $type = '', string $name = ''): string
{
    $records = $this->listRecords($zoneID, $type, $name);
    if (isset($records->result[0]->id)) {
        return $records->result[0]->id;
    }
    return false;
}

Split a string by another string in C#

In order to split by a string you'll have to use the string array overload.

string data = "THExxQUICKxxBROWNxxFOX";

return data.Split(new string[] { "xx" }, StringSplitOptions.None);

Insert current date/time using now() in a field using MySQL/PHP

The only reason I can think of is you are adding it as string 'now()', not function call now().
Or whatever else typo.

SELECT NOW();

to see if it returns correct value?

CSS full screen div with text in the middle

text-align: center will center it horizontally as for vertically put it in a span and give it a css of margin:auto 0; (you will probably also have to give the span a display: block property)

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

How to parse JSON in Scala using standard Scala classes?

I like @huynhjl's answer, it led me down the right path. However, it isn't great at handling error conditions. If the desired node does not exist, you get a cast exception. I've adapted this slightly to make use of Option to better handle this.

class CC[T] {
  def unapply(a:Option[Any]):Option[T] = if (a.isEmpty) {
    None
  } else {
    Some(a.get.asInstanceOf[T])
  }
}

object M extends CC[Map[String, Any]]
object L extends CC[List[Any]]
object S extends CC[String]
object D extends CC[Double]
object B extends CC[Boolean]

for {
  M(map) <- List(JSON.parseFull(jsonString))
  L(languages) = map.get("languages")
  language <- languages
  M(lang) = Some(language)
  S(name) = lang.get("name")
  B(active) = lang.get("is_active")
  D(completeness) = lang.get("completeness")
} yield {
  (name, active, completeness)
}

Of course, this doesn't handle errors so much as avoid them. This will yield an empty list if any of the json nodes are missing. You can use a match to check for the presence of a node before acting...

for {
  M(map) <- Some(JSON.parseFull(jsonString))
} yield {
  map.get("languages") match {
    case L(languages) => {
      for {
        language <- languages
        M(lang) = Some(language)
        S(name) = lang.get("name")
        B(active) = lang.get("is_active")
        D(completeness) = lang.get("completeness")
      } yield {
        (name, active, completeness)
      }        
    }
    case None => "bad json"
  }
}

How can I add 1 day to current date?

currentDay = '2019-12-06';
currentDay = new Date(currentDay).add(Date.DAY, +1).format('Y-m-d');

How can I wait for a thread to finish with .NET?

I can see five options available:

1. Thread.Join

As with Mitch's answer. But this will block your UI thread, however you get a Timeout built in for you.


2. Use a WaitHandle

ManualResetEvent is a WaitHandle as jrista suggested.

One thing to note is if you want to wait for multiple threads: WaitHandle.WaitAll() won't work by default, as it needs an MTA thread. You can get around this by marking your Main() method with MTAThread - however this blocks your message pump and isn't recommended from what I've read.


3. Fire an event

See this page by Jon Skeet about events and multi-threading. It's possible that an event can become unsubcribed between the if and the EventName(this,EventArgs.Empty) - it's happened to me before.

(Hopefully these compile, I haven't tried)

public class Form1 : Form
{
    int _count;

    void ButtonClick(object sender, EventArgs e)
    {
        ThreadWorker worker = new ThreadWorker();
        worker.ThreadDone += HandleThreadDone;

        Thread thread1 = new Thread(worker.Run);
        thread1.Start();

        _count = 1;
    }

    void HandleThreadDone(object sender, EventArgs e)
    {
        // You should get the idea this is just an example
        if (_count == 1)
        {
            ThreadWorker worker = new ThreadWorker();
            worker.ThreadDone += HandleThreadDone;

            Thread thread2 = new Thread(worker.Run);
            thread2.Start();

            _count++;
        }
    }

    class ThreadWorker
    {
        public event EventHandler ThreadDone;

        public void Run()
        {
            // Do a task

            if (ThreadDone != null)
                ThreadDone(this, EventArgs.Empty);
        }
    }
}

4. Use a delegate

public class Form1 : Form
{
    int _count;

    void ButtonClick(object sender, EventArgs e)
    {
        ThreadWorker worker = new ThreadWorker();

        Thread thread1 = new Thread(worker.Run);
        thread1.Start(HandleThreadDone);

        _count = 1;
    }

    void HandleThreadDone()
    {
        // As before - just a simple example
        if (_count == 1)
        {
            ThreadWorker worker = new ThreadWorker();

            Thread thread2 = new Thread(worker.Run);
            thread2.Start(HandleThreadDone);

            _count++;
        }
    }

    class ThreadWorker
    {
        // Switch to your favourite Action<T> or Func<T>
        public void Run(object state)
        {
            // Do a task

            Action completeAction = (Action)state;
            completeAction.Invoke();
        }
    }
}

If you do use the _count method, it might be an idea (to be safe) to increment it using

Interlocked.Increment(ref _count)

I'd be interested to know the difference between using delegates and events for thread notification, the only difference I know are events are called synchronously.


5. Do it asynchronously instead

The answer to this question has a very clear description of your options with this method.


Delegate/Events on the wrong thread

The event/delegate way of doing things will mean your event handler method is on thread1/thread2 not the main UI thread, so you will need to switch back right at the top of the HandleThreadDone methods:

// Delegate example
if (InvokeRequired)
{
    Invoke(new Action(HandleThreadDone));
    return;
}

Making a WinForms TextBox behave like your browser's address bar

This is working for me in .NET 2005 -

    ' * if the mouse button is down, do not run the select all.
    If MouseButtons = Windows.Forms.MouseButtons.Left Then
        Exit Sub
    End If

 ' * OTHERWISE INVOKE THE SELECT ALL AS DISCUSSED.

How to redirect and append both stdout and stderr to a file with Bash?

cmd >>file.txt 2>&1

Bash executes the redirects from left to right as follows:

  1. >>file.txt: Open file.txt in append mode and redirect stdout there.
  2. 2>&1: Redirect stderr to "where stdout is currently going". In this case, that is a file opened in append mode. In other words, the &1 reuses the file descriptor which stdout currently uses.

Background blur with CSS

In recent versions of major browsers you can use backdrop-filter property.

HTML

<div>backdrop blur</div>

CSS

div {
    -webkit-backdrop-filter: blur(10px);
    backdrop-filter: blur(10px);
}

or if you need different background color for browsers without support:

div {
    background-color: rgba(255, 255, 255, 0.9);
}

@supports (-webkit-backdrop-filter: none) or (backdrop-filter: none) {
    div {
        -webkit-backdrop-filter: blur(10px);
        backdrop-filter: blur(10px);
        background-color: rgba(255, 255, 255, 0.5);  
    }
}

Demo: JSFiddle

Docs: Mozilla Developer: backdrop-filter

Is it for me?: CanIUse

Reading and displaying data from a .txt file

public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

MySQL Update Inner Join tables query

The SET clause should come after the table specification.

UPDATE business AS b
INNER JOIN business_geocode g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

Put a Delay in Javascript

I just had an issue where I needed to solve this properly.

Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.

the code I ended up with:

$.each(messages, function(idx, el){
  window.setTimeout(function(){
    doSomething(el);
  },Math.floor(idx+1)*10000);
});

Basically, think of the timeouts as a "timeline" of your script.

This is what we WANT to code:

DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();

This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:

At Runtime 0    : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();

Hope this helps.

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

SUM of grouped COUNT in SQL Query

You can use ROLLUP

select nvl(name, 'SUM'), count(*)
from table
group by rollup(name)

.datepicker('setdate') issues, in jQuery

Try changing it to:

queryDate = '2009-11-01';
$('#datePicker').datepicker({defaultDate: new Date (queryDate)});

Bash script plugin for Eclipse?

It works for me in Oxygen.

1) Go to Help > Eclipse Marketplace... and search for "DLTK". You'll find something like "Shell Script (DLTK) 5.8.0". Install it and reboot Eclipse.

(Or drag'n'drop "Install" button from this web page to your Eclipse: https://marketplace.eclipse.org/content/shell-script-dltk)

Shell Script (DLTK)

2) Right-click on the shell/batch file in Project Explorer > Open With > Other... and select Shell Script Editor. You can also associate the editor with all files of that extension.

Shell script editor

PHP: if !empty & empty

Here's a compact way to do something different in all four cases:

if(empty($youtube)) {
    if(empty($link)) {
        # both empty
    } else {
        # only $youtube not empty
    }
} else {
    if(empty($link)) {
        # only $link empty
    } else {
        # both not empty
    }
}

If you want to use an expression instead, you can use ?: instead:

echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
                     : ( empty($link) ? 'only $link empty' : 'both not empty' );

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

How do I get the current date and time in PHP?

You can either use the $_SERVER['REQUEST_TIME'] variable (available since PHP 5.1.0) or the time() function to get the current Unix timestamp.

How to generate different random numbers in a loop in C++?

The way the function rand() works is that every time you call it, it generates a random number. In your code, you've called it once and stored it into the variable random_x. To get your desired random numbers instead of storing it into a variable, just call the function like this:

for (int t=0;t<10;t++)
{
    cout << "\nRandom X = " << rand() % 100;
}

What is the best way to modify a list in a 'foreach' loop?

Here's how you can do that (quick and dirty solution. If you really need this kind of behavior, you should either reconsider your design or override all IList<T> members and aggregate the source list):

using System;
using System.Collections.Generic;

namespace ConsoleApplication3
{
    public class ModifiableList<T> : List<T>
    {
        private readonly IList<T> pendingAdditions = new List<T>();
        private int activeEnumerators = 0;

        public ModifiableList(IEnumerable<T> collection) : base(collection)
        {
        }

        public ModifiableList()
        {
        }

        public new void Add(T t)
        {
            if(activeEnumerators == 0)
                base.Add(t);
            else
                pendingAdditions.Add(t);
        }

        public new IEnumerator<T> GetEnumerator()
        {
            ++activeEnumerators;

            foreach(T t in ((IList<T>)this))
                yield return t;

            --activeEnumerators;

            AddRange(pendingAdditions);
            pendingAdditions.Clear();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ModifiableList<int> ints = new ModifiableList<int>(new int[] { 2, 4, 6, 8 });

            foreach(int i in ints)
                ints.Add(i * 2);

            foreach(int i in ints)
                Console.WriteLine(i * 2);
        }
    }
}

jQuery iframe load() event?

You may use the jquery's Contents method to get the content of the iframe.

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

WPF Datagrid Get Selected Cell Value

Ok after doing reverse engineering and a little pixie dust of reflection, one can do this operation on SelectedCells (at any point) to get all (regardless of selected on one row or many rows) the data from one to many selected cells:

MessageBox.Show(

string.Join(", ", myGrid.SelectedCells
                        .Select(cl => cl.Item.GetType()
                                             .GetProperty(cl.Column.SortMemberPath)
                                             .GetValue(cl.Item, null)))

               );

I tried this on text (string) fields only though a DateTime field should return a value the initiate ToString(). Also note that SortMemberPath is not the same as Header so that should always provide the proper property to reflect off of.

<DataGrid ItemsSource="{Binding MyData}"                      
          AutoGenerateColumns="True"
          Name="myGrid"
          IsReadOnly="True"
          SelectionUnit="Cell"
          SelectionMode="Extended">

How to compile python script to binary executable

Or use PyInstaller as an alternative to py2exe. Here is a good starting point. PyInstaller also lets you create executables for linux and mac...

Here is how one could fairly easily use PyInstaller to solve the issue at hand:

pyinstaller oldlogs.py

From the tool's documentation:

PyInstaller analyzes myscript.py and:

  • Writes myscript.spec in the same folder as the script.
  • Creates a folder build in the same folder as the script if it does not exist.
  • Writes some log files and working files in the build folder.
  • Creates a folder dist in the same folder as the script if it does not exist.
  • Writes the myscript executable folder in the dist folder.

In the dist folder you find the bundled app you distribute to your users.

How does "make" app know default target to build if no target is specified?

To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:

.DEFAULT_GOAL := mytarget

mytarget will now be the target that is run if "make" is executed and no target is specified.

If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:

.PHONY: default
default: mytarget ;

References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html

Accessing UI (Main) Thread safely in WPF

Use [Dispatcher.Invoke(DispatcherPriority, Delegate)] to change the UI from another thread or from background.

Step 1. Use the following namespaces

using System.Windows;
using System.Threading;
using System.Windows.Threading;

Step 2. Put the following line where you need to update UI

Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate
{
    //Update UI here
}));

Syntax

[BrowsableAttribute(false)]
public object Invoke(
  DispatcherPriority priority,
  Delegate method
)

Parameters

priority

Type: System.Windows.Threading.DispatcherPriority

The priority, relative to the other pending operations in the Dispatcher event queue, the specified method is invoked.

method

Type: System.Delegate

A delegate to a method that takes no arguments, which is pushed onto the Dispatcher event queue.

Return Value

Type: System.Object

The return value from the delegate being invoked or null if the delegate has no return value.

Version Information

Available since .NET Framework 3.0

How to add line break for UILabel?

Just using label.numberOfLines = 0;

Internet Access in Ubuntu on VirtualBox

I could get away with the following solution (works with Ubuntu 14 guest VM on Windows 7 host or Ubuntu 9.10 Casper guest VM on host Windows XP x86):

  1. Go to network connections -> Virtual Box Host-Only Network -> Select "Properties"
  2. Check VirtualBox Bridged Networking Driver
  3. Come to VirtualBox Manager, choose the network adapter as Bridged Adapter and Name to the device in Step #1.
  4. Restart the VM.

Angular: How to update queryParams without changing route

I ended up combining urlTree with location.go

const urlTree = this.router.createUrlTree([], {
       relativeTo: this.route,
       queryParams: {
           newParam: myNewParam,
       },
       queryParamsHandling: 'merge',
    });

    this.location.go(urlTree.toString());

Not sure if toString can cause problems, but unfortunately location.go, seems to be string based.

Cassandra cqlsh - connection refused

Check for correct IP address in the cassandra.yaml file. Majority of times the error is due to incorrect IP address of your system also the username and password too.

After doing so initiate cqlsh by the command :-

cqlsh 10.31.79.1 -u cassandra -p cassandra

How to escape single quotes within single quoted strings

How to escape single quotes (') and double quotes (") with hex and octal chars

If using something like echo, I've had some really complicated and really weird and hard-to-escape (think: very nested) cases where the only thing I could get to work was using octal or hex codes!

Here are some examples:

1. Single quote example, where ' is escaped with hex \x27 or octal \047 (its corresponding ASCII code):

# 1. hex
$ echo -e "Let\x27s get coding!"
Let's get coding!

# 2. octal
$ echo -e "Let\047s get coding!"
Let's get coding!

2. Double quote example, where " is escaped with hex \x22 or octal \042 (its corresponding ASCII code).

Note: bash is nuts! Sometimes even the ! char has special meaning, and must either be removed from within the double quotes and then escaped "like this"\! or put entirely within single quotes 'like this!', rather than within double quotes.

# 1. hex; escape `!` by removing it from within the double quotes 
# and escaping it with `\!`
$ echo -e "She said, \x22Let\x27s get coding"\!"\x22"
She said, "Let's get coding!"

# OR put it all within single quotes:
$ echo -e 'She said, \x22Let\x27s get coding!\x22'
She said, "Let's get coding!"


# 2. octal; escape `!` by removing it from within the double quotes 
$ echo -e "She said, \042Let\047s get coding"\!"\042"
She said, "Let's get coding!"

# OR put it all within single quotes:
$ echo -e 'She said, \042Let\047s get coding!\042'
She said, "Let's get coding!"


# 3. mixed hex and octal, just for fun
# escape `!` by removing it from within the double quotes when it is followed by
# another escape sequence
$ echo -e "She said, \x22Let\047s get coding! It\x27s waaay past time to begin"\!"\042"
She said, "Let's get coding! It's waaay past time to begin!"

# OR put it all within single quotes:
$ echo -e 'She said, \x22Let\047s get coding! It\x27s waaay past time to begin!\042'
She said, "Let's get coding! It's waaay past time to begin!"

Note that if you don't properly escape !, when needed, as I've shown two ways to do above, you'll get some weird errors, like this:

$ echo -e "She said, \x22Let\047s get coding! It\x27s waaay past time to begin!\042"
bash: !\042: event not found

OR:

$ echo -e "She said, \x22Let\x27s get coding!\x22"
bash: !\x22: event not found

References:

  1. https://en.wikipedia.org/wiki/ASCII#Printable_characters
  2. https://serverfault.com/questions/208265/what-is-bash-event-not-found/208266#208266
  3. See also my other answer here: How do I write non-ASCII characters using echo?.

How is TeamViewer so fast?

The most fundamental thing here probably is that you don't want to transmit static images but only changes to the images, which essentially is analogous to video stream.

My best guess is some very efficient (and heavily specialized and optimized) motion compensation algorithm, because most of the actual change in generic desktop usage is linear movement of elements (scrolling text, moving windows, etc. opposed to transformation of elements).

The DirectX 3D performance of 1 FPS seems to confirm my guess to some extent.

Proxy Basic Authentication in C#: HTTP 407 error

This method may avoid the need to hard code or configure proxy credentials, which may be desirable.

Put this in your application configuration file - probably app.config. Visual Studio will rename it to yourappname.exe.config on build, and it will end up next to your executable. If you don't have an application configuration file, just add one using Add New Item in Visual Studio.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.net>
    <defaultProxy useDefaultCredentials="true" />
  </system.net>
</configuration>

static files with express.js

If you have this setup

/app
   /public/index.html
   /media

Then this should get what you wanted

var express = require('express');
//var server = express.createServer();
// express.createServer()  is deprecated. 
var server = express(); // better instead
server.configure(function(){
  server.use('/media', express.static(__dirname + '/media'));
  server.use(express.static(__dirname + '/public'));
});

server.listen(3000);

The trick is leaving this line as last fallback

  server.use(express.static(__dirname + '/public'));

As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.

For example this line shows that index.html is supported https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140

How do I open a URL from C++?

Your question may mean two different things:

1.) Open a web page with a browser.

#include <windows.h>
#include <shellapi.h>
...
ShellExecute(0, 0, L"http://www.google.com", 0, 0 , SW_SHOW );

This should work, it opens the file with the associated program. Should open the browser, which is usually the default web browser.


2.) Get the code of a webpage and you will render it yourself or do some other thing. For this I recommend to read this or/and this.


I hope it's at least a little helpful.

EDIT: Did not notice, what you are asking for UNIX, this only work on Windows.

Trigger change event <select> using jquery

Use val() to change to the value (not the text) and trigger() to manually fire the event.

The change event handler must be declared before the trigger.

Here's a sample

$('.check').change(function(){
  var data= $(this).val();
  alert(data);            
});

$('.check')
    .val('two')
    .trigger('change');

How do I fill arrays in Java?

Arrays.fill(). The method is overloaded for different data types, and there is even a variation that fills only a specified range of indices.

In nodeJs is there a way to loop through an array without using array size?

In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of. Take this examples:

_x000D_
_x000D_
'use strict';_x000D_
_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
    output;_x000D_
_x000D_
arr[6] = 'five';_x000D_
_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
    output += val + ' ';_x000D_
});_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
    output += arr[i] + ' ';_x000D_
}_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
    output += val + ' ';_x000D_
};_x000D_
console.log(output);
_x000D_
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->_x000D_
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>
_x000D_
_x000D_
_x000D_

All array methods which you can use to iterate safely over dense arrays use the length property of an object created by calling ToObject internaly. See for instance the algorithm used in the forEach method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18 However in es6, you can use for...of safely for iterating over sparse arrays.

See also Are Javascript arrays sparse?.

HTML5: Slider with two inputs possible?

Coming late, but noUiSlider avoids having a jQuery-ui dependency, which the accepted answer does not. Its only "caveat" is IE support is for IE9 and newer, if legacy IE is a deal breaker for you.

It's also free, open source and can be used in commercial projects without restrictions.

Installation: Download noUiSlider, extract the CSS and JS file somewhere in your site file system, and then link to the CSS from head and to JS from body:

<!-- In <head> -->
<link href="nouislider.min.css" rel="stylesheet">

<!-- In <body> -->
<script src="nouislider.min.js"></script>

Example usage: Creates a slider which goes from 0 to 100, and starts set to 20-80.

HTML:

<div id="slider">
</div>

JS:

var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [20, 80],
    connect: true,
    range: {
        'min': 0,
        'max': 100
    }
});

scroll image with continuous scrolling using marquee tag

I think you set the marquee width related to 5 images total width. It works fine

ex: <marquee style="width:700px"></marquee>

What's the difference between size_t and int in C++?

From the friendly Wikipedia:

The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.

The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.

Also, check Why size_t matters

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

For rails6, I was facing the same problem, as I was missing following files, once I added them, the issue resolved:

1. config/master.key
2. config/credentials.yml.enc

Make sure you have this files.!!!

How do I get git to default to ssh and not https for new repositories

SSH File

~/.ssh/config file
Host *
    StrictHostKeyChecking no
    UserKnownHostsFile=/dev/null
    LogLevel QUIET
    ConnectTimeout=10
Host github.com
        User git
        AddKeystoAgent yes
        UseKeychain yes
        Identityfile ~/github_rsa

Edit reponame/.git/config

[remote "origin"]
        url = [email protected]:username/repo.git

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

How do I shut down a python simpleHTTPserver?

It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.

Or just run it in the foreground as suggested and kill it with control c

Confirm deletion in modal / dialog using Twitter Bootstrap?

http://bootboxjs.com/ - latest works with Bootstrap 3.0.0

The simplest possible example:

bootbox.alert("Hello world!"); 

From the site:

The library exposes three methods designed to mimic their native JavaScript equivalents. Their exact method signatures are flexible as each can take various parameters to customise labels and specify defaults, but they are most commonly called like so:

bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)

Here's a snippet of it in action (click "Run code snippet" below):

_x000D_
_x000D_
$(function() {_x000D_
  bootbox.alert("Hello world!");_x000D_
});
_x000D_
<!-- required includes -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<!-- bootbox.js at 4.4.0 -->_x000D_
<script src="https://rawgit.com/makeusabrew/bootbox/f3a04a57877cab071738de558581fbc91812dce9/bootbox.js"></script>
_x000D_
_x000D_
_x000D_